MATLAB: Does NaN==NaN give zero while isnumeric(NaN) and isreal(NaN) give 1

infisequalisnanisnumericisrealMATLABnan

Why does NaN==NaN give zero while isnumeric(NaN) and isreal(NaN) give 1?

Best Answer

This is not a contradiction or a bug in MATLAB, rather this is the way NaN is defined. The function call ISREAL(NaN) returns 1 (true) because NaN has no imaginary part.
ISNUMERIC(NaN) is true as NaN is stored in a double array (i.e. is it not a char array, structure, cell array, etc.)
When you compare a NaN value with NaN, you are comparing two numbers which have no defined values. Thus, the comparison returns 0 (false).
The best logical test that can be performed on NaN uses the builtin ISNAN function. We strongly recommended that you use the ISNAN function to find NaN entries of a double array. This is illustrated in the following example:
b=NaN;
test=(b==NaN)
testisnan=isnan(b)
The above code results in
test =
0
testisnan =
1