How to use ode45 to solve a system of two differential equation?

3 views (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 30 Jan 2016
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.
  4 Comments
Conner Nixon
Conner Nixon on 31 Jan 2016
Appologies, as I am not confident with Matlab as we have only been given limited teaching with it, but is it possible to isolate the plots of only Y(1) and Y(3)? Thank you for being so helpful!
Star Strider
Star Strider on 31 Jan 2016
My pleasure!
No apologies necessary. We’re all always learning.
To plot only ‘Y(1)’ and ‘Y(3)’ on one plot:
figure(1)
plot(t, Y(:,1))
hold on
plot(t, Y(:,3))
hold off
grid
The solutions are returned as column vectors, so it’s necessary to address them as columns of ‘Y’.
You could plot them using only one plot call and not using the hold function, but plotting them as I did here allows for more coding flexibility. I added a grid call because I like the reference lines.

Sign in to comment.

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!