Matlab  NaN and Inf
Introduction
If in matlab you type 1/0
you'll get
Warning: Divide by zero. (Type "warning off MATLAB:divideByZero" to suppress this warning.) ans = Inf
which is fair enough  it's potentially useful to for 1/0 to result in
infinity. If you type 0/0
you'll get
Warning: Divide by zero. (Type "warning off MATLAB:divideByZero" to suppress this warning.) ans = NaN
NaN
means "Not a Number"  i.e. the result is undefined.
Both these special values behave in predictable ways. Any mathematical
operation involving a NaN
results in a NaN
.
And not surprisingly, most mathematical
operation involving Inf
result in Inf

Inf/0
and Inf^2
produce Inf
.
But Inf/Inf
is NaN
. So is InfInf
.
isnan
and isinf
can be use to detect these special
values. E.g.
if (any(isnan(m))) disp('NaN values in m') end if (any(isinf(m))) disp('Inf values in m') end
Note that
NaN==NaN
is false  you need to useisnan
to check if a value isNaN
NaN~=NaN
is true NaN
isn't a value so it can't be equal to anythingInf==Inf
is trueInf~=Inf
is false
To remove NaN
and Inf
elements from a vector
m
you can use
m=m(finite(m))
To replace the NaN
s by 0s you can use
m(isnan(m))=0
Graphics
NaN
s are ignored when plotting (so are Inf
s). This is useful if you want to
make holes in surfaces
z = peaks(20); z(4:8,4:8) = NaN*z(4:8,4:8); surf(z)