Index in position 2 exceeds array bounds (must not exceed 1)?
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!