Help with Lotka-Volterra error codes

조회 수: 2 (최근 30일)
Matt Baron
Matt Baron 2021년 3월 14일
댓글: Star Strider 2021년 3월 20일
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.

채택된 답변

Star Strider
Star Strider 2021년 3월 14일
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
Matt Baron
Matt Baron 2021년 3월 20일
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 2021년 3월 20일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by