RK 4th order for second order ODE

5 views (last 30 days)
Abraham
Abraham on 17 Nov 2018
Answered: khalida on 14 Jul 2023
Hi, please is there a MATLAB code for RK 4th method 2nd order ODE. I have seen RK 4th for 1st order ODE. what I I need is a code for RK 4th order 2nd ODE (with a function handle). Which I can adjust based on my parameters. Thanks
  2 Comments
Jan
Jan on 17 Nov 2018
It is very easy to convert a 2nd order ODE into a system of 1st order ODEs. Do you have a reason to avoid this?
Abraham
Abraham on 18 Nov 2018
Figured it out. Thanks, Jan.

Sign in to comment.

Answers (1)

khalida
khalida on 14 Jul 2023
clear,clc
% % % % % RK4 system of odes higher order
h = 0.1;
x_beg = 0;
x_end = 0.7;
y_initial= 0;
z_initial= 0;
F_xy=@(x,z)(z);
F_xz=@(x,y,z)(-((1+5*x)/2*x*(x+1))*z-y^3+5*x+11*x^2+(8/27)*x^9);
x=x_beg:h:x_end;
y=zeros(1,length(x));
y(1)=y_initial;
z=zeros(1,length(x));
z(1)=z_initial;
for i=1:(length(x)-1);
i=1:(length(x)-1);
k1 = F_xy(x(i),y(i),z(i));
L1 = F_xz(x(i),y(i),z(i));
k2 = F_xy((x(i)+h/2),(y(i)+0.5*h*k1),z(i)+0.5*h*L1);
L2 = F_xz((x(i)+h/2),(y(i)+0.5*h*k1),z(i)+0.5*h*L1);
k3 = F_xy((x(i)+h/2),(y(i)+0.5*h*k2),z(i)+0.5*h*k2);
L3 = F_xz(x(i)+h/2,(y(i)+0.5*h*k2),(z(i)+0.5*h*L2));
k4 = F_xy((x(i)+h),(y(i)+k3*h),z(i)+L3*h);
L4 = F_xz((x(i)+h),(y(i)+k3*h),(z(i)+L3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h;
z(i+1) = z(i) + (1/6)*(L1+2*L2+2*L3+L4)*h;
end
% plot(y,z)
figure(1)
plot(x,z)
hold on
plot(x,y)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!