MATLAB: RK4/AB4, need help with correct code for 2 second order equations in Matlab

2 second order equationsab4rk4

I have examples of code to follow for one second order equation but struggling to write correct code for 2 second order equations. grateful for any help!

Best Answer

So, first define a 4-element state vector. To keep the nomenclature the same as the MATLAB docs, I will use the variable name y. The elements of y are defined as
y(1) = x1
y(2) = x2
y(3) = x1dot
y(4) = x2dot
Next step is to solve your matrix differential equations for x1dotdot and x2dotdot so that you have two expressions. You can do this easily on paper. I.e., do the matrix multiply on paper and then solve the two equations for the highest order derivatives. You will get:
x1dotdot = some expression involving x1, x2, x1dot, and x2dot
x2dotdot = some expression involving x1, x2, x1dot, and x2dot
Then rewrite these expressions using the definitions above, so that you will get
x1dotdot = some expression involving y(1), y(2), y(3), and y(4)
x2dotdot = some expression involving y(1), y(2), y(3), and y(4)
Now you are ready to write code. The derivative function will be
dy = @(t,y) [y(3); y(4); the expression for x1dotdot; the expression for x2dotdot]
This can be used in your RK4 code, or even passed into ode45( ).