MATLAB Examples

Working with Data with Missing Values

Create a 3-by-3 matrix of sample data. Remove two data values by replacing them with NaN.

X = magic(3);
X([1 5]) = [NaN NaN]
X =

   NaN     1     6
     3   NaN     7
     4     9     2

Compute the sum of for each column of the sample data matrix using the sum function.

s1 = sum(X)
s1 =

   NaN   NaN    15

If a column contains a NaN value, then the sum function will return NaN as the sum of the data in that column.

For comparison, compute the sum for each column of the sample data matrix using the nansum function.

s2 = nansum(X)
s2 =

     7    10    15

If a column contains a NaN value, then the nansum function ignores the NaN value and returns the sum of the remaining values in the column.