Search code examples
arraysmatlabsumcellcell-array

Sum M x N x P arrays in a R x 1 cell array element by element


I have a R x 1 cell array (R is the number of rows), where each entry is a M x N x P array. How do I sum each of the arrays in the cell array so each entry is added within each M x N x P array? Can I do this with cellfun?

I found this method in a similar question, but it returns a 1 x N x P array instead of the M x N x P array (see B) or I get an error "Error using cell2mat Too many input arguments" (see C).

M = 3;
N = 2;
P = 4;

A{1,1} = ones(M,N,P);
A{1,2} = 2*ones(M,N,P);
A{1,3} = 3*ones(M,N,P);

B = sum([A{:}]);
C = sum(cell2mat(A{:}),1);

I expect to get an M x N x P array but where each element is the sum of all of the elements in the i, j, k location of each of the cell entries.

B(1,1) = 6  % for all entries

Solution

  • Why do you have a cell array in the first place? You could store all the equal-sized 3D arrays into a 4D array, and then what you want is just the sum over the fourth dimension.

    If you really need a cell array, concatenate first along the fourth dimension to create the 4D array, then sum:

    result = sum(cat(4, A{:}), 4);
    

    If you need the cell array and concatenating into a 4D array gives you an error due to insufficient memory, you may need to resort to a loop:

    result = zeros(size(A{1}));
    for k = 1:numel(A)
        result = result + A{k};
    end
    

    You cannot use cellfun, at least not in a natural way, because cellfun applies a function to each cell, whereas you want to apply a function (sum) to each entry of all cells.