Răsfoiți Sursa

Seperate out .m functions

Pjotir 1 lună în urmă
părinte
comite
57d69d74ab

+ 7 - 0
Homework2/functions/approx_pi.m

@@ -0,0 +1,7 @@
+function r = approx_pi(steps)
+    total = 0;
+    for k = 0:steps
+        total = total + ((-1)^k) / ((2*k+1)*3^k);
+    end
+    r = 2 * sqrt(3) * total;
+end

+ 8 - 0
Homework2/functions/calc_path.m

@@ -0,0 +1,8 @@
+% a : vertical distance from town A to the river
+% b : vertical distance from town B to the river
+% w : width of the river
+% d : horizontal distance from town A to town B
+% x : horizontal distance of the bridge from town A
+function path_distance = calc_path(a, b, w, d, x)
+    path_distance = sqrt(x^2+a^2) + sqrt((d-x)^2+b^2) + w;
+end

BIN
Homework2/octave-workspace


+ 5 - 13
Homework2/problem2_piformula.m

@@ -1,14 +1,6 @@
-function main()
-    fprintf("%.15f\n", approx_pi(1));
-    fprintf("%.15f\n", approx_pi(3));
-    fprintf("%.15f\n", approx_pi(5));
-    fprintf("%.15f\n", approx_pi(10));
-end
+addpath("functions");
 
-function r = approx_pi(steps)
-    total = 0;
-    for k = 0:steps
-        total = total + ((-1)^k) / ((2*k+1)*3^k);
-    end
-    r = 2 * sqrt(3) * total;
-end
+fprintf("%.15f\n", approx_pi(1));
+fprintf("%.15f\n", approx_pi(3));
+fprintf("%.15f\n", approx_pi(5));
+fprintf("%.15f\n", approx_pi(10));

+ 5 - 14
Homework2/problem3_shortestpath.m

@@ -1,16 +1,7 @@
-function main()
-    % Constants for test
-    a = 3; b = 5; d = 12; w = 1;
+addpath("functions");
 
-    % Testing all possible bridge positions (0 to d)
-    [bridge_pos, path_distance] = fminbnd(@(x) calc_path(a,b,w,d,x), 0, d)
-end
+% Constants for test
+a = 3; b = 5; d = 12; w = 1;
 
-% a : vertical distance from town A to the river
-% b : vertical distance from town B to the river
-% w : width of the river
-% d : horizontal distance from town A to town B
-% x : horizontal distance of the bridge from town A
-function path_distance = calc_path(a, b, w, d, x)
-    path_distance = sqrt(x^2+a^2) + sqrt((d-x)^2+b^2) + w;
-end
+% Testing all possible bridge positions (0 to d)
+[bridge_pos, path_distance] = fminbnd(@(x) calc_path(a,b,w,d,x), 0, d)

+ 14 - 0
ode45_practice.m

@@ -0,0 +1,14 @@
+% First order ODE
+f = @(t, y) 3*exp(-0.05*t).*cos(2*t) - 0.4*y - 0.05*y.^3;
+y0 = 0;
+time = [0, 30];
+[t, v] = ode45(f, time, y0);
+plot(t, v);
+
+% Second order ODE
+f = @(t, y) [y(2), 2*cos(1.2*t.^1.5) - 0.5*y(2) - 4*y(1) - 0.2*y(1).^3];
+y0 = [1, 0];
+t = [0, 20];
+[t, y] = ode45(f, t, y0);
+
+plot(t, y(:, 1), 'LineWidth', 4);