# 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==NaN` is false - you need to use `isnan` to check if a value is `NaN`
• `NaN~=NaN` is true - `NaN` isn't a value so it can't be equal to anything
• `Inf==Inf` is true
• `Inf~=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)
```
• © Cambridge University, Engineering Department, Trumpington Street, Cambridge CB2 1PZ, UK (map)
Tel: +44 1223 332600, Fax: +44 1223 332662