Info

This question is closed. Reopen it to edit or answer.

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

1 view (last 30 days)
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

Answers (1)

Jon
Jon on 15 Aug 2015
Edited: Jon on 15 Aug 2015
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.

This question is closed.

Community Treasure Hunt

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

Start Hunting!