필터 지우기
필터 지우기

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개)

Rohit Kumar
Rohit Kumar 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