# how to compute the mean value of non-zero elements in each row of a sparse matrix

4 views (last 30 days)
Zahra Sheikhbahaee on 18 Mar 2021
Commented: Adam Danz on 18 Mar 2021
I built the following sparse matrix:
o=[1 1 1 3];
C = sparse(o',1:length(o),ones(length(o),1),4,4);
C =
(1,1) 1
(1,2) 1
(1,3) 1
(3,4) 1
I would like to write a function in order to compute the mean value of non-zero elements in each row. I was wondering how it should be done because the usual built-in mean function of matlab does not work.
Thanks.

Matt J on 18 Mar 2021
Edited: Matt J on 18 Mar 2021
rowmeans = sum(C,2)./sum(logical(C),2);
Adam Danz on 18 Mar 2021
+1 neat, tidy & efficient

David Hill on 18 Mar 2021
a=C;
a(a==0)=nan;
mean(a,2,'omitnan');

Adam Danz on 18 Mar 2021
Assuming you want to preserve row-number in the case were entire rows are 0s,
mu = zeros(size(C,1),1);
mu(any(C~=0,2)) = mean(C(C~=0),2);
If you don't want to preserve row number,
mu = mean(C(C~=0),2);
Demo with a different sparse matrix,
i = [6 6 6 5 10 10 9 9]';
j = [1 1 1 2 3 3 10 10]';
v = [100 202 173 305 410 550 323 121]';
C = sparse(i,j,v) %note: row numbers are not sorted
C =
(6,1) 475 (5,2) 305 (10,3) 960 (9,10) 444
mu = zeros(size(C,1),1);
mu(any(C~=0,2)) = mean(C(C~=0),2)
mu = 10×1
0 0 0 0 475 305 0 0 960 444