Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 45 ยท Real-World Projects

Project: Predator-Prey Simulation

Simulate rabbits and foxes with the Lotka-Volterra equations in MATLAB and Octave using ode45, draw a phase plot and run a parameter study, with SciPy stand-ins.

In this project you simulate two animal populations that depend on each other: rabbits (the prey) and foxes (the predators). Rabbits multiply when there is grass, foxes shrink when there are no rabbits to eat, and every meeting between the two removes a rabbit and feeds a fox. The result is a pair of coupled equations, the Lotka-Volterra model, whose solutions rise and fall in endless cycles.

It is a compact tour of what you learned in Integration, Differentiation and ODEs: write the right-hand side as a function handle, call ode45, then plot time series and a phase portrait, and finally vary the parameters in a loop. MATLAB and Octave do not run in your browser here, so the MATLAB code is read-only, and every step has a runnable Python stand-in with scipy.integrate.solve_ivp (the counterpart of ode45) and matplotlib.

Four steps

Model Write the two rates as a function.
Solve ode45 steps through time.
Plot Time series and phase plot.
Explore Change parameters in a loop.
1 / 2

Step 1: the model

Let x be the number of rabbits and y the number of foxes. Their rates of change are

  • dx/dt = alpha*x - beta*x*y
  • dy/dt = delta*x*y - gamma*y

Each parameter has a meaning. alpha is the rabbits' growth rate without foxes, beta how deadly an encounter is for a rabbit, delta how much an eaten rabbit helps foxes breed, and gamma the foxes' death rate without food. We choose alpha = 1.0, beta = 0.1, delta = 0.075 and gamma = 1.5.

The state is one column vector [x; y], so the right-hand side takes the time t and the state s and returns a column vector of two derivatives. In MATLAB, keep the parameters in a struct or capture them in an anonymous function (see Anonymous Functions and Function Handles):

MATLAB
p = struct('alpha', 1.0, 'beta', 0.1, 'delta', 0.075, 'gamma', 1.5);

rhs = @(t, s) [ p.alpha*s(1) - p.beta*s(1)*s(2);      % rabbits
                p.delta*s(1)*s(2) - p.gamma*s(2) ];   % foxes

The handle captures p at the moment you create it, so changing p later does not change rhs. Remember that the result must be a column: separating the two lines with a semicolon does that.

Step 2: solve with ode45

Start with 40 rabbits and 9 foxes and simulate 30 time units (think of them as months). Asking for output at evenly spaced times gives smooth curves:

MATLAB
s0    = [40; 9];
tspan = 0:0.05:30;
opts  = odeset('RelTol', 1e-8, 'AbsTol', 1e-10);
[t, s] = ode45(rhs, tspan, s0, opts);

size(s)          % 601 x 2: one row per time, one column per animal
x = s(:, 1);
y = s(:, 2);

Notice the layout: ode45 returns one row per time point. The tight tolerances matter here. This system conserves a certain quantity exactly (more about it in a moment), and a loose tolerance lets the numerical solution drift away from the true cycle.

Python Solve the Lotka-Volterra system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rabbit count swings between about 8 and 40, the foxes between about 3 and 23, and the foxes follow with a delay: first the rabbits boom, then the foxes feast and boom, then the rabbits crash, then the foxes starve.

Step 3: time series and phase plot

Two pictures tell the story. The first shows both populations against time. The second, the phase plot, draws foxes against rabbits: time disappears and each cycle becomes a closed loop.

MATLAB
figure
subplot(1, 2, 1)
plot(t, x, 'b-', t, y, 'r-', 'LineWidth', 1.5)
xlabel('time'), ylabel('population')
legend('rabbits', 'foxes')
title('Populations over time')

subplot(1, 2, 2)
plot(x, y, 'k-', x(1), y(1), 'go', 'MarkerFaceColor', 'g')
xlabel('rabbits'), ylabel('foxes')
title('Phase plot')

Also mark the equilibrium, the point where both rates are zero. Setting dx/dt = 0 and dy/dt = 0 with x, y > 0 gives x* = gamma/delta and y* = alpha/beta, here 20 rabbits and 10 foxes. If the populations ever started exactly there, nothing would change. Anywhere else, the loop circles around that point.

Python Time series and phase portrait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 4: check the numerics

How do you know the solver is right? This model has a conserved quantity, a combination of x and y that stays the same along every true trajectory:

H = delta*x - gamma*log(x) + beta*y - alpha*log(y)

If the numerical solution is accurate, H should be almost constant. Its drift is a handy error measure that needs no exact solution:

MATLAB
H = p.delta*x - p.gamma*log(x) + p.beta*y - p.alpha*log(y);
drift = max(H) - min(H)

Try the same run with the default tolerances and with 'RelTol', 1e-3, and compare the drift. A loose tolerance gives a visibly larger value, and over a long simulation the loop would spiral slowly outward or inward instead of closing.

Python Use the conserved quantity as an error check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tighter tolerances cost more function evaluations but shrink the drift by orders of magnitude. That trade-off is the one to remember whenever you pick tolerances for ode45.

Step 5: a parameter study

A model becomes interesting when you ask "what if?". Does a bigger starting rabbit population change the cycle? Wrap the solver in a loop over starting values and overlay the phase curves:

MATLAB
figure, hold on
for x0 = [25 30 40 50]
    [~, s] = ode45(rhs, tspan, [x0; 10], opts);
    plot(s(:,1), s(:,2))
end
plot(p.gamma/p.delta, p.alpha/p.beta, 'r*')
xlabel('rabbits'), ylabel('foxes')
legend('x0 = 25', 'x0 = 30', 'x0 = 40', 'x0 = 50', 'equilibrium')

You get a family of nested loops around the equilibrium: the farther from it you start, the bigger the swings. Population ecologists care about a related question: how long does one cycle take? You can measure it by finding the times when the rabbit count crosses the equilibrium value upward, using the logical tools from Logical Indexing and find: idx = find(x(1:end-1) < 20 & x(2:end) >= 20), and then diff(t(idx)) gives the period.

Python Nested cycles and their period

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Larger loops take longer to travel, which is why the printed cycle length grows from about 5.2 to 5.8 as the starting rabbit count rises from 25 to 50. Near the equilibrium the period approaches a fixed value of about 2*pi/sqrt(alpha*gamma), roughly 5.13 time units here.

Where to go next

The model is a first sketch, not a forecast. Real populations do not grow without limit: adding a carrying capacity to the rabbit equation (alpha*x*(1 - x/K)) turns the endless loops into a spiral that settles at the equilibrium. Try it, it is a one-line change in rhs. You could also stop the run when a population drops below 1 with an event function (see Integration, Differentiation and ODEs), since a fraction of a rabbit is not a rabbit, or fit alpha to real data with fminsearch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the right-hand-side function for ode45 return a column vector for a two-variable system?

    ode45 works with the state as a column vector, so the function must return the derivatives as a column of the same length. A row vector triggers a dimension error.
  2. 2. In the model, what does the product betaxy represent?

    x*y counts rabbit-fox encounters, and beta says how many of those end in a rabbit being eaten. The same product, scaled by delta, feeds the foxes.
  3. 3. What does a closed loop in the phase plot tell you?

    The phase plot removes time. A closed curve means the pair (rabbits, foxes) returns to the same values, so the populations oscillate periodically.
  4. 4. Why monitor the conserved quantity H during the run?

    H should stay constant along a true trajectory, so any drift in the computed values is solver error. Tighter tolerances reduce it.
  5. 5. In SciPy's solve_ivp result, what is the shape of sol.y for 2 states and 601 time points?

    solve_ivp returns one row per state variable, the transpose of ode45's layout. That is why the stand-ins unpack x, y = sol.y.

Summary

  • The Lotka-Volterra model is two coupled ODEs; write the right-hand side as a function handle that returns a column vector [dx; dy].
  • [t, s] = ode45(rhs, tspan, s0, opts) returns one row per time and one column per population; tighten RelTol and AbsTol for long runs.
  • A time-series plot shows the delayed boom and crash, and a phase plot turns each cycle into a closed loop around the equilibrium (gamma/delta, alpha/beta).
  • A conserved quantity gives a free accuracy check; a loop over starting values is a parameter study.
  • SciPy's solve_ivp is the stand-in and returns the transposed layout.

Next, clean up a noisy measurement in Project: Denoise a Signal.