Convert higher order to first order system

11 views (last 30 days)
kingsley
kingsley on 17 May 2017
Answered: Torsten on 17 May 2017
I'm trying to solve the higher order ode by using RK4 method. Here is the code I have so far.
function [y] = rk4_high_ode(a,t0,n,h,f)
%f = @(t,y) 2*y(2)-y(3)+2*y(4);
% Do I need to define y(2) derivative first?
F=@(t,y)[y(2:end);f]; % Convert the higher order to the 1st order system
t(1)=t0;
for i=1:n
% update time
t(i+1)=t(i)+h;
k1=F(t(i) ,y(i) );
k2=F(t(i)+0.5*h,y(i)+0.5*h*k1);
k3=F(t(i)+0.5*h,y(i)+0.5*h*k2);
k2=F(t(i)+h ,y(i)+h*k1 );
y(i+1)=y(i)+h/6*(k1+2*k2+2*k3+k4);
end
end
And this is the test program:
clear
% test y=sin(t)
% y^(4) = 2*y'-y"+2*y^(3)
t0 = 0.1; n = 100; h = 1e-2;
a = [sin(t0) cos(t0) -sin(t0) -cos(t0)]';
f = @(t,y) 2*y(2)-y(3)+2*y(4);
y = rk4_high_ode(a,t0,n,h,f);
ye = sin(t0+n*h);
error2 = abs(y-ye)
There is an error " Undefined function or variable 'y'". Does that mean I need to define y(2) first? or something else.

Answers (1)

Torsten
Torsten on 17 May 2017
You will have to define
f=@(t,y) [y(2) y(3) y(4) 2*y(2)-y(3)+2*y(4)];
Additionally note that "rk4_high_ode" must be modified because at the moment, it is only capable of solving a single ODE.
Best wishes
Torsten.

Community Treasure Hunt

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

Start Hunting!