필터 지우기
필터 지우기

Index in position 2 exceeds array bounds (must not exceed 1)?

조회 수: 2 (최근 30일)
Naruto
Naruto 2020년 11월 9일
답변: Walter Roberson 2020년 11월 9일
Why does the following for loop produce the error "Index in position 2 exceeds array bounds (must not exceed 1)"?
data matrix (1000x4)
x = data(:,2);
y = data(:,3);
tr = data(:,4);
xt = x((tr)==1);
yt = y((tr)==1);
for i = 1:size(x)
for j = 1:size(xt)
if sqrt((x(1,i)-xt(1,j))+(y(1,i)-yt(1,j)))< 5
fprintf ('Pass')
end
end
end

채택된 답변

Walter Roberson
Walter Roberson 2020년 11월 9일
size(x) returns a vector of values -- size() with a single parameter always returns two values.
When you use a vector of values as the boundary in a colon operation, 1:size(x) for example, then it will use the first element as the bound. That might or might not be what you want.
x = data(:,2);
That is going to be a column vector.
xt = x((tr)==1);
When you do logical indexing on a row vector, you get out a row vector. When you do logical indexing on any other orientation (column vector, 2D array, etc.) then you get out a column vector. x is a column vector, so logical indexing on it is going to return a column vector.
if sqrt((x(1,i)-xt(1,j))+(y(1,i)-yt(1,j)))< 5
You are trying to index the column vectors x and xt as if they are row vectors.
You have the same issue with respect to y and yt.

추가 답변 (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