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!
0 个评论
回答(1 个)
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.
Or better yet, don't do that. Instead http://www.mathworks.com/help/matlab/math/parameterizing-functions.html
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Computations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!