Convert higher order to first order system

조회 수: 11(최근 30일)
kingsley
kingsley 2017년 5월 17일
답변: VBBV 2021년 11월 20일
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.

답변(2개)

Torsten
Torsten 2017년 5월 17일
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.

VBBV
VBBV 2021년 11월 20일
clear
y = @(t) sin(t)
y = function_handle with value:
@(t)sin(t)
y(2)
ans = 0.9093
% 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 = 2*y(2)-y(3)+2*y(4)
f = 0.1639
[y t] = rk4_high_ode(a,t0,n,h,f)
F = function_handle with value:
@(t,y)f
y = 1×100
0 0.0016 0.0033 0.0049 0.0066 0.0082 0.0098 0.0115 0.0131 0.0147 0.0164 0.0180 0.0197 0.0213 0.0229 0.0246 0.0262 0.0279 0.0295 0.0311 0.0328 0.0344 0.0361 0.0377 0.0393 0.0410 0.0426 0.0442 0.0459 0.0475
t = 1×100
0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100 0.0100
ye = sin(t0+n*h);
error2 = abs(y-ye)
error2 = 1×100
0.8912 0.8896 0.8879 0.8863 0.8847 0.8830 0.8814 0.8797 0.8781 0.8765 0.8748 0.8732 0.8715 0.8699 0.8683 0.8666 0.8650 0.8633 0.8617 0.8601 0.8584 0.8568 0.8552 0.8535 0.8519 0.8502 0.8486 0.8470 0.8453 0.8437
plot(y,'linewidth',2)
hold on; plot(error2,'ro')
function [y t] = 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) f % Convert the higher order to the 1st order system
t = zeros(1,n);
y = zeros(1,n);
t(1)=t0;
for i=2:n
% update time
t(i-1)=t(i)+h;
k1=F(t(i-1),y(i-1));
k2=F(t(i-1)+0.5*h,y(i-1)+0.5*h*k1);
k3=F(t(i-1)+0.5*h,y(i-1)+0.5*h*k2);
k4=F(t(i-1)+h,y(i-1)+h*k1);
y(i)=y(i-1)+h/6*(k1+2*k2+2*k3+k4);
end
end

Community Treasure Hunt

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

Start Hunting!

Translated by