Best way to count all the elements in an array of cells?

I want to count all the elements in an array of cells, including in "nested" cells.

For an array of cells

>> C = {{{1,2},{3,4,5}},{{{6},{7},{8}},{9}},10} C = {1x2 cell} {1x2 cell} [10] 

The answer should be 10 .

One way is to use [C{:}] several times until there are no cells left, then use numel , but should there be a better way?

+6
source share
2 answers

Since you are only interested in the number of elements, here is a simplified version of flatten.m that @Ansari related to:

 function n = my_numel(A) n = 0; for i=1:numel(A) if iscell(A{i}) n = n + my_numel(A{i}); else n = n + numel(A{i}); end end end 

Result:

 >> C = {{{1,2},{3,4,5}},{{{6},{7},{8}},{9}},10}; >> my_numel(C) ans = 10 

EDIT:

If you feel lazy, we can let CELLPLOT do the counting:

 hFig = figure('Visible','off'); num = numel( findobj(cellplot(C),'type','text') ); close(hFig) 

In principle, we create an invisible figure, build an array of cells, count the number of β€œtext” objects, and then delete the invisible figure.

Here is the plot below:

screenshot

+9
source

Put this in a function (say flatten.m ) (code from MATLAB Central ):

 function C = flatten(A) C = {}; for i=1:numel(A) if(~iscell(A{i})) C = [C,A{i}]; else Ctemp = flatten(A{i}); C = [C,Ctemp{:}]; end end 

Then do numel(flatten(C)) to find the total number of elements.

If you don’t like to make a separate function, you can use this smart (but nasty) part of the code to define a smoothing function using anonymous functions (code from here ):

 flatten = @(nested) feval(Y(@(flat) @(v) foldr(@(x, y) ifthenelse(iscell(x) | iscell(y), @() [flat(x), flat(y)], @() {x, y}), [], v)), nested); 

In any case, you need to recursively align the array of cells and then count.

+2
source

Source: https://habr.com/ru/post/919569/


All Articles