How to calculate the mean value of the non vero value in a vector?

1 回表示 (過去 30 日間)
M
M 2022 年 9 月 3 日
編集済み: James Tursa 2022 年 9 月 3 日
How to calculate the mean value of the non vero value in a vector?
For example there is a vector contains 3 values M = [0.7,0.3,0]
the mean value in this case should be 0.5

採用された回答

Star Strider
Star Strider 2022 年 9 月 3 日
M = [0.7,0.3,0];
Mmean = mean(M(M~=0))
Mmean = 0.5000

その他の回答 (1 件)

James Tursa
James Tursa 2022 年 9 月 3 日
編集済み: James Tursa 2022 年 9 月 3 日
Another way that doesn't require any data copying:
M = [0.7,0.3,0];
sum(M)/nnz(M)
ans = 0.5000
Be aware that if there are no non-zero elements, this will return NaN (same as Star's method).

カテゴリ

Help Center および File ExchangeError Functions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by