Problem with loop index

3 ビュー (過去 30 日間)
Arthur Romeu
Arthur Romeu 2020 年 3 月 9 日
コメント済み: Arthur Romeu 2020 年 3 月 9 日
Greetings everyone,
I am trying to do a simple loop with this piece of code:
for k = 1:size(rm_zerohoras,1)
for j = 1:size(FinAti,1)
if rm_zerohoras(k) == FinAti.Data(j)
FinAti(j,:) = [];
end
end
end
rm_zerohoras contains datetimes that I need to delete from FinAti. My intention is to, whenever the loop finds the corresponding datetime on a row in FinAti, the whole row gets deleted on FinAti. I'll attach both rm_zerohoras and FinAti for better understanding. The current problem is that when I run the program, the following error appears:
"Error using tabular/dotParenReference (line 108)
Index exceeds the number of array elements (474)."
I think it has something to do with the size of FinAti which is shrinking whenever the loop passes through. But how do I overcome this?
Thanks in advance,
Arthur.

採用された回答

Alex Mcaulley
Alex Mcaulley 2020 年 3 月 9 日
A simple way to do that avoiding the loop is:
idx = ismember(FinAti.Data,rm_zerohoras);
FinAti(idx,:) = [];
  1 件のコメント
Arthur Romeu
Arthur Romeu 2020 年 3 月 9 日
Thanks!

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

その他の回答 (1 件)

Adam
Adam 2020 年 3 月 9 日
Calculate the indices of all the rows you want to delete , then delete them all in one go afterwards, as e.g.
rowsToDelete = [1 5 7 8];
FinAti( rowsToDelete, : ) = [];
There's probbaly a vectorised way to calculate those indices, but if not simply store them in your loop instead of actually deleting rows.
If the number of occurences isn't huge the cost of having an array of indices growing in a loop is negligible, despite that it will give a code warning.
You should never delete elements of an array you are iterating forwards through - it never ends well. You can do it if you iterate backwards, but still my first suggestion is much cleaner as deleting a row at a time will be a lot slower than just deleting them all in one go.
  1 件のコメント
Arthur Romeu
Arthur Romeu 2020 年 3 月 9 日
Thank you!
Your explanation was really clear. I've learned a lot!

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by