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 CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by