1

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?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
mona
  • 101
  • 6
  • 1
    Your cell structure is two deep. You need to do `ismember(b, A{1}{1})` if you're trying to get at the numeric values. – Andrew Janke May 04 '15 at 17:25
  • Can you give us more info on what your data structure is? Are those inner cell arrays always 3 elements long? Is the nesting depth always the same? – Andrew Janke May 04 '15 at 17:29
  • And will you always be comparing against one specific value, or a list of reference values? That is, will `b`, the value you're searching for, always be one long? – Andrew Janke May 04 '15 at 17:31

1 Answers1

4

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.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • if A = {1 {1 2 3};2 {4 5 6};3 {7}} how can the problem solved? – mona May 04 '15 at 17:43
  • Ah that wasn't part of your original question. So you're saying that your cell array can be a mixture of non-cells and cells? – rayryeng May 04 '15 at 17:48
  • Yes, exactly. My original question is solved, but this is another question!! – mona May 04 '15 at 18:35
  • @mona - You should perhaps make that another question. That requires a significant amount of additional work that doesn't merit simply editing my answer. – rayryeng May 04 '15 at 18:49