MATLAB: How to use ode45 to solve a system of two differential equation

mass spring systemode45second order odestwo degrees of freedom

I am aware of how to solve a system with one set of ODEs but not two
m1x1''=k2(x2-x1) – k1x1,
m2x2''=-k2(x2-x1) -k3x2

Best Answer

Feeling lazy today, and watching the Stuttgart-Hamburg football match, so I let the Symbolic Math Toolbox do the heavy lifting:
syms k1 k2 k3 m1 m2 x1(t) x2(t) x10 x20
Eqs = [m1*diff(x1(t),2) == k2*(x2(t)-x1(t)) - k1*x1(t), m2*diff(x2(t),2) == -k2*(x2(t)-x1(t)) -k3*x2(t)];
SymSys = odeToVectorField(Eqs);
Sys = matlabFunction(SymSys)
Sys = @(Y,k1,k2,m1,m2)[Y(2);-(k2.*(Y(1)-Y(3)))./m2;Y(4);-(-k2.*Y(1)+k1.*Y(3)+k2.*Y(3))./m1];
It transmuted your ‘’x1 and ‘x2’ to elements of the ‘Y’ vector, but no worries. To make ode45 happy, you would change this to:
Sys = @(t,Y,k1,k2,m1,m2)[Y(2);-(k2.*(Y(1)-Y(3)))./m2;Y(4);-(-k2.*Y(1)+k1.*Y(3)+k2.*Y(3))./m1];
and then in ode45, call it as:
[t,y] = ode45(@(t,y) Sys(t,Y,k1,k2,m1,m2), tspan, Y0);
having previously defined the constants ‘k1’,‘k2’,‘m1’,‘m2’ in your workspace.
I did not run this, so I am labeling it UNTESTED CODE, but it should work.