Index exceeds matrix dimensions while using a for loop

2 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by