mean — Compute arithmetic means in MATLAB and RunMat.
mean(X) computes arithmetic means along the first non-singleton dimension. Select a dimension, dimension vector, or all to change the reduction; missing-value, output-class, and weighted forms have separate controls.
Syntax
M = mean(A)
M = mean(A, dim)
M = mean(A, "all")
M = mean(A, missingflag)
M = mean(A, outtype)
M = mean(A, dim, missingflag)All supported mean forms
M = mean(A)
M = mean(A, dim)
M = mean(A, "all")
M = mean(A, missingflag)
M = mean(A, outtype)
M = mean(A, dim, missingflag)
M = mean(A, missingflag, dim)
M = mean(A, vecdim)
M = mean(___, Weights=W)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
dim- Type
Any- Required
- No
- Default
[]- Description
- Dimension selector or vector of dimensions.
all- Type
StringScalar- Required
- No
- Default
"all"- Description
- Reduce across all dimensions.
missingflag- Type
StringScalar- Required
- No
- Default
"includemissing"- Description
- Missing-data handling mode: "includemissing" or "omitmissing".
outtype- Type
StringScalar- Required
- No
- Default
"default"- Description
- Output class specifier: "double", "default", or "native".
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
- Mean reduction result.
Errors
RunMat:mean:InvalidArgument- When
- Dimension, missing-data, weights, or output class argument grammar is invalid.
- Message
mean: invalid argument
RunMat:mean:InvalidInput- When
- Input values cannot be converted to supported mean reduction domains.
- Message
mean: invalid input
RunMat:mean:Internal- When
- Reduction execution fails due to conversion, provider, allocation, or coercion operations.
- Message
mean: internal reduction failure
Dimensions and missing values
For an m-by-n matrix, mean(X) returns a 1-by-n row of column means. mean(X,2) returns an m-by-1 column of row means. mean(X,"all") reduces every dimension to a scalar. mean(X,vecdim) reduces each selected dimension and preserves the others; dimensions beyond ndims(X) leave the corresponding values unchanged.
"includenan" is the default and propagates NaN in an affected slice. "omitnan" ignores NaN observations and returns NaN if none remain. Empty reduction slices return NaN with the selected output shape.
Complex floating inputs are reduced componentwise. Logical observations enter the numerical mean as zero or one and return double by default.
Output class and weighted means
The default output is double for integer and double data, and single for single data. "double" forces double; "native" returns the input class. Native integer means accumulate exactly and round once at the division boundary. "default" selects the ordinary class rule.
mean(X, ..., "Weights", W) admits nonnegative floating weights. Weighted means accept one operating dimension, but not a dimension vector or "all". Integer and logical weights are rejected. The proposed "like", prototype form is not currently admitted by mean; use an output-class control instead.
Execution and residency
Eligible resident reductions use the owning acceleration provider. Unsupported provider forms, including NaN omission, can gather to the host through the owner's transfer path. The admitted output class and residency are restored afterward. This is runtime-owned preparation, not a claim that every form has a GPU kernel.
Automatic placement may choose a device when the shared planner finds a benefit; callers can use gpuArray to explicitly request residency. Mean is a reduction/fusion boundary rather than an elementwise fused operation.
Examples
Column and row means
A = [1 2 3; 4 5 6];
colMeans = mean(A);
rowMeans = mean(A, 2);
colMeans
rowMeansExpected output:
colMeans = [2.5 3.5 4.5]
rowMeans = [2; 5]Ignore NaN observations
values = [1 NaN 3];
avg = mean(values, 'omitnan')Expected output:
avg = 2Mean of all elements
B = reshape(1:12, [3 4]);
overall = mean(B, 'all')Expected output:
overall = 6.5Reduce selected dimensions
C = cat(3, [1 2; 3 4], [5 6; 7 8]);
slice_means = mean(C, [1 3])Expected output:
slice_means = [4 5]Preserve resident single precision
G = gpuArray(single([1 3; 5 7]));
mu = mean(G, 'all');
result = gather(mu)Expected output:
result = single(4)Ignore NaNs in a resident input
G = gpuArray([1 2 NaN; 3 4 5]);
means = mean(G, 2, 'omitnan');
result = gather(means)Expected output:
result = [1.5; 4]Using mean with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how mean changes the result.
Run a small mean example, explain the result, then change one input and compare the output.
FAQ
When should I use mean?⌄
Use mean for the arithmetic average along the default or selected dimensions. For a weighted average, pass "Weights" and floating weights.
What shape does mean(A) return?⌄
The selected dimension becomes size one. For an m-by-n matrix, the default result is a 1-by-n row of column means.
How do I select a dimension or several dimensions?⌄
Pass a positive dimension, such as mean(A,2), or a dimension vector, such as mean(A,[1 3]). Use "all" to reduce every element.
What happens to an all-NaN slice?⌄
With "omitnan", a slice with no retained observations returns NaN. With the default "includenan", any NaN makes its slice's result NaN.
Can mean work on GPU arrays?⌄
Yes. Eligible reductions can use a resident provider operation; forms unsupported by that provider gather through its owner. The output follows the admitted residency and output-class controls.
How are complex values handled?⌄
RunMat averages the real and imaginary components of complex floating inputs. A NaN in either component affects its output slice.
How do I control the output class?⌄
Use "native" to preserve the input class or "double" to request double. The default retains single for single input and returns double for integer or double input. mean does not currently admit a "like", prototype option.
Can a resident input remain on the GPU?⌄
Yes. Admitted resident reductions use the input's owning provider when possible; unsupported provider forms can evaluate on the host and restore the requested resident result.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · median · 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 mean is executed, line by line, in Rust.
- View the source for mean 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.