Help with Lotka-Volterra error codes

1 visualización (últimos 30 días)
Matt Baron
Matt Baron el 14 de Mzo. de 2021
Comentada: Star Strider el 20 de Mzo. de 2021
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.

Respuesta aceptada

Star Strider
Star Strider el 14 de Mzo. de 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 comentarios
Matt Baron
Matt Baron el 20 de Mzo. de 2021
Right, I meant that I just figured out from your help this;
>> test
test =
function_handle with value:
@(x)[x+1;x+2]
>> x=[1 2]
x =
1 2
>> test(x)
ans =
2 3
3 4
Star Strider
Star Strider el 20 de Mzo. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by