how to compute the mean value of non-zero elements in each row of a sparse matrix
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (3)
Adam Danz
le 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
mu = zeros(size(C,1),1);
mu(any(C~=0,2)) = mean(C(C~=0),2)
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!