Search code examples
matlabcell-array

find the intersection of a cell array


I have a vector, let say as = [1 3 4] and I have 30 by 30 cell array. I want to check if the elements of vector as intersect with the elements of each cell or not? the cells may be 2D arrays of size n-by-2 (where n= 1 2 3 4,etc).

If the row in a cell has an intersection with that vector, it should return (1 or 0) & if the row has no intersection with that vector, it should return (0 or 1).

Example: If on of the cell arrays contains [ 1 8 ;6 9] , so the output is [1; 0].


Solution

  • Assuming cellarr to be input cell array, see if this approach works for you -

    out = cellfun(@(x) any(any(bsxfun(@eq,x,permute(as,[1 3 2])),2),3),cellarr,'un', 0)
    

    This would give you a cell array of all those matches for each cell. You can see their values with a call to celldisp(out).

    Sample run -

    as =
         1     3     4
    -----------------------------------
    cellarr{1,1} =
         1     8
         6     9
    cellarr{2,1} =
         7     4
         2     3
    cellarr{1,2} =
         4     3
    cellarr{2,2} =
         7     8
         2     3
         7     8
    -----------------------------------
    out{1,1} =
         1
         0
    out{2,1} =
         1
         1
    out{1,2} =
         1
    out{2,2} =
         0
         1
         0
    

    Edit: If you would like to find indices that do not have any zeros corresponding to their cell values in out, that is we intend to find cells where all rows have at least one element from as, you can use this modified code, assuming ca to be the input cell array (name changed here to keep the code compact) -

    mch = cellfun(@(x) all(any(any(bsxfun(@eq,x,permute(as,[1 3 2])),2),3)),ca,'un',0)
                                                       %// Find matches for all cells
    mch(cellfun('isempty',ca))={false} %// take care of empty cell condition
    [row_ind,col_ind] = find(cell2mat(mch)) %// row and column indices of good matches