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

1 vue (au cours des 30 derniers jours)
Julia
Julia le 7 Fév 2023
Modifié(e) : Voss le 10 Fév 2023
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?

Réponse acceptée

Voss
Voss le 7 Fév 2023
Modifié(e) : Voss le 10 Fév 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 commentaires
Julia
Julia le 9 Fév 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.
Voss
Voss le 10 Fév 2023
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by