RK4 method to solve a 2nd ODE.

2 visualizzazioni (ultimi 30 giorni)
joe brady
joe brady il 22 Nov 2022
Modificato: Torsten il 22 Nov 2022
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;

Risposte (1)

Torsten
Torsten il 22 Nov 2022
Modificato: Torsten il 22 Nov 2022
  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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by