Why couldn't ode45 doesn't work in this case?

조회 수: 3 (최근 30일)
Trung Ngo
Trung Ngo 2017년 12월 4일
댓글: Trung Ngo 2017년 12월 6일
I have tried debugging this annoying error related to using ode45 passed on one function handle declared in another script for almost a day!!! But, I couldn't believe why based on reflections of different code snippets that I looked up for modeling the DE of the predator-prey problem, my code still has this error
Error using alpha Too many output arguments.
Error in prey (line 2) dV(1) = alpha * y(1) - beta * y(1) * y(2) - E*V(1);
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in proj3_modified (line 25)
[t1, V1] = ode45('prey', tspan, v0);
I have 2 codes - one for the function prey.m & another script proj3_modified.m
prey.m
function dV = prey(t, y)
dV(1) = alpha * y(1) - beta * y(1) * y(2) - E*V(1);
dV(2) = -gamma * V(2) + delta * V(1) * V(2) - E*V(2);
dV = [dV(1) dV(2)]';
end
proj3_modified.m
global delta gamma alpha beta E
% prey = @(t,V)[ alpha * V(1) - beta * V(1) * V(2);
% -gamma * V(2) + delta * V(1) * V(2)];
alpha = 0.5;
beta = 0.01;
delta = 0.5;
gamma = 0.01;
E = 0.4; % E < alpha for moderate fishing
% 4 equilibrias noted by Di
D1 = [0 0];
D2 = [0 alpha/beta];
D3 = [gamma/delta 0];
D4 = [gamma/delta alpha/beta];
tspan = [0 10]; %a time span of 10 years
v0 = D1;
[t1, V1] = ode45('prey', tspan, v0);
v0 = D2;
[t2, V2] = ode45('prey', tspan, v0);
v0 = D3;
[t3, V3] = ode45('prey', tspan, v0);
v0 = D4;
[t4, V4] = ode45('prey', tspan, v0);
figure;
plot(t1, V1(:,1), t1, V1(:,2)); %X(t), Y(t) - equilibrium(0, 0)
title('Without fishing: Solutions started from different equilbrias');
hold on;
plot(t2, V2(:,1), t2, V2(:,2)); %X(t), Y(t) - equilibrium(0, alpha/beta)
plot(t3, V3(:,1), t3, V3(:,2)); %X(t), Y(t) - equilibrium(gamma/delta, 0)
plot(t4, V4(:,1), t4, V4(:,2)); %X(t), Y(t) - equlilbrium(gamma/delta, alpha/beta)
Please give me some workarounds to fix this because I couldn't think of any other ways!

답변 (1개)

Walter Roberson
Walter Roberson 2017년 12월 4일
global delta gamma alpha beta E
does not mean that "anywhere any function refers to delta, gamma, alpha, beta, or E, should suddenly become references to the global version of those variables."
Variables are only interpreted as global in functions (or scripts) that declare them as global. So you need to put a
global alpha
into your function.
  댓글 수: 1
Trung Ngo
Trung Ngo 2017년 12월 6일
Thank you for your correction. I should have understand this syntactic concept related to 'global'. I was able to fix it thanks to your suggestion! Thank you!

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

카테고리

Help CenterFile Exchange에서 Matrix Computations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by