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

1 view (last 30 days)
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?

Accepted Answer

Voss
Voss on 7 Feb 2023
Edited: Voss on 10 Feb 2023
'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 Comments
Julia
Julia on 9 Feb 2023
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!