recipes : programming : Finding NaNs

Problem

How do I find NaN values in a matrix or vector?

SolutionNaNs are values that are "Not a Number." They are defined as not being equal to any number and also not being equal to other NaNs. Therefore you can identify them in two different ways:

%Generate data and add some NaNs R=randn(1,15); R(R>0)=nan; %To identify the NaNs: isnan(R) %built-in function R~=R %roll your own version

Since nan==nan is always false, the second line of code uses the not-equals operator (~=) to identify NaNs. However, MATLAB's built-in isnan is optimised for the task and therefore faster. Still, it's useful to remember that nan==nan is always false: nasty bugs can be caused by not knowing things of that nature.