System of Equations with Runge Kutta
1 view (last 30 days)
Show older comments
Hi, I have a couple questions about solving the second order DE y"=-y with initial conditions y(0)=0 and y'(0)=1. I know the answer with pen and paper is just the sin function. So I wrote this code and it's not quite doing what I want so if someone could comment on it I would much appreciate it!
function rungekutte2(c, d, h, t0, T)
t = t0:h:T;
yp = zeros(size(t));
zp = zeros(size(t));
yp(1) = c;
zp(1) = d;
for i = 1:(length(t)-1)
k1 = h*f(yp(i),zp(i));
l1 = h*g(yp(i),zp(i));
k2 = h*f(yp(i)+k1/2,zp(i)+l1/2);
l2 = h*g(yp(i)+k1/2,zp(i)+l1/2);
k3 = h*f(yp(i)+k2/2,zp(i)+l2/2);
l3 = h*g(yp(i)+k2/2,zp(i)+l2/2);
k4 = h*f(yp(i)+k3,zp(i)+l3);
l4 = h*g(yp(i)+k3,zp(i)+l3);
yp(i+1) = yp(i) + (k1+2*k2+2*k3+k4)/6
zp(i+1) = zp(i) + (l1+2*l2+2*l3+l4)/6
end
end
function y = f(y,z) y=-z;
end
function z = g(y,z) z=-y; end
0 Comments
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!