Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

This should do the trick, just initialize an empty array and sum over each element of the cell array. I don't see any way around using a for loop without concatenating it into one giant 3D array (which will almost definitely run out of memory)

running_sum=zeros(size(cell_arr{1}))
for i=1:length(cell_arr)
  running_sum=running_sum+cell_arr{i};
end
means = running_sum./length(cell_arr);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top