# How to Count the NaN in MATLAB

Written by chris daniels
• Share
• Tweet
• Share
• Pin
• Email

In the mathematical programming environment MATLAB, NAN is a special value meaning not a number. Values of Nan may arise in your variables in cases where an unusual operation occurs, such as dividing by zero. It can also happen in certain operations with infinity, represented as +Inf and -Inf in MATLAB. Nan values may also arise when importing data from a corrupted file or an unusual format. MATLAB offers special functions for dealing with arrays containing Nan values.

Skill level:
Easy

### Things you need

• MATLAB software

## Instructions

1. 1

Create or obtain an array containing Nan values. For instance "my Array = nan(m,n);" returns a m-by-n array of Nan values to the variable my Array.

2. 2

Determine whether each value is equal to Nan using the function "isnan()". This is necessary because normal logic operations, such as "==", are unable to compare Nan values. Following the example above:

myBooleanArray = isnan(myArray);

3. 3

Sum the values in myBooleanArray to determine the number of Nan values contained in my Array. In MATLAB, the sum operation only operates on the last dimension. So, in the above example of an m-by-n my Array, you would either need to call:

how_many_NaNs = sum(sum(myBooleanArray));

or:

how_many_NaNs = sum(reshape(myBooleanArray,m*n,1));

The second example code reshapes the array into a one-dimensional array, so that the sum function works on the entire array.

### Don't Miss

#### References

• All types
• Articles
• Slideshows
• Videos
##### Sort:
• Most relevant
• Most popular
• Most recent