Attempted to access y(2); index out of bounds because numel(y)=1

1 次查看(过去 30 天)
I am trying to make sir epidemic model uding ode45 but constantly I am getting this error "Attempted to access y(2); index out of bounds because numel(y)=1".please suggest some method to remove this.
thank you
if true
% code
function sir_model = sir_model(t,y)
a=1;
b=1;
sir_model(1) = -a*y(1)*y(2);
sir_model(2)= a*y(1)*y(2) -b*y(2);
sir_model(3)= b*y(2);
sir_model=[sir_model(1) sir_model(2) sir_model(3)]';
end

回答(2 个)

Youssef  Khmou
Youssef Khmou 2013-5-27
hi y's length must >2 : try :
H=sir_model(t,rand(2,1));

Image Analyst
Image Analyst 2013-5-27
Are you trying to do a recursive function? If so, I see no exit condition. Or are you just use to Visual Basic where you set the return argument of a function by setting the function name equal to something?
Since sir_model is a function, I don't think this will work:
sir_model(1) = -a*y(1)*y(2);
Then to make it worse, you're recursing back into sir_model three separate times with this statement:
sir_model=[sir_model(1) sir_model(2) sir_model(3)]';
As if that weren't bad enough, you're passing in a y that's just a single value (1, 2, or 3), not an array of two numbers.
By chance do you mean this:
function sir_model_output = sir_model(t,y)
a = 1;
b = 1;
term1 = -a * y(1) * y(2);
term2 = a * y(1) * y(2) - b * y(2);
term3 = b * y(2);
sir_model_output = [term1, term2, term3]';

类别

Help CenterFile Exchange 中查找有关 Problem-Based Optimization Setup 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by