John Smith
John Smith

Reputation: 428

Sum member sizes of a cell array

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?

Upvotes: 4

Views: 596

Answers (2)

plesiv
plesiv

Reputation: 7028

You could do this:

length( [ a{:} ] )

Upvotes: 5

Jonas
Jonas

Reputation: 74940

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.

Upvotes: 7

Related Questions