4th order runge kutta algorithm gives strange results for ode
Show older comments
I have a boundary value problem as below. I would like to solve it as initial value problem first by implementing a numerical approximation algorithm and to fulfil boundary conditions with newton method.
y1(t)'=t*y2(t) y(0)=1 y(5)=0 y2(t)'=4*y1(t)^(3/2)
I get strange results as full of zeros and inf in solution components (y in main) when i try to solve the Ivp with 4th order runge kutta algorithm.
function ystar = rk4( t0,y0,h)
y1=zeros(11,1);
y2=zeros(11,1);
y1=y0(1);
y2=y0(2);
t=0:0.5:5;
f=@(t,y1,y2) t*y2;
g=@(t,y1,y2) 4*(y1^(3/2));
for i=1:11
k1 = f(t(i),y1(i),y2(i));
l1=g(t(i),y1(i),y2(i));
k2= f(t(i)+0.5*h,y1(i)+0.5*h*k1,y2(i)+0.5*h*k1);
l2=g(t(i)+0.5*h,y1(i)+0.5*h*l1,y2(i)+0.5*h*l1);
k3 = f(t(i)+0.5*h,y1(i)+0.5*h*k2,y2(i)+0.5*h*k2);
l3= g(t(i)+0.5*h,y1(i)+0.5*h*l2,y2(i)+0.5*h*l2);
k4 = f((t(i)+h),(y1(i)+k3*h),(y2(i)+k3*h));
l4= g((t(i)+h),(y1(i)+l3*h),(y2(i)+l3*h));
y1(i+1)=y1(i)+(1/6)*(k1+2*k2+2*k3+k4)*h;
y2(i+1)=y2(i)+(1/6)*(l1+2*l2+2*l3+l4)*h;
ystar=[y1 y2];
end
end
main.m
y0=[1 0];
t0=[0,1];
h=0.5;
y=rk4(t0,y0,h);
Answers (0)
Categories
Find more on Ordinary Differential Equations 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!