I have a cell array with arrays of values 0 and I want to clear those
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
N/A
el 14 de Dic. de 2019
Comentada: N/A
el 14 de Dic. de 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
0 comentarios
Respuesta aceptada
Stephen23
el 14 de Dic. de 2019
Editada: Stephen23
el 14 de Dic. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!