Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Naruto
Naruto le 9 Nov 2020
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

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Nov 2020
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.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by