Summing arrays within a cell array.

I've got a cell array which consists of 501 4D arrays, I want to sum all of these together and output a single 4D array. I've tried using sum and plus but get the error saying too many input arguments.

1 件のコメント

Jan
Jan 2018 年 1 月 4 日
Please post the code, instead of telling what it should do, and a copy of the complete error message, instead of a short rephrasing. Thanks.

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

 採用された回答

Jan
Jan 2018 年 1 月 4 日
編集済み: Jan 2018 年 1 月 4 日

0 投票

What about a simple loop?
S = 0;
for k = 1:numel(C)
S = S + C{k};
end
You can check if a vectorized code is faster:
S = sum(cat(5, C{:}), 5);
While it does not have the overhead for the loop, it requires a large temporary array.

4 件のコメント

mathman
mathman 2018 年 1 月 4 日
The loop worked! The vectorized code gave the error:
Error using cat
Requested 81x81x1x200901 (9.8GB) array exceeds maximum array size preference. Creation of arrays greater
than this limit may take a long time and cause MATLAB to become unresponsive. See array size limit or
preference panel for more information.
Jan
Jan 2018 年 1 月 4 日
This is a nice example for a problem, which does not profit from vectorization.
mathman
mathman 2018 年 1 月 6 日
Sorry, I just want to make sure I'm understanding the loop correctly. So S would initially be 0. It would then be added to the first cell array C{1}. This would change the value of S to equal to C{1} which would then be added to C{2} and so on?
Jan
Jan 2018 年 1 月 7 日
@mathman: Only the variable on the left side of the assignment operator "=" is modified. This means, that S is 0 initially. Then in the first iteration, S is replaced by S + C{1}. In the 2nd iteration, this new S is replaced by S + C{2}, and so on. This is equivalent to (assuming that C has 5 elements):
S = C{1} + C{2} + C{3} + C{4} + C{5}
You can simply try if:
C = {1,3,4,7,8}
S = 0;
for k = 1:numel(C)
fprintf('Loop %d\n', k);
disp(C{k})
disp(S)
S = S + C{k};
disp(C{k})
disp(S)
end

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2018 年 1 月 4 日

コメント済み:

Jan
2018 年 1 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by