How to calculate the average without taking zeros values?

115 visualizaciones (últimos 30 días)
afrya
afrya el 12 de Dic. de 2013
Comentada: Dongpeng Lin el 3 de Dic. de 2019
Hi, I have a large data list which has this form:
Y=
1 2 4 5 6 7 0 0 0 8 9 0 0 0 0... AVerage1=5.25
2 3 4 5 6 7 0 0 0 8 0 0 0 9 0... Average2=5.5
3 4 5 6 7 8 9 0 0 0 0 0 0 0 0... Average3=6
.
.
.
I would like to calculate the average of each row wihout taking zeros values.
Thanks in advance

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 13 de Dic. de 2013
[ii,~,v] = find(Y);
out = accumarray(ii,v,[],@mean);
  4 comentarios
Guanting SU
Guanting SU el 10 de Mzo. de 2019
This worked out really well!

Iniciar sesión para comentar.

Más respuestas (3)

Jos (10584)
Jos (10584) el 13 de Dic. de 2013
Editada: Jos (10584) el 13 de Dic. de 2013
No need of a loop:
A = [1 2 3 ; 10 0 30 ; 9 0 0]
rowMean = sum(A,2) ./ sum(A~=0,2)
Note that zeros do not contribute to sum(A) …
  4 comentarios
Jan
Jan el 26 de Abr. de 2018
Editada: Jan el 10 de Mzo. de 2019
+1: Easy and efficient.

Iniciar sesión para comentar.


Simon
Simon el 12 de Dic. de 2013
Hi!
for n = 1:size(Y, 1)
Average(n) = mean(Y(n, (Y(n, :) ~= 0)));
end

Mech Princess
Mech Princess el 5 de Mzo. de 2019
mean(nonzeros(X))
Y=[1 2 4 5 6 7 0 0 0 8 9 0 0 0 0; ...
2 3 4 5 6 7 0 0 0 8 0 0 0 9 0;...
3 4 5 6 7 8 9 0 0 0 0 0 0 0 0];
for i=1:3
mean(nonzeros(Y(i,:)))
end

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by