Choosing the role of NaN elements in the sum environment of matrices

1 回表示 (過去 30 日間)
Richard Wood
Richard Wood 2024 年 3 月 25 日
コメント済み: Chunru 2024 年 3 月 25 日
Hello everyone
I would like to know what would be the best way to add element by element two matrices, a and b, which, for simplicity, could be defined as:
aa=[1 2; 3 NaN];
bb=[NaN 1; 2 NaN];
adding some conditions: i) if two elements in position (i,j) are different from NaN, add them and divide by the number of elements in that position other than NaN (for example, for position (2,2): (2+1)/2, and for position (1,1): 1/1), and ii) if two elements in position (i,j) are equal to NaN, the sum goes to NaN. So I was wondering which will be the an efficient way to do aa+bb under the i) and j) conditions to obtain:
cc=[1 3/2; 5/2 NaN];

回答 (1 件)

Chunru
Chunru 2024 年 3 月 25 日
aa=[1 2; 3 NaN];
bb=[NaN 1; 2 NaN];
cc = mean(cat(3, aa, bb), 3)
cc = 2x2
NaN 1.5000 2.5000 NaN
  2 件のコメント
Stephen23
Stephen23 2024 年 3 月 25 日
aa = [1,2; 3,NaN];
bb = [NaN,1; 2,NaN];
cc = mean(cat(3, aa, bb), 3, 'omitnan')
cc = 2x2
1.0000 1.5000 2.5000 NaN
Chunru
Chunru 2024 年 3 月 25 日
Yes. It should be with 'omitnan' option.

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

カテゴリ

Help Center および File ExchangeGPU Computing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by