aboutsummaryrefslogtreecommitdiffstats
path: root/Part 1/Good Code/midpoint.m
diff options
context:
space:
mode:
Diffstat (limited to 'Part 1/Good Code/midpoint.m')
-rw-r--r--Part 1/Good Code/midpoint.m22
1 files changed, 22 insertions, 0 deletions
diff --git a/Part 1/Good Code/midpoint.m b/Part 1/Good Code/midpoint.m
new file mode 100644
index 0000000..000f103
--- /dev/null
+++ b/Part 1/Good Code/midpoint.m
@@ -0,0 +1,22 @@
+function [ x, y ] = midpoint( f, t0, tfinal, y0, h)
+
+%calculate number of steps
+N = round((tfinal - t0) / h);
+%initialise the array
+ya = zeros(1,N);
+ta = zeros(1,N);
+ya(1) = y0;
+ta(1) = t0;
+
+for i = 1 : N - 1
+ ta(i+1) = ta(i) + h;
+ halfstep = ta(i) + 1 * h / 2;
+ gradient1 = f(ta(i), ya(i));
+ ypredict = ya(i) + 0.5 * h * gradient1;
+ gradient2 = f(halfstep, ypredict);
+ ya(i+1) = ya(i) + h * gradient2;
+end
+x = ta;
+y = ya;
+
+