Search code examples
matlabcellsparse-matrix

Matlab Mean over same-indexed elements across cells


I have a cell array of 53 different (40,000 x 2000) sparse matrices. I need to take the mean over the third dimension, so that for example element (2,5) is averaged across the 53 cells. This should yield a single (33,000 x 2016) output. I think there ought to be a way to do this with cellfun(), but I am not able to write a function that works across cells on the same within-cell indices.


Solution

  • You can convert from sparse matrix to indices and values of nonzeros entries, and then use sparse to automatically obtain the sum in sparse form:

    myCell = {sparse([0 1; 2 0]), sparse([3 0; 4 0])}; %// example
    
    C = numel(myCell);
    M = cell(1,C); %// preallocate
    N = cell(1,C);
    V = cell(1,C);
    for c = 1:C
        [m n v] = find(myCell{c}); %// rows, columns and values of nonzero entries
        M{c} = m.';
        N{c} = n.';
        V{c} = v.';
    end
    result = sparse([M{:}],[N{:}],[V{:}])/C; %'// "sparse" sums over repeated indices