Index exceeds matrix dimensions while using a for loop

1 次查看(过去 30 天)
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