Removing elements from a cell array... Loop index issue

조회 수: 7 (최근 30일)
Alex
Alex 2011년 3월 18일
Hi, I want to loop through the elements of a cell array and remove elements that do not satisfy a size requirement. I'm getting an issue where the loop index points to non-existent elements as a result of this removal.
How can I get around this? Is there a more elegant MATLAB way to solve this problem?
Summary: d1 is a cell array in which each element is a 1xN array of doubles. I want to remove the elements that do not satisfy a specific size requirement (in this case if the length is not equal to patch^2).
for i = 1:length(d1) if length(d1{i}) ~= patch^2 d1(i) = []; end end
Thanks for your help.

채택된 답변

Walter Roberson
Walter Roberson 2011년 3월 18일
Either loop backwards or do them all at once.
for i = length(d1):-1:1; if length(d1{i}) ~= patch^2; d1(i) = []; end end
OR
d1(cellfun(@length, d1) ~= patch^2) = [];
By the way, it is not advisable to use "patch" as a variable name, as it is the name of an often-used function. "i" is not recommended as a variable name either, as it is pre-defined as sqrt(-1)
  댓글 수: 1
Alex
Alex 2011년 3월 18일
Awesome, thanks for the answer and thanks for the tips; I'll make those changes.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by