Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Iterating through array of structures causes "Index exceeds matrix dimension"

1 回表示 (過去 30 日間)
Velin  Alex
Velin Alex 2015 年 8 月 15 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello, I try to iterate through this array of struct, and it causes this exception. I was monitoring values of j, and it really goes bigger than numel(D). Also tried with length(D) instead of numel(D) with same result. I would appreciate any help.
It seems that the for j = 1:numel(D) allows iteraion when j > numel(D), that doesnt make any sense to me. Is this a correct way to iterate trough array of structs?
for i = 1:numel(B)
for j = 1:numel(D)
dist = sqrt((B(i).x - D(j).x)^2 + (B(i).y - D(j).y)^2);
if dist < B(i).size/2 & B(i).size/2 > D(j).size
B(i).size = B(i).size + D(j).size;
D(j) = [];
end
end
end

回答 (1 件)

Jon
Jon 2015 年 8 月 15 日
編集済み: Jon 2015 年 8 月 15 日
It is impossible for j to go larger than numel(D) unless you modify j or D within the loop (which you are doing). I believe what's happening is that when you run the for loop, Matlab doesn't recompute numel(D) each iteration; it's computed only once initially. Your code then erases elements of D, making it have fewer elements. So initially, D may have 10 elements. As you iterate, say you delete two of those elements. When the loop gets to j = 9, there are only 8 elements so you get the error.
A better way to do this is to keep track of the indices you want to remove, then remove them all at once. This also has the advantage of not skipping indices (for example, if j = 5 and you remove D(5), then D(6) becomes D(5), but on your next iteration j will be 6, skipping over the new D(5).
for i = 1:numel(B)
remove_these = [];
for j = 1:numel(D)
dist = sqrt((B(i).x - D(j).x)^2 + (B(i).y - D(j).y)^2);
if dist < B(i).size/2 & B(i).size/2 > D(j).size
B(i).size = B(i).size + D(j).size;
remove_these = [remove_these j];
end
D(remove_these) = [];
end
end
Finally, I don't know what else your structure stores, but it may be more convenient just to use matrices if you're just storing x,y coordinates. Makes indexing easier.
  1 件のコメント
Velin  Alex
Velin Alex 2015 年 8 月 15 日
編集済み: Velin Alex 2015 年 8 月 15 日
I like the solution. Thank you very much, Jon!

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by