movmean — Compute moving averages in MATLAB and RunMat.
movmean(A,k) computes means over a sliding window of length k along the first non-singleton dimension.
Syntax
M = movmean(A, k)
M = movmean(A, k, dim)
M = movmean(A, k, nanflag)
M = movmean(A, k, Name, Value)
M = movmean(A, k, nanflag, Name, Value)
M = movmean(A, k, dim, Name, Value)
M = movmean(A, k, dim, nanflag, Name, Value)Inputs
A- Type
Any- Required
- Yes
- Description
- Input numeric, logical, or gpuArray data.
k- Type
NumericArray- Required
- Yes
- Description
- Window length or two-element [kb kf] backward/forward window.
dim- Type
NumericArray- Required
- No
- Description
- Dimension along which to move the window.
nanflag- Type
StringScalar- Required
- No
- Default
"includenan"- Description
- NaN handling mode: "includenan" or "omitnan".
NameValue- Type
Any- Required
- Variadic
- Description
- Name-value options, including "Endpoints".
Returns
M- Type
NumericArray- Description
- Moving-window reduction result.
Errors
RunMat:movmean:InvalidArgument- When
- Window length, dimension, nanflag, or name-value options are invalid.
- Message
moving window: invalid argument
RunMat:movmean:InvalidInput- When
- Input values cannot be converted to a supported moving-window domain.
- Message
moving window: invalid input
RunMat:movmean:Internal- When
- Moving-window execution fails due to allocation, provider, or shape operations.
- Message
moving window: internal failure
Behavior
k may be a positive scalar window length or a two-element [kb kf] backward/forward window.
Pass an explicit dim to move along a chosen dimension.
'includenan' is the default; 'omitnan' and 'omitmissing' skip NaN values inside each window.
'Endpoints' supports 'shrink' (default), 'discard', 'fill', and numeric scalar fill values.
'SamplePoints', sp uses a strictly increasing numeric point vector for irregular moving windows. With sample points, RunMat currently supports shrink endpoints.
This implementation covers numeric, logical, complex, and gpuArray inputs; table/timetable DataVariables forms are tracked separately.
Execution and residency
Real dense gpuArray inputs use provider-resident count-window reductions for scalar or [kb kf] windows, explicit dimensions, omit/include NaN modes, shrink/discard/fill endpoints, and sample/population normalization for movstd/movvar. SamplePoints and unsupported provider backends fall back to gather-once host evaluation and re-upload when an acceleration provider is active; complex GPU moving-window support remains tracked outside this resident real-dense fast path. These host fallback statements apply only to admitted Unbounded host evaluation and compatibility-enabled forms. Complex GPU input is outside the implemented resident path; the statements do not certify a complex-GPU fallback. Provider failures after an attempt do not select fallback. See the precision, compatibility, and finite-allocation boundaries below.
Accelerator scope
GPU acceleration is optional: real dense count-window kernels reduce overlapping windows rather than applying an elementwise operation. Scalar and two-element window controls, explicit dimensions and endpoint geometry follow the documented MATLAB-style forms; this is not a general binary-array broadcasting guarantee.
f32: native real single precision is supported by WGPU moving-window kernels; a provider must return physical single output for single input.
f64: native real double precision is supported by WGPU moving-window kernels and the current SimpleProvider reference hook.
Classes and storage
Real single/double inputs retain their floating output class. Logical data computes double. movsum, movmean and movprod materialize integer data once into double; movmin, movmax and movmedian retain native integer data and compare exact int64/uint64 values without binary64 conversion. movstd and movvar reject integer data; their typed integer normalization/dimension controls remain a compatibility extension. Host complex single/double reads canonical native storage without widening: movsum, movmean, movprod, movmin, movmax and movmedian return complex results of that class; movstd and movvar return real results of the same native floating class, using squared complex distance. Complex-single scalar results retain tensor storage because the scalar complex value variant is double. Complex integer, sparse numeric and complex GPU moving-window inputs are not admitted by this dense family. SimpleProvider currently computes physical double; mismatched floating precision and integer/logical provider input select only an authorized automatic host fallback before invoking its hook, never a precision-changing attempted result.
Compatibility and errors
Compatibility is limited to the documented count/span windows and controls, not complete MATLAB parity. Table/timetable DataVariables forms are not implemented. GPU SamplePoints is a compatibility-gated gather/re-upload extension where host fallback is admitted. movmedian GPU count windows larger than 31 require its existing large-window compatibility extension; the WGPU native rank-selection implementation supports at most 256 elements. Explicit GPU data and controls are never silently gathered: unsupported explicit forms require the caller to gather first, and enabling a language compatibility extension does not grant placement authority. Automatic-provenance provider refusals may select the existing host fallback only when the canonical typed unsupported/no-attempt predicate allows it. Execution, cancellation, stale-authority, malformed-result, and restore failures are terminal; original typed causes are retained and no host replay is permitted after a provider attempt.
Finite host allocation
Host evaluation, SamplePoints scratch, and gather/re-upload fallback currently require Unbounded host allocation. Under a Managed finite policy the shared moving-window admission fence refuses before unowned host parsing, cloning, gathering, or numerical scratch. A supported resident real provider request is not refused merely because host fallback is unavailable: rooted control preparation and its exact borrowed request-shape workspace use existing canonical claims, checked before and after suspension and before publication. Provider execution still depends on the provider's own allocation/admission contract; the SimpleProvider hook has ordinary private host scratch. Guarded finite host refusal and claimed request metadata are not completion of finite moving-kernel workspace ownership (L25).
Performance
Moving windows materialize results and are not fused elementwise or reduction expressions. Host work enumerates each selected window, and median additionally orders its values; irregular SamplePoints builds membership scratch. Complex kernels borrow native interleaved input directly, never materializing the whole input per element or widening a complex-single payload, and publish only the selected real or complex output payload. This removes the repeated whole-payload copy; it is not a measured speedup or an asymptotically optimized prefix/rolling/tree algorithm. Complete finite host workspace ownership, cooperative bounds for all host loops/order-statistics work, and provider-private allocation qualification remain open. No universal GPU residency or provider precision parity is promised.
Complete control grammar
Data and a window are required, with at most one output. Count windows accept a positive scalar k or exactly two nonnegative backward/forward counts; even scalar windows contain k/2 preceding and (k-1)/2 following positions. The default axis is the first extent unequal to one, including a zero extent; an explicit positive scalar dimension extends missing axes with singleton extents. Empty output geometry is retained, and discard removes the unavailable window margins rather than inventing samples. movstd/movvar consume normalization 0 (sample) or 1 (population), or an empty normalization placeholder, before a dimension; singleton sample windows divide by one. NaN/missing keywords and Endpoints name-value pairs may be interleaved with numeric controls; repeated missing flags and endpoint selections use the last one. SamplePoints may occur only once and must be finite, nonempty, strictly increasing, and length-matched to the selected input axis; its endpoints must be shrink. Window and SamplePoints controls must be scalars or row/column vectors; non-singleton higher-dimensional pages and matrices are rejected before numeric materialization. Trailing singleton axes do not change vector geometry. Endpoint fill uses the operation's documented default or a real numeric scalar, preserving exact typed fills for native integer order statistics. All-NaN omitted windows use sum/product identities and otherwise NaN; including NaN propagates it. Complex order statistics use magnitude then phase and average the two middle values for even median counts.
Error and authority boundaries
Output-count rejection precedes preparation. Missing data/window, invalid window counts or overflow, invalid dimensions, malformed name-value pairs, repeated SamplePoints, invalid/mismatched sample coordinates and incompatible endpoints are argument errors; unsupported data representations and integer moving-dispersion data are input errors. Compatibility-gated controls keep their declared extension diagnostics. Explicit resident controls or data requiring host fallback are rejected before gather; language compatibility does not grant placement permission. Finite host scratch without a complete owner fails closed, and exact provider request metadata may fail admission independently. Cancellation and stale issuer/generation failures use the installed runtime's canonical control diagnostics, not numeric failure or fallback. Provider execution, malformed/foreign/wrong-class results, provenance and restore failures retain their causes and terminal no-replay policy. This numerical owner does not read or mutate language workspace, environment, files, network, clock, RNG, or UI; it therefore requires no such capability. Optional accelerator services and possible suspension/errors do not imply ambient service authority or full finite allocation support.
Examples
Moving mean across columns
A = [1 3 5; 2 4 6];
M = movmean(A,3,2)Expected output:
M = [2 3 4; 3 4 5]Preserve complex single moving means
A = complex(single([1 3 5]), single([1 1 1]));
M = movmean(A,3);Using movmean with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how movmean changes the result.
Run a small movmean example, explain the result, then change one input and compare the output.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · 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 movmean is executed, line by line, in Rust.
- View the source for movmean 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.