median — Compute medians in MATLAB and RunMat.
median(X) returns median values along a dimension or across selected elements. Default dimension behavior and tie handling follow MATLAB semantics.
Syntax
M = median(A)
M = median(A, dim)
M = median(A, vecdim)
M = median(A, "all")
M = median(A, [])
M = median(A, nanflag)All supported median forms
M = median(A)
M = median(A, dim)
M = median(A, vecdim)
M = median(A, "all")
M = median(A, [])
M = median(A, nanflag)
M = median(A, axes, nanflag)
M = median(A, nanflag, axes)
M = median(A, nanflag, "all")Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input array. |
axes | Any | No | [] | Dimension selector, vector of dimensions, or "all". |
nanflag | StringScalar | No | "includenan" | NaN handling mode: "includenan" or "omitnan". |
Returns
| Name | Type | Description |
|---|---|---|
M | NumericArray | Median reduction result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:median:InvalidArgument | Dimension selectors, nanflags, or argument ordering are invalid. | median: invalid argument |
RunMat:median:InvalidInput | Input values cannot be converted to supported median reduction domains. | median: invalid input |
RunMat:median:Internal | Median reduction fails due to tensor allocation or device fallback internals. | median: internal reduction failure |
How median works
median(X)on anm × nmatrix returns a row vector (1 × n) containing the column medians.median(X, 2)returns a column vector (m × 1) containing the row medians.median(X, 'all')reduces across every element inXand returns a scalar.median(X, vecdim)accepts a row or column vector of dimensions (for example[1 3]) and reduces each listed axis in a single call while preserving the others.- Even-length slices return the average of the two center elements after sorting.
- Logical inputs are promoted to double precision (
true → 1.0,false → 0.0) before computing the median. median(..., 'omitnan')ignoresNaNvalues; if every element isNaN, the result isNaN.median(..., 'includenan')(default) propagatesNaNwhen any value in the slice isNaN.- Empty slices return
NaNvalues that preserve MATLAB-compatible shape semantics. - Dimensions larger than
ndims(X)leave the input unchanged.
Does RunMat run median on the GPU?
When RunMat Accelerate is active, tensors that already live on the GPU remain on the device. The runtime asks providers for a dedicated median reduction. If the provider cannot supply one or cannot honour omitnan, RunMat gathers GPU data back to the host and executes the CPU path to preserve MATLAB semantics (including even-length averaging and ordering ties).
GPU memory and residency
You usually do NOT need to call gpuArray yourself in RunMat (unlike MATLAB).
In RunMat, the fusion planner keeps residency on GPU in branches of fused expressions. As such, in the above example, the result of the median call will already be on the GPU when the fusion planner has detected a net benefit to operating the fused expression it is part of on the GPU.
To preserve backwards compatibility with MathWorks MATLAB, and for when you want to explicitly bootstrap GPU residency, you can call gpuArray explicitly to move data to the GPU if you want to be explicit about the residency.
Since MathWorks MATLAB does not have a fusion planner, and they kept their parallel execution toolbox separate from the core language, as their toolbox is a separate commercial product, MathWorks MATLAB users need to call gpuArray to move data to the GPU manually whereas RunMat users can rely on the fusion planner to keep data on the GPU automatically.
Examples
Finding the median of an odd-length vector
x = [7 2 9 4 5];
m = median(x)Expected output:
m = 5Computing the median of an even-length vector with averaging
x = [1 4 9 10];
m = median(x)Expected output:
m = 6.5Column-wise median of a matrix
A = [1 3 5; 7 9 11; 2 4 6];
colMedians = median(A)Expected output:
colMedians = [2 4 6]Row medians while ignoring NaN values
A = [1 NaN 3; 4 5 NaN];
rowMedians = median(A, 2, 'omitnan')Expected output:
rowMedians = [2; 4.5]Median of all elements in a matrix
A = reshape(1:6, [3 2]);
overall = median(A, 'all')Expected output:
overall = 3.5Median of all elements on a GPU-backed tensor
G = gpuArray(randn(2048, 2048));
overall = median(G, 'omitnan');
result = gather(overall)Using median with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how median changes the result.
Run a small median example, explain the result, then change one input and compare the output.
FAQ
When should I use the median function?⌄
Use median when you need a robust measure of central tendency that resists outliers better than the mean.
How are NaN values handled?⌄
Use 'omitnan' to ignore NaN entries. The default 'includenan' propagates NaN if any element in the slice is NaN.
Does median convert logical values?⌄
Yes. Logical arrays are converted to double precision before the median is taken, matching MATLAB.
What happens with even-length slices?⌄
Even-length slices return the arithmetic mean of the two middle values after sorting, matching MATLAB behaviour.
Can I compute the median along a specific dimension?⌄
Yes. Pass a dimension index (>= 1) as the second argument: median(A, 2) reduces across rows.
What if I ask for a dimension larger than ndims(A)?⌄
RunMat treats trailing dimensions as having size 1, so the result is the original array unchanged.
Does median fully execute on the GPU today?⌄
When the active provider implements the reduce_median* hooks (e.g., the WGPU backend), the reduction stays on the device. Otherwise the runtime gathers to the CPU to guarantee MATLAB-compatible semantics.
Related Math functions
Reduction
all · any · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · mean · min · nnz · prod · std · sum · trapz · var
Elementwise
abs · angle · complex · conj · double · exp · expm1 · factorial · gamma · heaviside · hypot · imag · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · sign · single · sqrt · times
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cos · cosd · cosh · deg2rad · rad2deg · sin · sind · sinh · tan · tand · tanh
Structure
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how median is executed, line by line, in Rust.
- View the source for median in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.