This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Median, ignoring NaN values


y = nanmedian(X)
y = nanmedian(X,'all')
y = nanmedian(X,dim)
y = nanmedian(X,vecdim)



y = nanmedian(X) is the median of X, computed after removing NaN values.

For vectors x, nanmedian(x) is the median of the remaining elements, once NaN values are removed. For matrices X, nanmedian(X) is a row vector of column medians, once NaN values are removed. For multidimensional arrays X, nanmedian operates along the first nonsingleton dimension.

y = nanmedian(X,'all') returns the median of all elements of X, computed after removing NaN values.

y = nanmedian(X,dim) takes the median along the operating dimension dim of X.


y = nanmedian(X,vecdim) returns the median over the dimensions specified in the vector vecdim, computed after removing NaN values. Each element of vecdim represents a dimension of the input array X. The output y has length 1 in the specified operating dimensions. The other dimension lengths are the same for X and y. For example, if X is a 2-by-3-by-4 array, then nanmedian(X,[1 2]) returns a 1-by-1-by-4 array. Each element of the output array is the median of the elements on the corresponding page of X.


collapse all

Find the column medians for matrix data with missing values.

X = magic(3);
X([1 6:9]) = NaN
X = 3×3

   NaN     1   NaN
     3     5   NaN
     4   NaN   NaN

y = nanmedian(X)
y = 1×3

    3.5000    3.0000       NaN

Find the median of a multidimensional array over multiple dimensions.

Create a 3-by-5-by-2 array X with some missing values.

X = reshape(1:30,[3 5 2]);
X([10:12 25]) = NaN
X = 
X(:,:,1) =

     1     4     7   NaN    13
     2     5     8   NaN    14
     3     6     9   NaN    15

X(:,:,2) =

    16    19    22   NaN    28
    17    20    23    26    29
    18    21    24    27    30

Find the median of each page of X by specifying dimensions 1 and 2 as the operating dimensions.

ypage = nanmedian(X,[1 2])
ypage = 
ypage(:,:,1) =


ypage(:,:,2) =


For example, ypage(1,1,1) is the median of the non-NaN elements in X(:,:,1).

Find the median of the elements in each X(:,i,:) slice by specifying dimensions 1 and 3 as the operating dimensions.

ycol = nanmedian(X,[1 3])
ycol = 1×5

    9.5000   12.5000   15.5000   26.5000   21.5000

For example, ycol(4) is the median of the non-NaN elements in X(:,4,:).

Alternative Functionality

Instead of using nanmedian, you can use the MATLAB® function median with the input argument nanflag specified as the value 'omitnan'.

Extended Capabilities

See Also

| |

Introduced before R2006a