Search code examples
arraysmatlabmatrixcell

Array filtering based on cell content


I have a cell of length n where each number is a numeric array of varying length.

eg

C = { [ 1 2 3] ; [ 4 1 ] ; [ 28 5 15] }

And a 4xn numeric array

eg

A = [[ 1 2 3 4] ; [ 5 6 7 8 ] ; [ 9 10 11 12]]

I'd like to filter the numeric array A based on the content in cell C.

The filter may be to return all rows in A which have a 28 in the corresponding element in C.

ans = [ 9 10 11 12 ]

Or, the filter may be to return all rows in A which have a 1 in the first column of C or a 5 in the second column of C.

ans =  [[ 1 2 3 4] ; [ 9 10 11 12]]

Hope this makes sense! It's the correlation the vectors in the cell to the main array which I'm struggling with


Solution

  • Cellfun makes this relatively straightforward - design the function that returns a logical vector matching your filter requirements (i.e., it maps each vector in C to a single logical scalar depending on the conditions), and make this the first input to cellfun. Your cell array is the second input. The output of this will be your nx1 "filter" vector. Then apply this along the dimension of A that has length n, and use a colon operator in the other dimension.

    First one:

    A(cellfun(@(x) ismember(28, x), C), :);
    ans =
     9    10    11    12
    

    Second one:

    A(cellfun(@(x) (x(1)==1) || (x(2)==5), C), :)
    ans =
         1     2     3     4
         9    10    11    12