var — Compute sample or population variance.
var(A) measures spread along the first non-singleton dimension. Normalization, selected axes, and missing-value handling can be controlled separately.
Syntax
V = var(A)
V = var(A, w)
V = var(A, w, dim)
V = var(A, w, vecdim)
V = var(A, w, "all")
V = var(A, nanflag)All supported var forms
V = var(A)
V = var(A, w)
V = var(A, w, dim)
V = var(A, w, vecdim)
V = var(A, w, "all")
V = var(A, nanflag)
V = var(A, w, nanflag)
V = var(A, w, dim, nanflag)
V = var(A, w, nanflag, dim)
V = var(A, w, [], nanflag)
V = var(A, w, nanflag, "all")Inputs
A- Type
Any- Required
- Yes
- Description
- Single- or double-precision input array.
w- Type
Any- Required
- No
- Default
0- Description
- Normalization flag (0 sample, 1 population) or [] placeholder.
axes- Type
Any- Required
- No
- Default
[]- Description
- Dimension selector, vector of dimensions, or "all".
nanflag- Type
StringScalar- Required
- No
- Default
"includemissing"- Description
- Missing-value mode: "includemissing"/"includenan" or "omitmissing"/"omitnan".
Returns
V- Type
NumericArray- Description
- Variance reduction result.
Errors
RunMat:var:InvalidArgument- When
- Argument grammar, dimensions, normalization, or missing-value selectors are invalid.
- Message
var: invalid argument
RunMat:var:InvalidInput- When
- Input values are outside the supported floating var reduction domains, including integer data.
- Message
var: invalid input
RunMat:var:ComplexUnsupported- When
- Input value is complex for a path that currently supports only real reductions.
- Message
var: complex inputs are not supported yet
RunMat:var:Internal- When
- Execution fails due to provider, conversion, gather, or tensor allocation internals.
- Message
var: internal reduction failure
Normalization and axes
var(A) uses the sample normalization: it divides the squared-deviation sum by n-1 when a slice has more than one observation. var(A,1) uses the population denominator n; var(A,0) and var(A,[]) select the sample form. A scalar observation returns zero.
var(A,flag,dim) chooses one axis; var(A,flag,vecdim) reduces several, and var(A,flag,'all') reduces all elements. For a non-scalar array, a selected dimension beyond the stored rank keeps the shape and produces zeros in the input class. Empty selected slices return NaN with the selected shape. An empty dimension argument after the normalization placeholder is rejected, unlike std.
includenan is the default and propagates NaNs. omitnan ignores them, returning NaN when no observations remain. A vector in the normalization-flag position is not a supported weighted variance and receives an error.
Supported classes
Real double and single inputs are admitted. Logical input is converted to numeric observations; integer and complex data are not currently admitted. Typed-integer normalization or dimension controls are a RunMat-only compatibility-mode extension, not integer data support.
Real single reductions retain single output storage on host and admitted provider routes; double and logical inputs return double. Host reductions accumulate in double and round when constructing single output; CPU and GPU results can differ within floating-point precision.
GPU execution
Eligible resident real reductions use the owning provider's standard-deviation hooks and square the result on that device. Unsupported axes, shapes, or missing-value modes can gather to the host. Variance is a fusion boundary, not an elementwise fused operation. Automatic placement may choose a GPU; explicit gpuArray remains available.
Examples
Sample variance
x = [1 2 3 4 5];
v = var(x)Expected output:
v = 2.5Population variance by column
A = [1 3 5; 2 4 6];
vpop = var(A,1)Expected output:
vpop = [0.25 0.25 0.25]Variance of every element
B = reshape(1:12,[3 4]);
overall = var(B,0,'all')Expected output:
overall = 13Reduce rows and pages
C = cat(3,[1 2;3 4],[5 6;7 8]);
sliceVariance = var(C,[],[1 3])Expected output:
sliceVariance = [6.6667 6.6667]Ignore NaNs
D = [1 NaN 3;2 4 NaN];
rowVariance = var(D,0,2,'omitnan')Expected output:
rowVariance = [2; 2]Variance of a resident array
G = gpuArray([1 3;5 7]);
spread = var(G,1,'all');
answer = gather(spread)Expected output:
answer = 5Keep sample normalization with an empty flag
C = [1 2;3 4];
rowVariance = var(C,[],2)Expected output:
rowVariance = [0.5; 0.5]Using var with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how var changes the result.
Run a small var example, explain the result, then change one input and compare the output.
FAQ
Which normalization flag should I use?⌄
Use 0 or [] for sample variance, and 1 for population variance. Weighted-vector flags are not implemented.
How can I collapse multiple dimensions?⌄
Pass a dimension vector such as var(A,[],[1 3]), or pass all after the normalization flag.
How are NaNs handled?⌄
The default includenan mode propagates NaNs. Omitnan excludes them and returns NaN when no observations remain.
What happens beyond ndims(A)?⌄
For a non-scalar array, var keeps the shape and returns zeros in the input class when the selected dimension is beyond the stored rank. Scalars return zero.
Are complex or integer data supported?⌄
No. Real floating data and logical input are admitted; typed-integer controls are a separate RunMat-only extension.
Does var run on a GPU?⌄
An eligible resident reduction uses the input's provider; other supported forms calculate on the host.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz
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 var is executed, line by line, in Rust.
- View the source for var 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.