Search code examples
arraysmatlabcell

MATLAB: how to find indices of cells which have length greater than threshold?


Suppose I have a cell array defined as follows:

A = {[1:6],[1:4], [1:6],[1:4],[1:4],[1:6] };  

And I want to find the indices of cells with length greater than threshold, I thought this might work:

I = cellfun(@(x) find(length(A)>threshold), A, 'UniformOutput', false);

but it doesn't (it returns a 1x6 cell containing all 1's)

If anyone could help, it would be appreciated!

Thanks in Advance,

N


Solution

  • You're almost there:

    I = find(cellfun(@(x)(length(x)>threshold), A))
    

    You want find to be outside of the cellfun. cellfun is going to return a logical array of if the element of A is greater than threshold or not. You don't need the 'UniformOutput', false bit because you're returning a boolean for each cell, so the output is uniform.

    Lastly you had length(A) but that's the number of cells in A where as you actually want the length of the vector in each cell which is given by x in your code

    e.g.

    A = {[1:6], [1:4], [1:6], [1:4], [1:4], [1:6]};  
    thresold = 5;
    I = find(cellfun(@(x)(length(x)>threshold), A))
    
    I =
    
       1   3   6