Clear Filters
Clear Filters

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

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

Accepted Answer

Stephen23
Stephen23 on 14 Dec 2019
Edited: Stephen23 on 14 Dec 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.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!