george andrew
george andrew

Reputation: 471

How to sum up the corresponding elements for each element of a cell array

I have a cell array C, each element is an N1xN2xN3 matrix. I need to sum up all the correspondent elements in these cells, and result in a N1xN2xN3 matrix res, whose element equals to

res=zeros(size(C{1}));
for i=1:n_cell
    res=res.+C{i}
end

Is there a more efficient way to do it(without for loop?)? Thanks!

Upvotes: 1

Views: 320

Answers (1)

Suever
Suever

Reputation: 65430

You can concatenate the matrices along the 4th dimension and then sum along that.

res = sum(cat(4, C{:}), 4); 

Here is a general solution for any dimension of elements of C

res = sum(cat(ndims(C{1}) + 1, C{:}), ndims(C{1}) + 1);

If you're using octave you can simply use plus:

res = plus(C{:});

Unfortunately this last option won't work on MATLAB because plus in MATLAB only accepts two input arguments.

Upvotes: 2

Related Questions