How to calculate the average without taking zeros values?

174 ビュー (過去 30 日間)
afrya
afrya 2013 年 12 月 12 日
コメント済み: Dongpeng Lin 2019 年 12 月 3 日
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

採用された回答

Andrei Bobrov
Andrei Bobrov 2013 年 12 月 13 日
[ii,~,v] = find(Y);
out = accumarray(ii,v,[],@mean);
  4 件のコメント
Guanting SU
Guanting SU 2019 年 3 月 10 日
This worked out really well!
Dongpeng Lin
Dongpeng Lin 2019 年 12 月 3 日
Thank God

サインインしてコメントする。

その他の回答 (3 件)

Jos (10584)
Jos (10584) 2013 年 12 月 13 日
編集済み: Jos (10584) 2013 年 12 月 13 日
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 件のコメント
Jan
Jan 2018 年 4 月 26 日
編集済み: Jan 2019 年 3 月 10 日
+1: Easy and efficient.
Alvaro Espinoza Hernández
Alvaro Espinoza Hernández 2018 年 8 月 13 日
Excellent!!!! Thanks

サインインしてコメントする。


Mech Princess
Mech Princess 2019 年 3 月 5 日
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

Simon
Simon 2013 年 12 月 12 日
Hi!
for n = 1:size(Y, 1)
Average(n) = mean(Y(n, (Y(n, :) ~= 0)));
end
  1 件のコメント
afrya
afrya 2013 年 12 月 13 日
thank you for your answer,

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by