Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by