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

36 views (last 30 days)
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.

Answers (3)

Matt J
Matt J on 18 Mar 2021
Edited: Matt J on 18 Mar 2021
rowmeans = sum(C,2)./sum(logical(C),2);

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

Adam Danz
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

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!