# IF.....OR with conditions

2 views (last 30 days)
Carolina on 9 Apr 2015
Commented: Carolina on 9 Apr 2015
Hi!
I have two vectors, call them A and B, and I want an IF loop to write them in a table if they aren't NaNs.
The expression
if isnan(A)
works, but I want to evaluate both vectors. I tried:
if isnan(A) || is nan(B)
and this doesn't work:
Error using | Matrix dimensions must agree
True, they are not the same size but I don't want to compare them! I just want to evaluate both. if I do 2 ifs, it won't work for my project.

Edited: Adam on 9 Apr 2015
isnan(A)
will produce a logical vector as its result containing 1s (true values) where there is a NaN and zeros elsewhere.
Likewise on vector B. So if you want a single result then you can use:
all( isnan(A) )
or
any( isnan(A) )
to give you a single logical telling you if all the values in A are NaN or if any of the value of A are NaN.
This can then be OR'd with the same for B as e.g.
if any( isnan(A) ) || any( isnan(B) )
You can also add in ~ to reverse (NOT) the logic if that is what you require, but it depends what condition you really want.
Your question didn't really specify what exactly you want to do with respect to vector A having some NaNs and some non-NaN values.
I'm not sure what you mean by an "If loop" though either. Is that just a typo or genuine confusion as to what an if statement is compared to a while or for loop when using vectors?
For completeness. If your vectors A and B are the same length the logical statement
isnan(A) | isnan(B)
(note the single | )
makes sense and can be very useful. It will produce another logical vector of equal length to A and B with the element-wise result of the OR logic - i.e. true where either the n th element of A or the n th element of B are NaN and false elsewhere
Carolina on 9 Apr 2015
all(isnan(A)) is perfect. thank you!

Thomas Koelen on 9 Apr 2015
N=NaN(1,3);
N2=NaN(1,4);
if any(isnan(N)) || any(isnan(N2))
end
any will give you a single logical value!