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
採用された回答
その他の回答 (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
2016 年 1 月 3 日
Oh, noticed you said "cumulative" when read Jan's comment -- just replace sum w/ cumsum
cs=cumsum(cellfun(@sum,C));
zhirzh
2016 年 1 月 4 日
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
2016 年 1 月 4 日
Ah--the first was for 1D arrays (vectors)...see update for higher-dimensions.
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!