IF.....OR with conditions

2 次查看(过去 30 天)
Carolina
Carolina 2015-4-9
评论: Carolina 2015-4-9
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.
Thank you for your help!

采纳的回答

Adam
Adam 2015-4-9
编辑:Adam 2015-4-9
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?
Addendum:
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

更多回答(1 个)

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

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by