필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
N/A
N/A 2019년 12월 14일
댓글: N/A 2019년 12월 14일
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

채택된 답변

Stephen23
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by