Find sum of matrices, of different sizes, in a cell

I have n matrices with different sizes in a cell and I need to find the cumulative sum, without using a for loop.
With a for loop, here is my approach
% C = cell containing n matrices
% size(C) = n, 1
total = 0;
for i = 1:n
total = total + sum(sum(C{i}))
end

2 Comments

Is this a homework question?
No. To be precise, I am taking part in a Coursera course - Intro to ML, by Andrew Ng. In one part, I need to find sum of N 2d matrices. for-loop was the obvious solution. I just want to find out some other solution that does not require loops.

Sign in to comment.

 Accepted Answer

It's arguable that cellfun is not a loop, but here is one way to do it
C{1}=magic(3);
C{2}=magic(5);
total = cumsum(cellfun(@(c) sum(c(:)), C)) %for cumulative sum
%or
total = sum(cellfun(@(c) sum(c(:)), C)) %equivalent to your example

More Answers (1)

dpb
dpb on 3 Jan 2016
Edited: dpb on 4 Jan 2016
s=sum(cellfun(@sum,C));
ADDENDUM For more than 1D cells, sum returns sums by column instead of single total sum. Use an anonymous function instead of native summation--
s=sum(cellfun(@(x) sum(x(:),C));
Here, use the Matlab idiom X(:) to return the vector/matrix/array X as a 1D column vector.

4 Comments

Oh, noticed you said "cumulative" when read Jan's comment -- just replace sum w/ cumsum
cs=cumsum(cellfun(@sum,C));
It didn't work.
C=cell(2,1);
C{1}=magic(3);
C{2}=magic(5);
cumsum(cellfun(@sum,C));
error: cellfun: all values must be scalars when UniformOutput = true
error: evaluating argument list element number 1
setting 'UniformOutput' to false is not going to help, it's just going to output a cell array that won't agree with cumsum.
Ah--the first was for 1D arrays (vectors)...see update for higher-dimensions.

Sign in to comment.

Categories

Asked:

on 3 Jan 2016

Edited:

dpb
on 4 Jan 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!