Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

matlab - Finding number of all nested cells in a complex cell

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:

enter image description here

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...