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

3 次查看(过去 30 天)
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