median — Find the middle value along selected dimensions.
median(X) finds the central value of each slice along the first non-singleton dimension. A dimension, dimension vector, or all selects other axes; missing-value and weighted forms have their own controls.
Syntax
M = median(A)
M = median(A, dim)
M = median(A, vecdim)
M = median(A, "all")
M = median(A, [])
M = median(A, missingflag)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, missingflag)
M = median(A, axes, missingflag)
M = median(A, missingflag, axes)
M = median(A, missingflag, "all")
M = median(___, Weights=W)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
axes- Type
Any- Required
- No
- Default
[]- Description
- Dimension selector, vector of dimensions, or "all".
missingflag- Type
StringScalar- Required
- No
- Default
"includemissing"- Description
- Missing-value handling mode.
Weights- Type
StringScalar- Required
- Yes
- Default
"Weights"- Description
- Weighting-scheme name.
W- Type
NumericArray- Required
- Yes
- Description
- Nonnegative single- or double-precision weighting scheme.
Returns
M- Type
NumericArray- Description
- Median reduction result.
Errors
RunMat:median:InvalidArgument- When
- Dimension selectors, missing flags, or argument ordering are invalid.
- Message
median: invalid argument
RunMat:median:InvalidInput- When
- Input values cannot be converted to supported median reduction domains.
- Message
median: invalid input
RunMat:median:Internal- When
- Median reduction fails due to tensor allocation or device fallback internals.
- Message
median: internal reduction failure
Dimensions and missing values
For an m-by-n matrix, median(X) returns a 1-by-n row of column medians. median(X,2) returns an m-by-1 column of row medians. A dimension vector reduces each selected axis while preserving the others; median(X,'all') finds one overall median. A dimension beyond the stored rank leaves values unchanged.
An odd-length slice selects its middle sorted value. An even-length slice takes the midpoint of its two central values. includenan is the default and propagates NaNs; omitnan ignores them, returning NaN if no observations remain. Empty floating slices return NaN in the selected output shape.
Classes and weights
Single and double data retain their floating class. Native integer data retain their integer class, including even-length medians rounded at the integer result boundary. Logical data return logical results rather than being promoted to double. Complex data are not currently accepted by this builtin.
median(X, ..., 'Weights', W) accepts nonnegative single- or double-precision weights and one operating dimension. Weighted medians cannot combine weights with a dimension vector or all; integer and logical weight arrays are rejected.
GPU execution
Eligible resident floating reductions use the input provider's median hooks. If the provider does not support the form, or NaN omission or weights require host calculation, the runtime gathers through the exact owner and restores the admitted class and residency when supported. Integer and logical values retain their exact class through the fallback.
Automatic placement may use a device when beneficial; explicit gpuArray requests device residency. Median is a fusion boundary rather than an elementwise fused operation.
Examples
Median of an odd-length vector
x = [7 2 9 4 5];
m = median(x)Expected output:
m = 5Midpoint of an even-length vector
x = [1 4 9 10];
m = median(x)Expected output:
m = 6.5Column medians
A = [1 3 5; 7 9 11; 2 4 6];
colMedians = median(A)Expected output:
colMedians = [2 4 6]Row medians with omitted NaNs
A = [1 NaN 3; 4 5 NaN];
rowMedians = median(A, 2, 'omitnan')Expected output:
rowMedians = [2; 4.5]Overall median
A = reshape(1:6, [3 2]);
overall = median(A, 'all')Expected output:
overall = 3.5Median of a resident array
G = gpuArray(single([1 3; 5 7]));
overall = median(G, 'all');
result = gather(overall)Expected output:
result = single(4)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 median?⌄
Use median for a measure of central tendency less affected by extreme observations than the arithmetic mean.
How are NaN values handled?⌄
Use omitnan to ignore NaNs. The default includenan propagates a NaN in an affected slice.
What happens for an even number of values?⌄
Median uses the midpoint of the two central sorted values; an integer result is rounded to its integer class.
What happens for logical input?⌄
RunMat preserves logical results for logical input. An all-empty logical reduction is not a supported logical output.
Can I select another dimension?⌄
Pass a positive dimension, a vector of dimensions, or all for every element. Weights accept only one operating dimension.
Can a resident input remain on the GPU?⌄
An eligible form uses the owning provider; unsupported forms calculate on the host and restore class and residency when supported.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var
Elementwise
abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8
Optim
acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fmincon · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
Trigonometry
acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Factor
chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.