Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
Iterating through array of structures causes "Index exceeds matrix dimension"
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!