Search code examples
matlabmatrixsumvectorizationbinary-operators

Adding three or more matrices in one command


For example, in Octave I can do the following:

A = randn(2);
B = randn(2);
C = randn(2);
plus(A, B, C)

This does not work in MATLAB however, because the plus function in MATLAB only allows two input arguments.

For context, I have a cell array full of large, sparse matrices and I need to add all of them together. I am looking for an efficient way to do this. For example, in Octave I would do the following:

D = {A, B, C};
plus(D{:})

But this doesn't work in MATLAB for the reason explained above.


Solution

  • If all matrices inside the cell array have the same size then you can concatenate each of them in a separate slice of a 3D array and then sum along the 3rd dimension i.e.

    sum(cat(3,D{:}),3)
    

    This is not valid if your cell array is a combination of scalars and matrices, or if you're doing implicit expansion with plus.


    If the cell array has combination of matrices of different size then just use a loop. Loops have been significantly improved in the newer versions of MATLAB.

    req = 0;
    for k = 1:numel(D)
        req = req + D{k}; %or bsxfun(@plus, req, D{k}) for < R2016b
    end