cumprod — Compute cumulative products in MATLAB and RunMat.
cumprod(X) multiplies elements cumulatively along a chosen dimension. The output has the same size as X, and each element stores the running product under MATLAB semantics.
Syntax
B = cumprod(A)
B = cumprod(A, dim)
B = cumprod(A, direction)
B = cumprod(A, nanflag)
B = cumprod(A, dim, direction)
B = cumprod(A, direction, dim)All supported cumprod forms
B = cumprod(A)
B = cumprod(A, dim)
B = cumprod(A, direction)
B = cumprod(A, nanflag)
B = cumprod(A, dim, direction)
B = cumprod(A, direction, dim)
B = cumprod(A, dim, nanflag)
B = cumprod(A, nanflag, dim)
B = cumprod(A, direction, nanflag)
B = cumprod(A, nanflag, direction)
B = cumprod(A, dim, direction, nanflag)
B = cumprod(A, dim, nanflag, direction)
B = cumprod(A, direction, dim, nanflag)
B = cumprod(A, direction, nanflag, dim)
B = cumprod(A, nanflag, dim, direction)
B = cumprod(A, nanflag, direction, dim)Inputs
A- Type
Any- Required
- Yes
- Description
- Dense real or complex single/double, real integer, or logical scalar or N-D array; sparse, distributed and complex-integer inputs are unsupported.
dim- Type
Any- Required
- No
- Default
[]- Description
- Positive finite integer-valued numeric scalar dimension, or [] to use the first nonsingleton dimension. No dimension vector is accepted.
direction- Type
StringScalar- Required
- No
- Default
"forward"- Description
- Scan direction: "forward" or "reverse".
nanflag- Type
StringScalar- Required
- No
- Default
"includenan"- Description
- Missing-value mode: "includenan"/"includemissing" or "omitnan"/"omitmissing".
Returns
B- Type
NumericArray- Description
- Cumulative product result.
Errors
RunMat:cumprod:InvalidArgument- When
- Input or output count, dimension, direction, or missing-value argument grammar is invalid.
- Message
cumprod: invalid argument
RunMat:cumprod:InvalidInput- When
- Input value type is unsupported for cumulative product reduction.
- Message
cumprod: invalid input
RunMat:cumprod:Internal- When
- Reduction execution fails due to conversion, provider, or allocation operations.
- Message
cumprod: internal reduction failure
Cumulative behavior
By default, the running product is taken along the first dimension whose length is greater than 1.
cumprod(X, dim) lets you choose the dimension explicitly; if dim > ndims(X), the input is returned unchanged.
Passing [] for the dimension argument keeps the default dimension (MATLAB treats it as a placeholder).
cumprod(..., "reverse") accumulates from the end toward the beginning; "forward" (default) works from start to finish.
cumprod(..., "omitnan") treats NaN values as missing. Empty prefixes yield 1, the multiplicative identity.
Synonyms such as "omitmissing" / "includemissing" are accepted for MATLAB compatibility.
The function supports real or complex scalars and dense tensors. Logical inputs are promoted to double precision.
Classes, residency and allocation
Accepts one dense numeric or logical input and at most three controls in any order: one positive numeric scalar dimension (or []), one forward/reverse direction, and one includenan/includemissing/omitnan/omitmissing mode. Options are trimmed and case-insensitive; repeated or unknown controls and nonscalar, nonfinite, fractional or nonpositive dimensions are errors. Native/double output-type selectors are not accepted.
The default dimension is the first nonsingleton dimension, including a zero extent, or dimension one for a scalar. Empty and N-D array shapes are preserved. A dimension beyond the stored rank leaves values unchanged; its result may be discarded, but requesting more than one output fails before execution.
All eight real integer input classes preserve their class and shape. Cumulative sums and products saturate after each native integer operation; extrema retain exact integer ordering. Logical inputs become double. Floating single and double, including complex storage, preserve native precision. Complex-integer, sparse and distributed inputs are not accepted.
Host inputs execute on the host. Resident inputs are offered to their exact owning provider without changing physical precision. Floating parallel prefix order can differ from sequential host accumulation; signed saturating integer scans can also depend on provider grouping.
Only a certified provider no-attempt permits fallback. An automatic input may then use the host route with unrestricted allocation. Explicit device input does not authorize host processing. Provider execution, cancellation, ownership and malformed-result errors are not replayed.
Finite Managed host scan scratch is not implemented: host scans and host fallback reject before unowned allocation or readback. Legal resident scans remain available under their provider allocation owner.
Calls do not use user callbacks, workspace mutation, filesystem, clock or random services. Input shape is preserved for empty and N-D arrays, and direction does not change the selected dimension.
An explicit missing-value flag on a GPU input is a gated RunMat extension.
Examples
Running products down each column (default dimension)
A = [1 2 3; 4 5 6];
columnProducts = cumprod(A)Expected output:
columnProducts =
1 2 3
4 10 18Tracking cumulative products across rows
A = [1 2 3; 4 5 6];
rowProducts = cumprod(A, 2)Expected output:
rowProducts =
1 2 6
4 20 120Reversing the accumulation direction
v = [2 3 4 5];
reverseProducts = cumprod(v, "reverse")Expected output:
reverseProducts =
120 60 20 5Ignoring NaN values while multiplying
v = [2 NaN 4 NaN 3];
running = cumprod(v, "omitnan")Expected output:
running =
2 2 8 8 24Computing a cumulative product inside a GPU workflow
G = gpuArray(1 + 0.1*rand(1, 5));
totals = cumprod(G);
hostResult = gather(totals)Using cumprod with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cumprod changes the result.
Run a small cumprod example, explain the result, then change one input and compare the output.
FAQ
Does cumprod change the size of the input?⌄
No. The output always equals the input shape.
What happens if I request a dimension larger than ndims(X)?⌄
The input is returned unchanged, matching MATLAB behaviour.
How does "omitnan" treat leading NaN values?⌄
They are ignored, so the cumulative product uses the multiplicative identity 1 until a finite value appears.
Can I combine "reverse" and "omitnan"?⌄
Yes. The options can be specified in any order and RunMat mirrors MATLAB’s results.
Does the GPU path respect "omitnan"?⌄
A supported scan executes through the exact input owner. A certified no-attempt permits host fallback only for automatic inputs with unrestricted host allocation. Explicit device inputs require a supported resident route; provider execution errors are terminal.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumsum · cumtrapz · diff · gradient · max · maxk · mean · 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 cumprod is executed, line by line, in Rust.
- View the source for cumprod 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.