How to make a statement true for column 5-6?
    3 views (last 30 days)
  
       Show older comments
    
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))
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))
but is there a better way to express "column 5-6" instead of making a isfinite statement for each column seperately?
0 Comments
Accepted Answer
  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 = isnan(M(:,2)) & all(~isnan(M(:,[5 6])),2)
P = isnan(M(:,2)) & ~any(isnan(M(:,[5 6])),2)
Note that I'm using ~isnan() where you used isfinite(). The difference is how Inf and -Inf are treated.
~isnan(Inf)
isfinite(Inf)
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.
More Answers (0)
See Also
Categories
				Find more on Logical in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
