Removing elements from a cell array... Loop index issue
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Walter Roberson
le 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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!