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

5 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 18 Mar 2011
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 Comment
Alex
Alex on 18 Mar 2011
Awesome, thanks for the answer and thanks for the tips; I'll make those changes.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!