Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum member sizes of a cell array

Tags:

arrays

matlab

I have a cell array,

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

I need to calculate the sum of lengths of fields of a, i.e. the answer should be 3+2=5. This can be done using for loop,

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

But, I need one line command without loops. Any thoughts?

like image 800
John Smith Avatar asked Dec 16 '22 14:12

John Smith


1 Answers

For a one-liner, use cellfun

sum(cellfun(@length,a))

cellfun applies the command length to each element of a, then sum adds the output.

like image 192
Jonas Avatar answered Dec 22 '22 00:12

Jonas