Often, you represent missing or
unavailable data values in MATLAB® code with the
which stands for Not-a-Number.
The IEEE® floating-point arithmetic convention defines
the result of an undefined operation, such as 0/0.
When you perform calculations on an IEEE variable that
are often propagated to the final result. This behavior might render the result useless.
For example, consider a matrix containing the
3-by-3 magic square with its center element replaced with
a = magic(3); a(2,2) = NaN a = 8 1 6 3 NaN 7 4 9 2
Compute the sum for each column in the matrix:
sum(a) ans = 15 NaN 15
Notice that the sum of the elements in the middle column is
NaN value because that column contains a
NaNs from the data yields a
more meaningful result.
There are multiple strategies for removing
from array computations. Some functions, such as
sum, allow an optional input argument
that causes MATLAB to ignore
NaNs in the calculation.
Instead of using
sum(a) in the previous example,
you can use the following command:
sum(a,'omitnan') ans = 15 10 15
NaNin the second column is ignored and only the non-
NaNelements are summed.
It is often useful to identify where the
are located within an array before deciding on a strategy that removes
them. The functions
ismissing can identify which elements
of an array are
NaNs. For an input array
both of these functions return a logical array of the same size as
Elements of the logical array are 1 (
the corresponding elements of
and 0 (
NaNs from data.
from vectors and can remove entire rows or columns from a matrix if
there is at least one
NaN in that row or column.
The following table summarizes techniques for removing
By IEEE arithmetic convention,
the logical comparison
Find the indices of elements in a vector
|Remove any rows containing |
Remove any rows containing
are present in data, you can replace them with non-
fillmissing function offers
several methods for replacing missing values. You can fill
with the following:
'previous' — previous non-missing
'next' — next non-missing
'nearest' — nearest non-missing
'linear' — linear interpolation
of neighboring, non-missing values
'spline' — piecewise cubic
'pchip' — shape-preserving
piecewise cubic interpolation
fillmissing works on numeric
NaNs, it also operates on arrays,
tables, and timetables that can contain non-numeric data types such
string. For example, a missing
can be represented with
NaT, and a missing
is represented as
rmmissing all can operate on arrays,
tables, and timetables containing non-numeric data types.
For numeric 1-D data, you also can interpolate over missing
values with the
interp1 function. For more information,