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

arrayerrorMATLAB

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

Best Answer

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