For elements in two arrays/columns of numbers, how can I find the average only if both elements are non-zero?

1 回表示 (過去 30 日間)
I have many external files. Each file contains two long columns of numbers, like this:
1 2
11 12
6 48
9 0.0
3 0.5
I can read each file in. Now I want to calculate the average of each row. In the column of results, for example, the elements would be:
(1 + 2 / 2)
(11 + 12 / 2)
(6 + 48 / 2) ...
The problem is, I don't want to take the average of rows where one element is zero. For example, I want the row that has
9 0.0
to be "9." Does anyone know how I can do, "calculate the average of each row, but leave the row alone if one element is zero?" I'm using 2016a. Thank you for any advice.

採用された回答

madhan ravi
madhan ravi 2020 年 7 月 21 日
matrix(matrix == 0) = nan
nanmean(matrix, 2)
  5 件のコメント
madhan ravi
madhan ravi 2020 年 7 月 21 日
cellfun(@(x) mean(x((x ~= 0) & (~isnan(x)))), num2cell(matrix, 2))
Srh Fwl
Srh Fwl 2020 年 7 月 21 日
Thank you, @madhan ravi. I found that I couldn't use "nanmean" because I don't have the statistics toolbox. However, I found an alternative and it works with the first part of your suggestion. Really appreciate it.
A = [3; 4; 5; 0]
B = [7; 8; 9; 10]
C = [A(:), B(:)]
C(C == 0) = nan
D = mean(C,2,'omitnan')

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by