How to make a statement true for column 5-6?

1 回表示 (過去 30 日間)
Julia
Julia 2023 年 2 月 7 日
編集済み: Voss 2023 年 2 月 10 日
I have a matrix
M= [1 50 60 70 50 40
2 NaN 10 20 10 10
3 NaN 20 NaN NaN NaN
1 NaN 60 30 40 50
2 10 20 10 20 NaN
1 30 20 40 NaN 50
2 NaN 50 50 1 NaN];
I want to check that, for each row, whether it is ture that the element in column 2 is NaN and the elements in column 5-6 are both non-NaN. I tried to code like this:
P=isnan(M(:,2))&isfinite(M(:,5:6))
P = 7×2 logical array
0 0 1 1 0 0 1 1 0 0 0 0 1 0
However, the result is in 2 columns, column "NaN in column 2 and non-NaN in column 5" and column "NaN in column 2 and non-NaN in column 6".
Could anyone please tell me how to have the answer in 1 column?
I think this code works,
P=isnan(M(:,2))&isfinite(M(:,5))&isfinite(M(:,6))
P = 7×1 logical array
0 1 0 1 0 0 0
but is there a better way to express "column 5-6" instead of making a isfinite statement for each column seperately?

採用された回答

Voss
Voss 2023 年 2 月 7 日
編集済み: Voss 2023 年 2 月 10 日
'is there a better way to express "column 5-6"'
Yes.
You can use all(). Specifically, all(~isnan(__),2) where the 2 tells all() to operate over the columns (2nd dimension). ("All are non-NaN.")
Or you can use any(). Specifically, ~any(isnan(__),2). ("Not any are NaN.")
M = [1 50 60 70 50 40
2 NaN 10 20 10 10
3 NaN 20 NaN NaN NaN
1 NaN 60 30 40 50
2 10 20 10 20 NaN
1 30 20 40 NaN 50
2 NaN 50 50 1 NaN];
These three are equivalent:
P = isnan(M(:,2)) & ~isnan(M(:,5)) & ~isnan(M(:,6))
P = 7×1 logical array
0 1 0 1 0 0 0
P = isnan(M(:,2)) & all(~isnan(M(:,[5 6])),2)
P = 7×1 logical array
0 1 0 1 0 0 0
P = isnan(M(:,2)) & ~any(isnan(M(:,[5 6])),2)
P = 7×1 logical array
0 1 0 1 0 0 0
Note that I'm using ~isnan() where you used isfinite(). The difference is how Inf and -Inf are treated.
~isnan(Inf)
ans = logical
1
isfinite(Inf)
ans = logical
0
And since the rules you describe talk about NaN vs non-NaN and say nothing about finte vs infinite, I think it makes sense to use isnan and ~isnan.
  2 件のコメント
Julia
Julia 2023 年 2 月 9 日
Thank you so much for guiding me through the logic behind this question! And thank you for pointing out the difference between ~isnan and isfinite.
Voss
Voss 2023 年 2 月 10 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by