Skip to main content
v2026.11,986 entries · CC-BY 4.0

MATLAB Median Function: Syntax, Arrays & NaN Guide

Learn how to use the MATLAB median function across vectors, matrices, and 3D arrays, including omitnan missing-data handling and open-source alternatives.

Written and maintained by CASRAI Editorial Board

Published

On this page

In MATLAB, the median() function computes the median value—the 50th percentile—of vectors, two-dimensional matrices, and multidimensional arrays. As a robust non-parametric measure of central tendency, the median separates the higher half of a dataset from the lower half. Unlike the arithmetic mean, the sample median remains resilient against severe outliers and heavy-tailed noise. The built-in median() function supports directional dimension reductions, multi-axis slicing with vector dimensions, grand medians using "all", and missing-data exclusion via "omitnan".

What it is used for in research

Calculating the median is essential across empirical science, biomedical signal processing, astronomical photometry, and quantitative economics. When research datasets contain skewed distributions, measurement dropouts, or non-Gaussian instrumentation noise, the median provides a stable location estimator with a breakdown point of 50%. This means up to half of the observations can be corrupted by extreme outliers without causing the median estimate to diverge, whereas a single aberrant data point can arbitrarily distort the MATLAB average function (mean()).

Key applications of the median function in scientific research include:

  • Electrophysiological and Biosignal Filtering: Eliminating high-amplitude movement artifacts and cardiac spikes in electroencephalogram (EEG) or electromyogram (EMG) recordings where Gaussian assumptions fail.
  • Environmental and Climate Data Aggregation: Summarizing multi-year precipitation, river discharge rates, or particulate pollution indices without distortion from extreme storm anomalies, evaluated alongside standard deviation in MATLAB.
  • Digital Microscopy and Astronomical Imaging: Performing median stacking across repeated astronomical exposures or confocal microscopy z-stacks to eliminate transient cosmic ray hits while preserving faint celestial structures.
  • Robust High-Throughput Matrix Reductions: Collapsing high-dimensional experimental matrices using vectorized array operations in MATLAB without introducing manual accumulation loops.

Median function matlab in research workflows

In quantitative workflows, understanding how the median function executes across matrix dimensions prevents systematic errors. While exploratory scripts often compute scalar summaries of 1D vectors, production data pipelines process 2D sensor arrays or 3D time-series cubes. Researchers often contrast global static medians with windowed local estimators using MATLAB moving average filters (such as movmedian() and movmean()) to isolate localized trend lines in volatile experimental series.

Install or access (official source only)

The median() function is a core built-in component of base MATLAB and does not require the Statistics and Machine Learning Toolbox or any third-party add-on. It is accessible through official MathWorks platforms and distributions:

  • MATLAB Desktop: Installed on Linux, Windows, or macOS systems through an authorized MathWorks Account using the official MathWorks installer.
  • MATLAB Online: Run inside any modern web browser without local software installation via the official MathWorks Cloud interface at matlab.mathworks.com.
  • MATLAB Mobile: Executed through verified MathWorks mobile applications on iOS and Android connected to a licensed cloud container or local workstation.
  • Command-Line Documentation: Accessed directly inside the MATLAB Command Window by executing doc median for the interactive Help browser or help median for immediate terminal syntax reference.

Step-by-step task (numbered, with menu names or commands exactly as in the current docs)

Follow these numbered steps to calculate medians across vectors, matrices, and multidimensional arrays, filter missing values, and configure output precision in MATLAB.

  1. Calculate the median of a 1D vector (odd vs. even length):

    Define a row or column vector. When the number of elements N is odd, median() returns the exact sorted middle element. When N is even, median() calculates the arithmetic average of the two central sorted values:

    % Odd number of elements (N = 5): middle element is 14.2
    v_odd = [12.4, 18.1, 14.2, 10.5, 16.5];
    m_odd = median(v_odd);
    % Returns: m_odd = 14.2000
    
    % Even number of elements (N = 6): average of 14.2 and 16.5
    v_even = [12.4, 18.1, 14.2, 10.5, 16.5, 20.0];
    m_even = median(v_even);
    % Returns: m_even = 15.3500
  2. Compute column-wise and row-wise medians in a 2D matrix:

    By default, calling median(A) on a matrix computes the median along dimension 1 (down each column), returning a row vector. Specify dimension 2 (median(A, 2)) to calculate medians across rows:

    % Create a 3x4 matrix (3 trials across 4 sensors)
    A = [10, 25, 30, 45;
         12, 22, 38, 42;
         14, 28, 34, 40];
    
    % Column medians (dim = 1, default): returns 1x4 row vector
    col_med = median(A);
    % Returns: [12, 25, 34, 42]
    
    % Row medians (dim = 2): returns 3x1 column vector
    row_med = median(A, 2);
    % Returns: [27.5; 27.0; 26.0]
  3. Calculate the overall grand median across all array elements:

    To compute the single median across all elements of a matrix or multidimensional array, use the "all" flag (or colon vectorization A(:)):

    % Calculate grand median over all 12 matrix elements
    grand_med = median(A, "all");
    % Returns: grand_med = 29
  4. Operate across multi-dimensional slices using vector dimensions (vecdim):

    When working with volumetric or multi-channel scientific data cubes, specify a vector of dimensions (vecdim) to collapse spatial planes while preserving temporal channels:

    % Simulate a 3D sensor array: 50 rows x 50 columns x 10 timepoints
    sensor_cube = rand(50, 50, 10);
    
    % Compute spatial median across dimensions 1 and 2 for each time slice
    spatial_med = median(sensor_cube, [1, 2]);
    
    % Squeeze singleton dimensions to produce a clean 10x1 temporal vector
    temporal_profile = squeeze(spatial_med);
  5. Exclude missing values (NaN) with omitnan:

    By default, MATLAB propagates NaN values, causing the median to evaluate to NaN if any missing values exist in the slice. Use the "omitnan" flag to exclude missing data:

    % Sensor readings with missing entries (NaN)
    sensor_data = [4.2, 5.1, NaN, 6.3, NaN, 5.9];
    
    % Default "includenan" returns NaN
    raw_res = median(sensor_data);
    % Returns: raw_res = NaN
    
    % Use "omitnan" to compute median from valid numeric observations
    clean_res = median(sensor_data, "omitnan");
    % Returns: clean_res = 5.5000
  6. Control output precision and native data types:

    By default, median() evaluates integer arrays to double precision. To preserve the input class (such as uint8 pixel arrays or int16 instrument signals), specify the 'native' output type:

    % 8-bit unsigned integer vector
    raw_bytes = uint8([10, 20, 30, 40]);
    
    % Default output evaluates to double (25.0)
    m_double = median(raw_bytes);
    
    % Native output preserves uint8 class (rounds to nearest integer: uint8 25)
    m_native = median(raw_bytes, "native");

Output and how to read it

The structure and data type of the output returned by median() reflect the geometry of the input array and the selected dimension:

  • Scalar Values: When the input is a 1D vector (row or column), or when passing the "all" argument, median() returns a single numeric scalar.
  • Dimension Reduction: When operating along dimension dim, the size of that dimension reduces to length 1. For an M × N matrix, median(A, 1) returns a 1 × N row vector of column medians, whereas median(A, 2) returns an M × 1 column vector of row medians.
  • Floating-Point Interpolation on Even Samples: For sorted data s with sample size N, if N is odd, the output is the middle observation s((N+1)/2). If N is even, the output is the arithmetic average of the two middle observations: (s(N/2) + s(N/2+1)) / 2. Therefore, even integer inputs yield a fractional double value (e.g., 2.5 for [1 2 3 4]) unless "native" is explicitly specified.
  • Missing-Data Flags: Under the default "includenan" behavior, any NaN within the slice results in NaN. When "omitnan" is specified, NaNs are discarded; if an entire dimension slice contains only NaNs, the output evaluates to NaN.

Troubleshooting

Researchers commonly encounter specific syntax or numerical challenges when running median computations in MATLAB. Use these verified solutions to diagnose and resolve them.

Why does median return NaN?

Issue: The calculated median evaluates to NaN even when only a single missing observation is present in the dataset.
Fix: Base MATLAB uses "includenan" by default. Add the "omitnan" flag to your function call: median(data, "omitnan"). The legacy standalone function nanmedian() from the Statistics Toolbox is deprecated in favor of base MATLAB median(..., "omitnan").

Why does median on a 2D matrix return a vector instead of a single number?

Issue: Calling median(A) on a matrix produces a row vector of multiple values rather than an overall summary scalar.
Fix: By default, MATLAB reduces along the first non-singleton dimension (dimension 1, down each column). To compute the grand median over all elements in the matrix, execute median(A, "all") or flatten the matrix using colon notation: median(A(:)).

Why does median of integer data return a decimal number?

Issue: An integer vector such as int32([10, 20, 30, 40]) returns the double value 25.0.
Fix: For an even sample size N, the median is defined as the arithmetic mean of the two middle elements. MATLAB evaluates this division in double precision by default to prevent integer truncation. If strict integer class retention is required, specify the 'native' flag: median(A, 'native').

Dimension argument out of bounds or invalid type

Issue: Supplying a non-integer or negative dimension index causes an error.
Fix: The dimension argument dim must be a positive integer scalar (1, 2, 3, …), and vecdim must be a vector of positive integers with unique entries. If dim exceeds the dimensionality of the array, MATLAB returns the original array unaltered.

Free alternatives (table)

Researchers seeking open-source software alternatives to MATLAB have several mature scientific computing options. The table below summarizes syntax, multidimensional capabilities, and missing-data flags across major environments.

Software License & Ecosystem 1D Vector Median Syntax 2D Matrix Reduction Syntax Missing Data Handling (NaN) Research Strengths
MATLAB Proprietary (MathWorks) median(x) median(A, 1) (cols)
median(A, 2) (rows)
median(A, "all")
median(x, "omitnan") Integrated engineering toolboxes, interactive Live Editor, optimized multi-threading.
GNU Octave Open Source (GNU GPL v3) median(x) median(A, 1) (cols)
median(A, 2) (rows)
median(A, "all")
median(x, "omitnan") Direct drop-in syntax compatibility with MATLAB scripts; zero code modification required.
Python (NumPy) Open Source (BSD 3-Clause) np.median(x) np.median(A, axis=0)
np.median(A, axis=1)
np.median(A) (all)
np.nanmedian(x) Broad scientific Python ecosystem, integration with SciPy, Pandas, PyTorch, and scikit-learn.
R Open Source (GNU GPL v2+) median(x) apply(A, 2, median) (cols)
apply(A, 1, median) (rows)
median(x, na.rm=TRUE) Extensive statistical modeling libraries, robust non-parametric packages (see MATLAB vs R).
Julia Open Source (MIT License) Statistics.median(x) median(A, dims=1)
median(A, dims=2)
median(skipmissing(x)) High-performance just-in-time compilation; expressive mathematical syntax for scientific computing.

FAQ

How does the MATLAB median function work?

The median() function sorts array elements in ascending order. If the sample size N is odd, it returns the single central element at position (N+1)/2. If N is even, it returns the arithmetic average of the two middle elements at positions N/2 and (N/2)+1.

How do I calculate the median of an entire matrix in MATLAB?

To calculate the median across all elements of a matrix or multidimensional array, specify the string "all" as the second argument: median(A, "all"). Alternatively, flatten the matrix into a single column vector using colon notation: median(A(:)). Both commands return a single scalar value.

How do I ignore NaN values in the MATLAB median function?

Include the "omitnan" flag in your function call: median(data, "omitnan"). MATLAB ignores all NaN entries and calculates the median using only valid numeric values. If all elements in the slice are NaN, the function returns NaN.

What is the difference between mean and median in MATLAB?

The mean() function calculates the parametric arithmetic average (sum divided by count), which is sensitive to extreme values. The median() function calculates the non-parametric 50th percentile, which provides robust central tendency even in the presence of heavy-tailed noise or severe outliers.

What is the difference between median and nanmedian in MATLAB?

The function nanmedian() was originally part of the Statistics and Machine Learning Toolbox to calculate medians while ignoring NaNs. In modern MATLAB, missing-data handling is integrated directly into core MATLAB via median(..., "omitnan"), rendering nanmedian() obsolete.

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about MATLAB Median Function: Syntax, Arrays & NaN Guide

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →