Heun's method program code
Show older comments
Hello,
I am trying to program a script to solve a second order ODE using the Heun's method as required for a project of mine. I cannot use ODE45 or any of the like. Here is the code I have written so far:
function project2()
h = 1/32; %STEP SIZE
z0 = [0, 2.4]; %INITIAL Y VALUE
t=0:h:20;
t(1)=0;
z(1)=0;
n=1;
while t < 6 %TIME INTERVAL
t(n+1) = t(n) + h;
k1 = f(t(n), z(n));
k2 = f(t(n)+h, z(n)+k1*h);
z(n+1) = z(n) + (h/2)*(k1+k2);
n = n+1;
end
plot(t,z,'g-','LineWidth',1)
function dzdt = f(t,z)
w = 2;
G = 9.81;
z1=z(1); % get z1
z2=z(2); % get z2
dzdt = [z2 ; -G*sin(2*t)+w^2*z1;];
I run this and get no errors, but the lot comes up completely empty. Please help!
Answers (2)
Geoff Hayes
on 23 Jul 2017
Sean - the problem is with your while loop condition
while t < 6
At this point, t is an array of 641 elements because of the line
t=0:h:20;
It is unclear why you populate this array as such (with the step size of h) and then reset the first element to 0
t(1)=0;
and then reset every element of t on the first line of the while loop body. You don't need to do this if t has already been initialized correctly.
Instead of the above code, try using a for loop with n incrementing on each iteration of the loop. Perhaps
function project2()
h = 1/32; %STEP SIZE
z0 = [0, 2.4]; %INITIAL Y VALUE
t=0:h:20;
z(1)=0;
for n=1:length(t)-1
k1 = f(t(n), z(n));
k2 = f(t(n)+h, z(n)+k1*h);
z(n+1) = z(n) + (h/2)*(k1+k2);
end
The above code will now call your f function, but there is a bug with that too
function dzdt = f(t,z)
w = 2;
G = 9.81;
z1=z(1); % get z1
z2=z(2); % get z2
dzdt = [z2 ; -G*sin(2*t)+w^2*z1;];
The code for this function assumes that z is two dimensional...but you only supply a scalar when calling it from within your loop
k1 = f(t(n), z(n));
k2 = f(t(n)+h, z(n)+k1*h);
What should you be supplying to this function f? z(n-1:n) to get the two elements? Please clarify.
3 Comments
Sean Malinowski
on 23 Jul 2017
Geoff Hayes
on 23 Jul 2017
Sean - can you provide some details on your f function? What are you basing it on?
Sean Malinowski
on 23 Jul 2017
ayman alarousi
on 8 Aug 2022
0 votes
i want mathlab codes for second order ODE
midpoint, Runge-Kutta method
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!