RK4 method to solve a 2nd ODE.

조회 수: 2 (최근 30일)
joe brady
joe brady 2022년 11월 22일
편집: Torsten 2022년 11월 22일
I am trying to solve a 2nd ODE using the RK4 method, however the increase in time step doesn't seem to be working correctly?
%% Initial Conditions
u0 = 0.719622752231628; % Initial Displacement
z0 = 0; % Initial Velocity
%%Defining the equations
f1 = @(u,z,t) z0; % Initial f1
f2 = @(u,z,t) A*z0(t)+B*u0(t); % Initial f2
% RK4 Loop
for i = 0:1:4001
% Update time
t(i+1) = t(i)+dt;
% Update u and z
K1 = f(x(i),y(i));
L1 = f(x(i),y(i));
K2 = f(x(i)+0.5*h,y(i)+h*0.5*k1);
L2 = f(x(i)+0.5*h,y(i)+h*0.5*k1);
K3 = f(x(i)+0.5*h,y(i)+h*0.5*k2);
L3 = f(x(i)+0.5*h,y(i)+h*0.5*k2);
K4 = f(x(i)+ h,y(i)+h *k2);
L4 = f(x(i)+ h,y(i)+h *k2);
u(i+1) = y(i)+h/6*(K1+2*K2+2*K3+K4);
z(i+1) = u(i)+h/6*(L1+2*L2+2*L3+L4);
end
Error message:
Array indices must be positive integers or logical values.
Error in RK4 (line 26)
t(i+1) = t(i)+dt;

답변 (1개)

Torsten
Torsten 2022년 11월 22일
편집: Torsten 2022년 11월 22일
  1. The definition of the function handles f1 and f2 is wrong:
f1 = @(u,z,t) z0; % Initial f1
f2 = @(u,z,t) A*z0(t)+B*u0(t); % Initial f2
You don't reference u, z and t in the definition of the functions
Further z0 and u0 are scalars, not functions. So z0(t) and u0(t) don't exist.
2. Array indices start with 1. You address t(0) in t(i+1) = t(i) + dt.
3. f is undefined. You defined f1 and f2, but no f.
4. dt and h are identical. So give them the same name.
5. dt and h are undefined.
6. k1 and k2 are undefined. You work with K1, K2, K3 K4,L1,L2,L3 and L4.
7. The updates
K4 = f(x(i)+ h,y(i)+h *k2);
L4 = f(x(i)+ h,y(i)+h *k2);
are wrong.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by