MATLAB: Can someone explain to me whats off with this function handle

functionfunction_handlelotka-volterra

So I have a function where I want to model the population of predators and prey based off of the classic model Lotka-Volterra. In my code I designate dy as an array with the two equations.
function[predator,prey]=lotka_volterra(fprime, timespan, y0, h)
h=.1; %step size
%initial conditions
X(1)=timespan(1);
Y(1)=4;
Y(2)=4;
prey=Y(1);
predator=Y(2);
dy=[2*prey(X)-predator(X)*prey(X); predator(X)*prey(X)-2*predator(X)];
i=2;
while X(end)<timespan(end)
X(i)=X(i-1) + h;
Y(i)=Y(i-1)+h*fprime(X(i-1)); % Y(i)=Y(i+1)+h*y'(X(i-1))
i=i+1;
end
end
In the command window I typed,
[predator,prey]=lotka_volterra(@(X)(dy), [0 10], [4 4], .1)
but it is not recognizing that the equations are supposed to change by X (time). What am I messing up?

Best Answer

This code doesn't do what you think it does.
dx=2*Y(1)-Y(1)*Y(2);
dy=2*Y(1)*Y(2)-2*Y(2);
yprime=[dx dy];
yprime = @(X, Y) [dx dy];
It computes NUMERIC values for dx and dy based on the values currently stored in the variable Y. When you define yprime the first time, it concatenates those numeric values together. When you define yprime the second time, it creates a function handle that will return those numeric values. Note that even though the function handle yprime accepts X and Y as inputs, dx and dy are numbers, not functions of X and Y, and so will not change. This function handle will return the same values every time, ignoring the values with which you call it.
You can do this using multiple function handles:
dx = @(X, Y) 2*X-X.*Y;
dy = @(X, Y) 2*X.*Y-2*Y;
yprime = @(X, Y) [dx(X, Y), dy(X, Y)];
Now when you evaluate yprime, it evaluates the function handles dx and dy and uses the output from those two function handles to generate the output that yprime will return.