Index exceeds matrix dimensions while using a for loop

조회 수: 1 (최근 30일)
Jeroen Bouma
Jeroen Bouma 2016년 11월 28일
댓글: Jeroen Bouma 2016년 11월 28일
I tried to make a simple program to find a specific set of numbers, but when I run it, it says "Index exceeds matrix dimensions". The line that causes an issue is "if(r(i+1)==2)"
does anyone know what the problem could be? I don't see it. r is a 10000x1 matrix, so I believe the dimensions are alright.
x=0
while (x==0)
n=10000
r = randi([0 9],n,1);
for i=1:n
if(r(i)==1)
if(r(i+1)==2)
if(r(i+2)==3)
if(r(i+3)==4)
if(r(i+4)==5)
if(r(i+5)==6)
if(r(i+6)==7)
if(r(i+7)==8)
if(r(i+8)==9)
display('found')
display(i)
x=1
end
end
end
end
end
end
end
end
end
end
end

채택된 답변

bio lim
bio lim 2016년 11월 28일
You defined your variable r as:
n=10000
r = randi([0 9],n,1);
So now, your r is 10000x1 double.
Then you defined a loop
for i=1:n
So i will go from 1 to 10000. What happens when i reaches to, let's say 10000?
if(r(i+1)==2)
The above is asking if the 10001 element of r is equal to 2, but the dimension of your r is 10000x1. Hence the error occurs.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by