RunMat
GitHub

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

NameTypeRequiredDefaultDescription
AAnyYesInput array.
axesAnyNo[]Dimension selector, vector of dimensions, or "all".
nanflagStringScalarNo"includenan"NaN handling mode: "includenan" or "omitnan".

Returns

NameTypeDescription
MNumericArrayMedian reduction result.

Errors

IdentifierWhenMessage
RunMat:median:InvalidArgumentDimension selectors, nanflags, or argument ordering are invalid.median: invalid argument
RunMat:median:InvalidInputInput values cannot be converted to supported median reduction domains.median: invalid input
RunMat:median:InternalMedian reduction fails due to tensor allocation or device fallback internals.median: internal reduction failure

How median works

  • median(X) on an m × n matrix 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 in X and 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') ignores NaN values; if every element is NaN, the result is NaN.
  • median(..., 'includenan') (default) propagates NaN when any value in the slice is NaN.
  • Empty slices return NaN values 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 = 5

Computing the median of an even-length vector with averaging

x = [1 4 9 10];
m = median(x)

Expected output:

m = 6.5

Column-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.5

Median 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.

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

Rounding

ceil · fix · floor · mod · rem · round

Factor

chol · eig · lu · qr · svd

Solve

cond · det · inv · linsolve · norm · null · pinv · rank · rcond · rref

Symbolic

digits · int · limit · sym · syms · vpa

Fft

fft · fft2 · fftshift · ifft · ifft2 · ifftshift

Interpolation

interp1 · interp2 · pchip · ppval · spline

Ode

ode15s · ode23 · ode45

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how median is executed, line by line, in Rust.

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.