IF.....OR with conditions

1 回表示 (過去 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 件のコメント
Carolina
Carolina 2015 年 4 月 9 日
all(isnan(A)) is perfect. thank you!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeElementary Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by