2
votes

how can I delete all elements of a cell array that have less then for example 5 elements inside.

result{1}= 1
result{2}= [2 3 4 5 6 7 8]
result{3}= [9 10 11 12 13 14 16 17 18]
result{4}= [19 20 21]

In this example I want to delete result{1} and result{4}, because they have less than 5 elements inside.

With this topic ( matlab length of each element in cell array) I know how to get the length of each element, but how is possible to delete elements of a specific length?

2

2 Answers

7
votes

Just choose the ones that have more than 4 elements by logical indexing:

result = result(cellfun('length', result) >= 5);
0
votes

This code will do what you need. But the above answer from Mohsen is very compact and nice.

result{1}= 1;
result{2}= {2 3 4 5 6 7 8};
result{3}= {9 10 11 12 13 14 16 17 18};
result{4}= {19 20 21};

i = 1;
while i<=size(result,2)
    if size(result{i},2)<5
        result(i)=[];
    end
    i = i+1;
end