Finding number of all nested cells in a complex cell

戏子无情 提交于 2019-12-18 07:18:36

问题


I have a nested cell which represents a tree-structure:

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}};

I want to find out the number of nodes in Matlab. I put a simple picture below that might help you understand what I am looking for more precisely:

Thanks.


回答1:


If I understand correctly, you want the number of cell elements, that are themselves cells. Then you can go recursively through your cell cells (and numbers) and check with iscell to see which elements are cells. See the following, where totnod ultimately gives the number of nodes.

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



回答2:


Here's a simpler approach using a single while loop and repeated concatenation of the sub-cells:

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

And the result for the sample CellArray in the question:

nNodes =

     5


来源:https://stackoverflow.com/questions/45665684/finding-number-of-all-nested-cells-in-a-complex-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!