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

18 次查看(过去 30 天)
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.

回答(3 个)

Matt J
Matt J 2021-3-18
编辑:Matt J 2021-3-18
rowmeans = sum(C,2)./sum(logical(C),2);

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

Adam Danz
Adam Danz 2021-3-18
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by