How to find an element in a complex cell?

时间:2015-05-04 19:32:55

标签: matlab

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!!

1 个答案:

答案 0 :(得分:1)

如果您的单元格数组可以有任意数量的嵌套级别,那么您只需要将所有嵌套级别递归以检查该值。这是一个可以执行此操作的功能:

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

此函数将检查不是值的单元格数组的条目,然后提取单元格数组的条目以删除一个嵌套层。重复此操作,直到没有更多的单元格数组或找到值为止。