简体   繁体   中英

The mean value of non-zero elements in each row of a sparse matrix

In the following sparse matrix:

A=[1 1 1 3];
C = sparse(A',1:length(A),ones(length(A),1),4,4);
C =

   (1,1)        1
   (1,2)        1
   (1,3)        1
   (3,4)        1

>>full(C)

ans =

     1     1     1     0
     0     0     0     0
     0     0     0     1
     0     0     0     0

How could I compute the mean value of non-zero elements in each row? I couldn't use the built-in mean function of matlab on these sparse matrices. I found this similar question and I can apply it to my problem

[row, ~, v] = find(C);
K>> rowmean = accumarray(row, v, [], @mean);
K>> rowmean 

rowmean =

     1
     0
     1

However, I would like to get zero value for the last row instead of this row being removed from the answer.

Approach 1

You can specify the output size as the third input ofaccumarray :

[row, ~, v] = find(C);
rowmean = accumarray(row, v, [size(C,1), 1], @mean);

If desired, you can use the sixth input of accumarray to obtain sparse output:

rowmean = accumarray(row, v, [size(C,1), 1], @mean, 0, true);

Approach 2

You can do something simpler like this. The result is sparse :

rowmean = sum(C, 2) ./ sum(C~=0, 2); % mean of nonzeros in each row, manually
rowmean(isnan(rowmean)) = 0; % replace NaN (resulting from 0/0) by 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM