For loop, exceeded dimension error.

Hi, this is most certainly an easy fix on which I seem to got myself stuck.
The loop should compare elements of an array and if it finds that they are equal it shall erase that row, next it shall recompute the size of the array and redo the comparison for the next element:
for ii=1:N
if (ii>1) && (ii<N)
i3=ii+1;
for jj=i3:N
if DD(ii,1)==DD(jj,1)
DD(jj,:)=[];
[N,M]=size(DD);
end
end
end
end
I get the following error:
??? Index exceeds matrix dimensions.
Error in ==> VB_CompDin2Darray at 29
if DD(ii,1)==DD(jj,1)
A pointer would be great. Cheers.

 採用された回答

Sean de Wolski
Sean de Wolski 2011 年 7 月 20 日

1 投票

Simply run the loop backwards so row 4 doesn't become row 3 when row 3 is deleted.
e.g:
for jj = N:-1:i3
%delete stuff
end
Now of course you're still best off (for speed) building an index vector and doing the whole delete once at the end.
idx = false(N-i3,1);
for jj = i3:N
if stuff
idx(jj) = true;
end
Mat(idx,:) = [];
end

4 件のコメント

Victor Buza
Victor Buza 2011 年 7 月 20 日
Great! Thanks. What was the problem with row 4 becoming 3? I mean, it was still resizing and comparing the element, wasn't it?
Jan
Jan 2011 年 7 月 20 日
@Victor: The loop "for jj=i3:N" runs until the inital value of N, even if N is modified inside the loop. In most other programming languages modifying the limit inside the loop effect the number of iterations.
Sean de Wolski
Sean de Wolski 2011 年 7 月 20 日
If you delete row 3; what happens to row 4? It becomes row 3! Now your matrix size is smaller, but the for-loop still wants to go to the ORIGINAL N.
Sean de Wolski
Sean de Wolski 2011 年 7 月 20 日
Use unique, as Jan has suggested, anyway.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2011 年 7 月 20 日

3 投票

Simple and efficient for large matrices:
[dummy, index] = unique(DD(:, 1));
DD = DD(index, :);

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by