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 Inf-Inf.
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==NaNis false - you need to useisnanto check if a value isNaNNaN~=NaNis true -NaNisn't a value so it can't be equal to anythingInf==Infis trueInf~=Infis false
To remove NaN and Inf elements from a vector
m you can use
m=m(finite(m))
To replace the NaNs by 0s you can use
m(isnan(m))=0
Graphics
NaNs are ignored when plotting (so are Infs). 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)
