Index exceeds matrix dimensions while using a for loop

1 view (last 30 days)
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

Accepted Answer

bio lim
bio lim on 28 Nov 2016
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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!