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

3 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2016-1-30
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 个评论
Conner Nixon
Conner Nixon 2016-1-31
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 2016-1-31
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by