Removing elements from a cell array... Loop index issue
5 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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)
More Answers (0)
See Also
Categories
Find more on Polygons in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!