Search code examples
arraysmatlabcell-array

How can I check whether an element is in a nested cell array?


How can I check whether an element is in a nested cell array? ex:

A = {{4 5 6};{6 7 8}};
b = 5;

The function

ismember(b,A{1})

does not work. Is there any solution better than for-loop?


Solution

  • Because each element is a cell, you don't have a choice but to use cellfun combined with ismember, which is the same as using a loop in any case. Your cells are specifically two-deep (per Andrew Janke). Each cell element in your cell array is another cell array of individual elements, so there is no vectorized solution that can help you out of this.

    Assuming that each cell is just a 1-D cell array of individual elements, you would thus do:

    A = {{4 5 6};{6 7 8}};
    b = 5;
    out = cellfun(@(x) ismember(b, cell2mat(x)), A);
    

    Which gives us:

    out =
    
         1
         0
    

    This checks to see if the value b is in each of the nested cell arrays. If it is your intention to simply check for its existence over the entire nested cell array, use any on the output, and so:

    out = any(cellfun(@(x) ismember(b, cell2mat(x)), A));
    

    Because each cell element is a cell array of individual elements, I converted these to a numerical vector by cell2mat before invoking ismember.