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

1 回表示 (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by