Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  programs >  matlab

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 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)
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: March 2004