Search for the number of all nested cells in a complex cell

I have a nested cell that 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, which can help you understand what I'm looking for more accurately:

enter image description here

Thanks.

+1
source share
2 answers

If I understand correctly, you need the number of cell elements that are themselves cells. You can then go recursively through the cells (and numbers) of the cell and check with iscellto 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
source

while :

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

CellArray :

nNodes =

     5
+2

All Articles