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.
0 个评论
回答(3 个)
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
mu = zeros(size(C,1),1);
mu(any(C~=0,2)) = mean(C(C~=0),2)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!