4

I have a complex cell array, ex:

A = {1 {2; 3};4 {5 6 7;8 9 10}};

How can I find an element in A? For example, I want to check whether 9 is in A or not!!

mona
  • 101
  • 6

1 Answers1

2

If you can have an arbitrary number of nesting levels for your cell arrays, you'll have to just recurse down all of them to check for the value. Here's a function that will do this:

function isPresent = is_in_cell(cellArray, value)

  f = @(c) ismember(value, c);
  cellIndex = cellfun(@iscell, cellArray);
  isPresent = any(cellfun(f, cellArray(~cellIndex)));

  while ~isPresent
    cellArray = [cellArray{cellIndex}];
    cellIndex = cellfun(@iscell, cellArray);
    isPresent = any(cellfun(f, cellArray(~cellIndex)));
    if ~any(cellIndex)
      break
    end
  end

end

This function will check the entries that aren't cell arrays for the value, then extract the entries that are cell arrays to remove one nesting layer. This is repeated until there are no more entries that are cell arrays, or the value is found.

gnovice
  • 125,304
  • 15
  • 256
  • 359