Search code examples
matlabcell-array

How to sum up values in corresponding indexes of cells?


I have a 1x24 cell array called chaining, whose each cell contains a 119x119 matrix:

enter image description here

I want to find the sum of each corresponding elements of all the cells, and store them in a matrix called result. That is, the (j,k)th element of result should contains the sum of the (j,k)th elements of all the matrices in the cell array chaining.

The code I wrote to do this is:

for j=1:size(chaining,2)
    for k=1:size(chaining,2)
        result(j,k) = sum(chaining{1,:}(j,k));
    end
end

But this gives error because apparently MATLAB can't aggregate cell arrays for some reason (i.e., the chaining{1,:} part).

Could anyone please show me how to go about doing this?


Solution

  • how about

    result = sum( cat(3, chaining{:}), 3 );
    

    What just happened here?
    First, we convert the cell array into a 3D array by "stacking" the 2D cell elements on the third dimension:

    cat(3, chaining{:})
    

    Once we have a 3D array of size 119-by-119-by-24 we can sum along the third dimension and get result of size 119-by-119:

    sum( ..., 3 );
    

    For more info see cat and sum help pages.


    BTW,
    If you insist on chaining{1,:}(jj,kk) type of solution (not recommended), you might find subsref command useful.