MATLAB: How do you use ODE to solve four linear differential equations

differential equationsMATLABodeode45system

I have two coupled systems composed of four linear differential equations. How do you use a stiff ode to solve these four equations simultaneously?
m is a constant value
x1' = m * [y1 + x1 – x2];
y1' = -1/m * [x1 + y1];
x2' = m * [y2 + x2 – x1];
y2' = -1/m * [x2 + y2];
I solved the differential equation for one system, the code is as follows:
f = @(t,y) [m * (y(2) + y(1) – z); (-1/m) * ( y(1) + y(2)) ];
g = @(y) f(0,y);
[T Y] = ode15s(f, [0 80], [0, 0]);
In this case, z was a constant. However, the solution of the first system is now dependent on the second (x2).

Best Answer

I would take advantage of the Symbolic Math Toolbox to create an anonymous function you can then use directly with any of the numerical ODE solvers.
syms x1(t) x2(t) y1(t) y2(t) t Y m
Eq1 = diff(x1) == m*(y1 + x1 + x2);
Eq2 = diff(y1) == -1/m*(x1 + y1);
Eq3 = diff(x2) == m*(y2 + x2 + x1);
Eq4 = diff(y2) == -1/m*(x2 + y2);
[DEVF, Subs] = odeToVectorField(Eq1, Eq2, Eq3, Eq4);
ODEfcn = matlabFunction(DEVF, 'Vars',{t,Y,m})
producing (after some slight editing):
ODEfcn = @(t,Y,m)[-(Y(1)+Y(2))./m;m.*(Y(1)+Y(2)+Y(3));m.*(Y(2)+Y(3)+Y(4));-(Y(3)+Y(4))./m];
You would then call this in the ODE solvers as:
[t,y] = ode15s(@(t,Y) ODEfcn(t,Y,M), tspan, ic);
where ‘tspan’ is the vector of times or time limits, and ‘ic’ is a (4x1) vector of initial conditions.
Note that the ‘Subs’ variable describes the substitutions made to create the rows of ‘DEVF’. I prefer using the numeric ODE solvers.
You can also use the dsolve (link) function if you only want an analytic solution. For best results, you have to give it the initial values for all the derivatives.
syms x1(t) x2(t) y1(t) y2(t) t Y m X10 X20 Y10 Y20
Eq1 = diff(x1) == m*(y1 + x1 + x2);
Eq2 = diff(y1) == -1/m*(x1 + y1);
Eq3 = diff(x2) == m*(y2 + x2 + x1);
Eq4 = diff(y2) == -1/m*(x2 + y2);
[x1,x2,y1,y2] = dsolve(Eq1, Eq2, Eq3, Eq4, x1(0) == X10, x2(0) == X20, y1(0) == Y10, y2(0) == Y20)