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 件のコメント

Jan
Jan 2016 年 1 月 3 日
Is this a homework question?
zhirzh
zhirzh 2016 年 1 月 4 日
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.

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2016 年 1 月 4 日

1 投票

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

その他の回答 (1 件)

dpb
dpb 2016 年 1 月 3 日
編集済み: dpb 2016 年 1 月 4 日

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 件のコメント

dpb
dpb 2016 年 1 月 3 日
Oh, noticed you said "cumulative" when read Jan's comment -- just replace sum w/ cumsum
cs=cumsum(cellfun(@sum,C));
zhirzh
zhirzh 2016 年 1 月 4 日
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
Guillaume
Guillaume 2016 年 1 月 4 日
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
dpb 2016 年 1 月 4 日
Ah--the first was for 1D arrays (vectors)...see update for higher-dimensions.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2016 年 1 月 3 日

編集済み:

dpb
2016 年 1 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by