I have a cell array with arrays of values 0 and I want to clear those
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2019-12-14
编辑:Stephen23
2019-12-14
"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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!