MATLAB: Solving System of Differential Equations with Multiple Variables using ode45

differential equationsfunctionode45solvesystem

Lets say I have a system of six differential equations with multiple variables:
dA = E – C + B – D
dB = F – D + A – C
…..
dF = – B + D – F
How can I write a function which is solvable with ode45? I want a 1×6 initial condition input and a 1×6 output over a time span.

Best Answer

If you assign ‘A(t)’ as ‘x(1)’ ... ‘F(t)’ as ‘x(6)’, then an anonymous function version would create this matrix:
dfcn = @(t,x) [x(5) - x(3) + x(2) + x(4)
x(6) - x(4) + x(1) - x(3)
. . .
-x(2) + x(4) + x(6)];
and then call ode45 with ‘dfcn’ and the appropriate initial conditions and time span.
The function gets a bit more complicated if involves derivatives of the functions on the right hand side. For that, I usually use the Symbolic Math Toolbox to create the equations, then odeToVectorField to create them as first-order equations, and matlabFunction to convert them to a system that ode45 can use. (Sure, I could do them by hand and then spend a bit of time sorting my algebra errors, but there is no reason to do that.)
Related Question