Applying runge kutta for coupled equations
Show older comments
Hey guys,
so I have 2 second order nonlinear ODE and after applying the state-space theorm I have 4 first order ODE.
I'm trying to apply RK4 but I think I'm doing it wrong because the graphs diverge.
I'm getting a hard time applying it because the equations are coupled.
Those are the main equations. L and Fa also have state-space variables in them but it doesn't make a diffrence for my qustion.

After applying the state-space theorm, Those are my equations:
f1 = @(x2) x2; % = x1'
f2 = @(x1, x2, x3) K/m*(l_0/sqrt((X_d(t, t1, t2, a_x0, X_d0, X_d0_tag)-x1).^2+(Z_d(t, t0, a_z0, Z_d0, Z_d0_tag)-x3).^2)-1)*(x1-X_d(t, t1, t2, a_x0, X_d0, X_d0_tag)) ...
- 0.5*Rho*A*C_d*(x2-Interpolation(Z_d(t, t0, a_z0, Z_d0, Z_d0_tag), data)).^2*sgn(x2, Z_d(t, t0, a_z0, Z_d0, Z_d0_tag), data)/m;
% = x2'
f3 = @(x1) x1; % = x3'
f4 = @(x1, x3) K/m*(l_0/sqrt((X_d(t, t1, t2, a_x0, X_d0, X_d0_tag)-x1).^2+(Z_d(t, t0, a_z0, Z_d0, Z_d0_tag)-x3).^2)-1)*(x3-Z_d(t, t0, a_z0, Z_d0, Z_d0_tag))-g;
% x4'
Than I tried to apply RK4. Heads up, it might be a complete nonsense. I also applied initial conditions but I don't want to make it messy.
h=0.2; % step size
t_array = 0:h:10;
w = zeros(1,length(t_array));
x = zeros(1,length(t_array));
y = zeros(1,length(t_array));
z = zeros(1,length(t_array));
for i=1:(length(t_array)-1) % calculation loop
t = 0 +h*i; % A parameter needed for the interpolation in f2
k_1 = f1(x(i));
k_2 = f1(x(i)+0.5*h*k_1);
k_3 = f1(x(i)+0.5*h*k_2);
k_4 = f1(x(i)+k_3*h);
x(i+1) = x(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
disp(x(i+1));
m_1 = f3(z(i));
m_2 = f3(z(i)+0.5*h*k_1);
m_3 = f3(z(i)+0.5*h*k_2);
m_4 = f3(z(i)+k_3*h);
z(i+1) = z(i) + (1/6)*(m_1+2*m_2+2*m_3+m_4)*h;
n_1 = f2(x(i), z(i), w(i));
n_2 = f2(x(i), z(i) ,w(i)+0.5*h*k_1);
n_3 = f2(x(i), z(i) ,w(i)+0.5*h*k_2);
n_4 = f2(x(i), z(i) ,w(i)+k_3*h);
w(i+1) = w(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
l_1 = f4(x(i), z(i));
l_2 = f4(x(i), z(i));
l_3 = f4(x(i), z(i));
l_4 = f4(x(i), z(i));
y(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
end
As I said my graphs are divering (they souldn't be) so I suspect my code is wrong.
Please help me fix the algorithm.
Thank you very much!
Accepted Answer
More Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!