median

Median value along a dimension.

Category: Language Fundamentals > Data Types

Syntax

M = median(A)

Median of a vector, or of each column of a matrix.

M = median(A, dim)

Median along dimension dim.

M = median(A, 'all')

Median of all elements.

M = median(___, nanflag)

'omitnan' ignores NaN values; 'includenan' (default) lets them make the result NaN.

Description

The median is the middle value after sorting. With an even count it is the average of the two middle values, so median([3 1 2 10]) is 2.5. Because it ignores how extreme the largest and smallest values are, a few outliers hardly move it, unlike the mean. A NaN in the data gives NaN unless 'omitnan' is used; the median of an empty array is NaN.

Input arguments

A
Numeric or logical array.
dim
Dimension to work along.

Output arguments

M
The medians; the working dimension has size 1.

Example

Median versus mean

x = [3 1 2 10];
median(x)
median([1 2; 3 4])
median([1 NaN 3], 'omitnan')
mean([1 2 3 100])
median([1 2 3 100])
Output
ans = 2.5000
ans = 1×2

     2     3
ans = 2
ans = 26.5000
ans = 2.5000

See also

mean mode sort prctile quantile