# How to Count the NaN in MATLAB

Save

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.

### Things You'll Need

• MATLAB software
• Create or obtain an array containing NaN values. For instance "myArray = nan(m,n);" returns a m-by-n array of NaN values to the variable myArray.

• 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);

• Sum the values in myBooleanArray to determine the number of NaN values contained in myArray. In MATLAB, the sum operation only operates on the last dimension. So, in the above example of an m-by-n myArray, 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.

## References

• Photo Credit Ablestock.com/AbleStock.com/Getty Images
Promoted By Zergnet

## Related Searches

Check It Out

### Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.