Mouse Problem: Why do I keep getting the error message, "Array indices must be positive integers or logical values."?

1 次查看(过去 30 天)
I'm not sure why I keep getting the following error messages:
Array indices must be positive integers or logical values.
Error in hehemouse (line 13)
dx=x(mod(i+1,5))-x(i)/sqrt(((x(mod(i+1,5))-x(i))^2)+((y(mod(i+1,5))-y(i))^2));
My code is the following.
% Initialize the positions of the 5 mice
x = [0, -sin(2*pi/5), -sin(4*pi/5), sin(4*pi/5), sin(2*pi/5)];
y = [1, cos(2*pi/5), -cos(pi/5), -cos(pi/5), cos(2*pi/5)];
% For each iteration, each mouse moves a distance d=0.01 towards neighbour ccw
% To find mouse's neighbour, just do (x+1)%5 = generate coordinates
% Repeat iterations until mice are sufficiently close to each other
while ((sqrt((y(2)-y(1)^2))+(x(2)-x(1))^2)>0.01)
for i=1:5
fprintf('%lf %lf', x(i), y(i));
dx=x(mod(i+1,5))-x(i)/sqrt(((x(mod(i+1,5))-x(i))^2)+((y(mod(i+1,5))-y(i))^2));
dy=y(mod(i+1,5))-y(i)/sqrt(((x(mod(i+1,5))-x(i))^2)+((y(mod(i+1,5))-y(i))^2));
x(i)=x(i)+0.01*dx;
y(i)=y(i)+0.01*dy;
end
end
% To graph, store sequence of vectors in matrices with each line representing coordinates at one of the time steps
x = mat(i,:);
y = mat(:,i);

采纳的回答

Walter Roberson
Walter Roberson 2019-4-1
When i becomes 4 in the for i=1:5 loop, then mod(i+1,5) is mod(4+1,5) which is mod(5,5) which is 0. You then try to use that 0 to index x.
The correct neighbour is mod(i,5)+1

更多回答(1 个)

Sakz
Sakz 2019-4-1
The source of error is in : x(mod(i+1,5))
when i=4, then mod(5,5) = 0; then x(0) is causing the error.
Matlab vector index starts from 1.
[ Subscript indices must either be real positive integers or logicals.]

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by