Removing elements from a cell array... Loop index issue

6 ビュー (過去 30 日間)
Alex
Alex 2011 年 3 月 18 日
Hi, I want to loop through the elements of a cell array and remove elements that do not satisfy a size requirement. I'm getting an issue where the loop index points to non-existent elements as a result of this removal.
How can I get around this? Is there a more elegant MATLAB way to solve this problem?
Summary: d1 is a cell array in which each element is a 1xN array of doubles. I want to remove the elements that do not satisfy a specific size requirement (in this case if the length is not equal to patch^2).
for i = 1:length(d1) if length(d1{i}) ~= patch^2 d1(i) = []; end end
Thanks for your help.

採用された回答

Walter Roberson
Walter Roberson 2011 年 3 月 18 日
Either loop backwards or do them all at once.
for i = length(d1):-1:1; if length(d1{i}) ~= patch^2; d1(i) = []; end end
OR
d1(cellfun(@length, d1) ~= patch^2) = [];
By the way, it is not advisable to use "patch" as a variable name, as it is the name of an often-used function. "i" is not recommended as a variable name either, as it is pre-defined as sqrt(-1)
  1 件のコメント
Alex
Alex 2011 年 3 月 18 日
Awesome, thanks for the answer and thanks for the tips; I'll make those changes.

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

その他の回答 (0 件)

カテゴリ

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