查找复杂单元格中所有嵌套单元格的数量

时间:2017-08-13 23:18:10

标签: matlab nodes cell cells

我有一个代表树结构的嵌套单元格:

CellArray={1,1,1,{1,1,1,{1,1,{1,{1 1 1 1 1 1 1 1}, 1,1},1,1},1,1,1},1,1,1,{1,1,1,1}};

我想在Matlab中找出节点的数量。我在下面放了一张简单的图片,可以帮助你更准确地理解我在寻找的东西:

enter image description here

感谢。

2 个答案:

答案 0 :(得分:2)

如果我理解正确,你需要细胞元素的数量,它们本身就是细胞。 然后,您可以递归遍历您的单元格(和数字),并与iscell一起查看哪些元素是单元格。请参阅以下内容,其中totnod最终给出节点数。

ind=cellfun(@iscell, Chains);
totnod=sum(ind);
oldtmp=Chains(ind);
while ~isempty(oldtmp)
       newtmp={};
       for i=1:length(oldtmp)
           ind=cellfun(@iscell, oldtmp{i});
           newtmp=[newtmp,oldtmp{i}(ind)];
           totnod=totnod+sum(ind);
       end
       oldtmp=newtmp;
end

答案 1 :(得分:2)

这是一种使用单个while循环和子单元重复连接的简单方法:

temp = CellArray;
nNodes = 0;
while iscell(temp)
  index = cellfun(@iscell, temp);
  nNodes = nNodes + sum(index);
  temp = [temp{index}];
end

问题中样本CellArray的结果:

nNodes =

     5