Systems of ODEs
Most dynamic models involve several quantities that change together: predators and prey, the angle and angular velocity of a pendulum, the positions of coupled masses, the concentrations in a chemical reaction. Integration & ODEs showed how ode45 solves a single equation and a damped spring. This lesson goes further: writing larger systems cleanly, passing parameters, getting values at the times you want, checking a solution against invariants and exact solutions, and stopping or recording the solution at events such as "the ball hits the ground".
The recipe
Every system is written as a first-order vector equation y′ = f(t, y):
- Choose the state vector
y(a column). A second-order equation contributes two entries: the quantity and its rate of change. - Write
f(t, y)so it returns a column of derivatives in the same order. - Call
[t, Y] = ode45(f, tspan, y0, opts). Row k ofYis the state at timet(k); column j is the history of state variable j.
Parameters are best captured with an anonymous function: write a general function with the parameters as extra inputs, then fix them with @(t, y) model(t, y, p1, p2).
Predator and prey
The Lotka–Volterra model describes rabbits x (growing at rate α, eaten at rate β·x·y) and foxes y (dying at rate γ, growing at rate δ·x·y from food):
x′ = α·x − β·x·y, y′ = δ·x·y − γ·y
lotka = @(t, y, a, b, c, d) [a*y(1) - b*y(1)*y(2);
d*y(1)*y(2) - c*y(2)];
f = @(t, y) lotka(t, y, 1.0, 0.1, 1.5, 0.075); % alpha, beta, gamma, delta
opts = odeset('RelTol', 1e-9, 'AbsTol', 1e-9);
tq = 0:5:20;
[t, Y] = ode45(f, tq, [10; 5], opts);
fprintf('t = %2d: prey %7.3f, predators %7.3f\n', [t'; Y']);t = 0: prey 10.000, predators 5.000
t = 5: prey 8.293, predators 7.419
t = 10: prey 8.007, predators 11.416
t = 15: prey 9.780, predators 17.167
t = 20: prey 15.905, predators 22.631
Passing a vector of output times tq makes ode45 report the solution exactly there (it still chooses its own internal steps). The tight tolerances keep MATLAB's and Octave's answers equal to the printed digits; with the default RelTol of 10⁻³ they agree only roughly.
[t, Y] = ode45(f, [0 20], [10; 5], opts);
subplot(1, 2, 1); plot(t, Y); legend('prey', 'predators'); xlabel('t'); ylabel('population')
title('Populations over time')
subplot(1, 2, 2); plot(Y(:, 1), Y(:, 2)); xlabel('prey'); ylabel('predators')
title('Phase plane')The populations oscillate, with the predator peaks lagging behind the prey peaks, and the phase-plane curve is a closed loop around the equilibrium (γ/δ, α/β) = (20, 10).
Checking a solution with an invariant
A numerical solution should be checked, not trusted. Lotka–Volterra has a conserved quantity, V = δx − γ ln x + βy − α ln y, which stays constant along exact solutions. Its drift measures the solver's error:
a = 1.0; b = 0.1; c = 1.5; d = 0.075;
f = @(t, y) [a*y(1) - b*y(1)*y(2); d*y(1)*y(2) - c*y(2)];
V = @(Y) d*Y(:, 1) - c*log(Y(:, 1)) + b*Y(:, 2) - a*log(Y(:, 2));
for tol = [1e-3 1e-6 1e-9]
opts = odeset('RelTol', tol, 'AbsTol', tol);
[t, Y] = ode45(f, [0 50], [10; 5], opts);
drift = max(abs(V(Y) - V(Y(1, :))));
fprintf('RelTol %.0e: drift of V below %.0e: %d\n', tol, 100 * tol, drift < 100 * tol);
endRelTol 1e-03: drift of V below 1e-01: 1
RelTol 1e-06: drift of V below 1e-04: 1
RelTol 1e-09: drift of V below 1e-07: 1
The drift falls with the tolerance. If an invariant drifts a lot, tighten the tolerances or suspect a bug in f.
Values between output times
[t, Y] = ode45(f, [t0 tEnd], ...) returns the solver's own steps, whose number and position differ between MATLAB and Octave. To get values at arbitrary times afterwards, interpolate with interp1 (it works column by column on Y):
f = @(t, y) [1.0*y(1) - 0.1*y(1)*y(2); 0.075*y(1)*y(2) - 1.5*y(2)];
opts = odeset('RelTol', 1e-9, 'AbsTol', 1e-9);
[t, Y] = ode45(f, [0 20], [10; 5], opts);
fprintf('solver returned more than 100 steps: %d\n', numel(t) > 100);
Yq = interp1(t, Y, [2.5 7.5 12.5], 'spline');
fprintf('t = %4.1f: prey %6.2f, predators %6.2f\n', [[2.5 7.5 12.5]; Yq']);solver returned more than 100 steps: 1
t = 2.5: prey 40.59, predators 10.21
t = 7.5: prey 35.67, predators 5.18
t = 12.5: prey 26.93, predators 3.45
MATLAB has a more accurate option: called with one output, sol = ode45(...) returns a solution structure, and deval(sol, tq) evaluates the solver's own interpolant. Octave 11 returns a structure too, but has no deval.
sol = ode45(f, [0 20], [10; 5], opts);
Yq = deval(sol, [2.5 7.5 12.5])'MATLAB output:
Yq =
40.5924 10.2075
35.6656 5.1816
26.9341 3.4495Coupled masses and the exact solution
Two equal masses joined by three equal springs between two walls give a linear system: with positions x₁, x₂, the equations are x₁″ = −2x₁ + x₂ and x₂″ = x₁ − 2x₂. Linear systems y′ = A·y have the exact solution y(t) = e^(At)·y(0), which expm (the matrix exponential) computes, a perfect check for ode45:
K = [-2 1; 1 -2];
A = [zeros(2) eye(2); K zeros(2)]; % state: x1, x2, v1, v2
y0 = [1; 0; 0; 0]; % pull mass 1 aside, release
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-10);
tq = 0:2:10;
[t, Y] = ode45(@(t, y) A * y, tq, y0, opts);
exact = zeros(numel(tq), 4);
for k = 1:numel(tq)
exact(k, :) = (expm(A * tq(k)) * y0)';
end
fprintf('t = %2d: x1 = %7.4f, x2 = %7.4f\n', [t'; Y(:, 1:2)']);
fprintf('ode45 agrees with expm within 1e-6: %d\n', max(abs(Y(:) - exact(:))) < 1e-6);
fprintf('normal-mode frequencies: %.4f and %.4f rad/s\n', sort(sqrt(-eig(K))));t = 0: x1 = 1.0000, x2 = 0.0000
t = 2: x1 = -0.6823, x2 = 0.2661
t = 4: x1 = 0.0727, x2 = -0.7264
t = 6: x1 = 0.1964, x2 = 0.7638
t = 8: x1 = 0.0658, x2 = -0.2113
t = 10: x1 = -0.3987, x2 = -0.4404
ode45 agrees with expm within 1e-6: 1
normal-mode frequencies: 1.0000 and 1.7321 rad/s
The motion is a mix of two normal modes: both masses swinging together at frequency 1 rad/s, and swinging against each other at √3 rad/s. They come from the eigenvalues of K, as in Matrix Decompositions.
Events: detecting when something happens
An event function tells the solver to watch a quantity and note (or stop at) the moment it crosses zero. It has the signature [value, isterminal, direction] = events(t, y):
| Output | Meaning |
|---|---|
value |
The quantity whose zero crossings are detected |
isterminal |
1 to stop the integration there, 0 to keep going |
direction |
1 only rising crossings, −1 only falling, 0 both |
Pass it with odeset('Events', @events) and ask for three extra outputs: [t, Y, te, ye, ie] = ode45(...), the event times, the states there, and which event fired.
The period of a pendulum
For a pendulum, θ″ = −(g/L)·sin θ. For small swings sin θ ≈ θ and the period is 2π√(L/g), but large swings take longer. Recording every moment the angular velocity crosses zero upwards (the far turning point) measures the true period:
g = 9.81; L = 1;
pend = @(t, y) [y(2); -g/L * sin(y(1))];
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-8, 'Events', @turningPoint);
[t, Y, te, ye, ie] = ode45(pend, [0 10], [pi/3; 0], opts); % released at 60 degrees
fprintf('events found: %d, angle there: %.4f rad\n', numel(te), ye(1, 1));
period = mean(diff(te));
small = 2*pi*sqrt(L/g);
fprintf('period at 60 degrees: %.4f s, small-angle formula: %.4f s, ratio %.4f\n', period, small, period / small);
function [value, isterminal, direction] = turningPoint(t, y)
value = y(2); % angular velocity
isterminal = 0; % keep integrating
direction = 1; % only crossings from negative to positive
endevents found: 5, angle there: -1.0472 rad
period at 60 degrees: 2.1529 s, small-angle formula: 2.0061 s, ratio 1.0732
At 60° the period is about 7% longer than the small-angle formula predicts. The event function is a local function at the end of the script (in MATLAB scripts, local functions must come last).
A bouncing ball: stop, change, restart
A terminal event stops the solver, so you can change the state and continue. A ball dropped from 10 m loses 20% of its speed at each bounce:
g = 9.81;
fall = @(t, y) [y(2); -g]; % height, velocity
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-10, 'Events', @hitGround);
t0 = 0; y0 = [10; 0];
bounces = zeros(1, 4);
for k = 1:4
[t, Y, te, ye] = ode45(fall, [t0 t0 + 10], y0, opts);
bounces(k) = te(end);
t0 = te(end);
y0 = [0; -0.8 * ye(end, 2)]; % reverse and damp the velocity
end
fprintf('bounce times: %s\n', sprintf('%.4f ', bounces));
first = sqrt(2 * 10 / g);
fprintf('exact first impact: %.4f s\n', first);
fprintf('exact later bounces: %s\n', sprintf('%.4f ', first + cumsum(2 * first * 0.8.^(1:3))));
function [value, isterminal, direction] = hitGround(t, y)
value = y(1); % height
isterminal = 1; % stop the integration
direction = -1; % only when falling
endbounce times: 1.4278 3.7124 5.5400 7.0021
exact first impact: 1.4278 s
exact later bounces: 3.7124 5.5400 7.0021
Each flight lasts 0.8 times the previous one, so the bounce times form a geometric series that the simulation matches.
Stiff systems
Some systems combine very fast and very slow processes, for example chemical reactions with rates differing by factors of millions. ode45 then needs tiny steps to stay stable even where the solution is smooth. Such problems are stiff: switch to ode15s (or ode23s), which take large steps safely. Both exist in MATLAB and Octave with the same calling syntax, so changing solvers is a one-word edit.
Learn more: the same models in Python are in SciPy ODE solvers; interpolation of solutions is covered in Interpolation.
Test yourself
How many state variables does a system of two coupled second-order equations need for ode45?
- 2
- 3
- 4
- 8
In an event function, what does isterminal = 1 do?
- Records the event and continues
- Stops the integration at the event
- Restarts the solver with the event state
- Ignores the event
Why pass a vector like 0:5:20 as the time span?
- It makes the solver use a fixed step of 5
- ode45 then reports the solution exactly at those times, so results are comparable
- It is required for systems
- It turns off error control