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

1 次查看(过去 30 天)
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by