MATLAB Answers

how to sum matrics inside a cell array?

278 views (last 30 days)
Kobi on 6 Aug 2014
Commented: lingyun ding on 26 Nov 2017
i have 4 matrics inside a cell and i need to sum them all currenyly i use this:
the original R is a cell with 4 matrics


Sign in to comment.

Accepted Answer

dpb on 6 Aug 2014
Edited: dpb on 22 Apr 2017
Oh, misunderstood the query...that's simply
S =
1.3771 0.5139
1.1590 0.7149
>> all(all(S==R{1}+R{2}))
ans =
Just used two cells here, but works for any number. As noted elsewhere sizes must be commensurate.
ERRATUM Does NOT work as written for any number of cells; plus isn't as smart as I was thinking it was/is... :(
Instead use
As another poster noted, all cells must contain conformantly-sized arrays.
NB: The result will be class of the content of the cell (default double, of course).


Show 2 older comments
Fizza Tariq
Fizza Tariq on 22 Apr 2017
It's not working for me either, error:"too many input arguments"
dpb on 22 Apr 2017 bad, had tested only for two cells; I was thinking w/o checking that plus was enabled to handle a variable number of arguments but it isn't...see ERRATUM above Answer--dpb
lingyun ding
lingyun ding on 26 Nov 2017
Is there other methods to solve this problem? This methods is less efficient then the for-loop

Sign in to comment.

More Answers (2)

Evan on 6 Aug 2014
Edited: Evan on 6 Aug 2014
Are all the matrices in your cell array the same size? If so, this should work:
% Get random cell array with n cells. Here n = 3
A = {rand(4) rand(4) rand(4)}
n = size(A,2);
% Get size of matrices in cell.
matSize = size(A{1},1);
B = reshape(cell2mat(A),matSize,[],n);
% Sum 3D matrix along 3rd dimension
C = sum(B,3);
If they're different sizes, this either wont work or we need more information about how you want the different sizes handles (e.g. trimming, padding, etc.).


Sign in to comment.

dpb on 6 Aug 2014
One way, seems should be better but it's still first cup o' coffee this morning...
>> R={rand(2) rand(3)}
R =
[2x2 double] [3x3 double]
>> sum(cellfun(@(x) sum(x(:)),R))
ans =

  1 Comment

Kobi on 6 Aug 2014
this is not what i need i need to + sum the matrics like this A=rand(7)+rand(7)+rand(7)+.... and to recive one matrix each and every element in one matrix is added to another corresponding element the only problem is that all of the matrics are inside a cell

Sign in to comment.



Community Treasure Hunt

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

Start Hunting!