Matrix Data Results Explanation

1 回表示 (過去 30 日間)
Augusto Gabriel da Costa Pereira
Augusto Gabriel da Costa Pereira 2023 年 9 月 16 日
コメント済み: Dyuman Joshi 2023 年 9 月 16 日
I used the following code, and you can see that in the second row of the fourth column, the result is zero and not NaN; it should be NaN as the result.
%
soma_total = nan(3, 4);
data1 = [nan nan 1 2; 1 2 nan nan; 1 2 nan nan];
data2 = [5 5 nan nan; 2 1 1 nan; nan nan 1 1];
%
result = nansum(cat(3, soma_total, data1, data2), 3);
%
disp(result);
The result was:
[5 5 1 2;
3 3 1 0;
1 2 1 1]
The result should be:
[5 5 1 2;
3 3 1 NaN;
1 2 1 1]
Does anyone have an idea to solve this?

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 9 月 16 日
編集済み: Dyuman Joshi 2023 年 9 月 16 日
nansum does not do what you are expecting it to do. Also, using nansum() is not recommended as you can see from its documentation page. Use sum instead -
Here's a workaround -
%
soma_total = nan(3, 4);
data1 = [nan nan 1 2; 1 2 nan nan; 1 2 nan nan];
data2 = [5 5 nan nan; 2 1 1 nan; nan nan 1 1];
%Dimension to operate on
dim = 3;
%defining the array
arr = cat(dim, soma_total, data1, data2);
%Finding indices for all elements which are NaN corresponding to the "dim" dimension
idx = all(isnan(arr),dim)
idx = 3×4 logical array
0 0 0 0 0 0 0 1 0 0 0 0
%If you want to use nansum instead, use this command
%result = nansum(arr,dim)
result = sum(arr,dim,'omitnan')
result = 3×4
5 5 1 2 3 3 1 0 1 2 1 1
%Converting the respective values back to NaN
result(idx) = NaN
result = 3×4
5 5 1 2 3 3 1 NaN 1 2 1 1
  2 件のコメント
Augusto Gabriel da Costa Pereira
Augusto Gabriel da Costa Pereira 2023 年 9 月 16 日
Thanks, mister.
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 16 日
You are welcome!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by