Search code examples
matlabindexingcell

How to sum the values of an MxN cell array?


How can I make the sum of values in an MxN cell array? I used cellfun('sum',CellArray{i}) in which, i refers to the MxN index of the CellArray. But because I used it in a loop to count the number of blocks, it gives me error for being out of index.

What's the right way to do that please?


Solution

  • I don't know if I got your problem entirely right. You just want the total sum of all elements of a cell array? Assuming they are doubles, you first need to transform your cell array into a matrix, and then you can use the normal sum function.

    % example data
    xCell = num2cell( magic(10) )
    

    gives you a a 10x10 cell array with some magic numbers from 1 to 100. The following creates a column-vector of all cell contents and sums them up:

    S = sum([xCell{:}])
    
    S =
    
            5050
    

    which is the result good ol' Mr. Gauss didn't need Matlab for.

    Alternatively if you're interested in the sum of all single rows or columns, you can use:

    S = sum(cell2mat(xCell),dimension)   % dimension = 1 or 2 (or 3)
    

    regarding your comment in your follow-up question, that you actually have complex doubles:

    use:

    S = sum( real( [xCell{:}] ) )