Effacer les filtres
Effacer les filtres

I have a cell array with arrays of values 0 and I want to clear those

2 vues (au cours des 30 derniers jours)
N/A
N/A le 14 Déc 2019
Commenté : N/A le 14 Déc 2019
I have an array cell with arrays containing 0 values. I want to remove those zero values but I keep getting an exception for my for loop.Index exceeds matrix dimensions.
My code is:
for i = 1:1:100
Fitness(c{i})
if ans == 0 || ans == 1
c(i) = [];
end
end

Réponse acceptée

Stephen23
Stephen23 le 14 Déc 2019
Modifié(e) : Stephen23 le 14 Déc 2019
"I keep getting an exception for my for loop.Index exceeds matrix dimensions."
You get this error precisely because you are removing elements from the cell array. Think about what happens when you remove one element: then the array is smaller but you are still iterating over its original length, not the shortened length, so you end up trying to index into elements that no longer exist.
Here are two easy solutions:
Method one: iterate backwards:
for k = 100:-1:1 % backwards!
out = Fitness(c{k});
if out==0 || out==1;
c(k) = [];
end
end
Method two: remove after the loop:
idx = false(1,100);
for k = 1:1:100
out = Fitness(c{k});
idx(k) = out==0 || out==1;
end
c(idx) = []
This is will generally be more efficient.
  1 commentaire
N/A
N/A le 14 Déc 2019
Thank you I understood method 1 but can you explain method 2?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical 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!

Translated by