Sum the sizes of the elements of a cell array

I have an array of cells,

a=cell(2,1); 
a{1,1}=[1 2 3];
a{2,1}=[4 5];

      

I need to calculate the sum of the field lengths a

i.e. the answer must be 3+2=5

. This can be done with a loop for

,

sum=0;
for i=1:size(a,1)
    sum = sum + size(a{i},2); 
end

      

But I need one line without loops. Any thoughts?

+3


source to share


2 answers


For a one-liner use cellfun

sum(cellfun(@length,a))

      



cellfun

applies the command length

to each item a

, then sum

adds the result.

+6


source


You can do it:



length( [ a{:} ] )

      

+5


source







All Articles