Help with Lotka-Volterra error codes
4 views (last 30 days)
Show older comments
dx/dt = -.1 x + .02 x y
dy/dt = .2 y - .025 x y
I am trying to figure out how to numerically solve this system of equations but my text book doesn't really explain how to do that. It just says "use a numerical solver". When I try to use MATLABs Lotka-Volterra or any of the previously asked questions I get the following errors;
>> function xdot = Lotka(t,x)
xdot = [x(1) - 0.05*x(1)*x(2); -0.5*x(2)-0.02*x(1)*x(2)];
function xdot = Lotka(t,x)
↑
Error: Function definition not supported in this context. Create functions in code file.
>> xdot = lotka(t,x)
xdot = [x(1) - 0.05*x(1)*x(2); -0.5*x(2)-0.02*x(1)*x(2)];
Index exceeds array bounds.
Error in sym/subsref (line 859)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in lotka (line 6)
yp = diag([1 - .01*y(2), -1 + .02*y(1)])*y;
I know my numbers don't match the code but I am trying to first figure out how to use Lotka or ODE45. My biggest issue is dealing with a system of equations with x, y, and t.
Any help is much appreciated.
0 Comments
Accepted Answer
Star Strider
on 14 Mar 2021
Function definitions of the type you posted can be at the end of a script in recent MATLAB releases, and are not required to be separate function files. (The documentation on Function Basics discusses that.)
The easiest way to use your function is to create it as an anonymous function:
lotka = @(t,x) [x(1) - 0.05*x(1)*x(2); -0.5*x(2)-0.02*x(1)*x(2)];
It will work in the MATLAB ODE solvers, such as ode45 and the others. See the documentation on Anonymous Functions for details.
10 Comments
Star Strider
on 20 Mar 2021
That works, however it’s a bit different from using an initial conditions vector with the numeric ODE solvers, since in this instance:
test = @(x)[x+1;x+2];
x=[1 2];
q1 = test(x) % Row Vector Argument
q2 = test(x.') % Column Vector Argument
produce different results, however the ODE solvers automatically assign the appropriate elements of the initial conditions vector to the appropriate differential equations, regardless of the orientation of the initial conditions vector.
More Answers (0)
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!