How to use ode45 to solve a system of two differential equation?
    3 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
    Conner Nixon
 il 30 Gen 2016
  
    
    
    
    
    Commentato: Star Strider
      
      
 il 31 Gen 2016
            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
0 Commenti
Risposta accettata
  Star Strider
      
      
 il 30 Gen 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 Commenti
  Star Strider
      
      
 il 31 Gen 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.
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

