Find sum of matrices, of different sizes, in a cell
Show older comments
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
Accepted Answer
More Answers (1)
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
dpb
on 3 Jan 2016
Oh, noticed you said "cumulative" when read Jan's comment -- just replace sum w/ cumsum
cs=cumsum(cellfun(@sum,C));
zhirzh
on 4 Jan 2016
Guillaume
on 4 Jan 2016
setting 'UniformOutput' to false is not going to help, it's just going to output a cell array that won't agree with cumsum.
dpb
on 4 Jan 2016
Ah--the first was for 1D arrays (vectors)...see update for higher-dimensions.
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!