cumsum — Compute cumulative sums in MATLAB and RunMat.
cumsum(X) computes running sums along a chosen dimension. The output has the same size as X, with each element storing the cumulative total under MATLAB semantics.
Syntax
B = cumsum(A)
B = cumsum(A, dim)
B = cumsum(A, direction)
B = cumsum(A, nanflag)
B = cumsum(A, dim, direction)
B = cumsum(A, direction, dim)All supported cumsum forms
B = cumsum(A)
B = cumsum(A, dim)
B = cumsum(A, direction)
B = cumsum(A, nanflag)
B = cumsum(A, dim, direction)
B = cumsum(A, direction, dim)
B = cumsum(A, dim, nanflag)
B = cumsum(A, nanflag, dim)
B = cumsum(A, direction, nanflag)
B = cumsum(A, nanflag, direction)
B = cumsum(A, dim, direction, nanflag)
B = cumsum(A, dim, nanflag, direction)
B = cumsum(A, direction, dim, nanflag)
B = cumsum(A, direction, nanflag, dim)
B = cumsum(A, nanflag, dim, direction)
B = cumsum(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 sum result.
Errors
RunMat:cumsum:InvalidArgument- When
- Input or output count, dimension, direction, or missing-value argument grammar is invalid.
- Message
cumsum: invalid argument
RunMat:cumsum:InvalidInput- When
- Input value type is unsupported for cumulative sum reduction.
- Message
cumsum: invalid input
RunMat:cumsum:Internal- When
- Reduction execution fails due to conversion, provider, or allocation operations.
- Message
cumsum: internal reduction failure
Cumulative behavior
By default, the running total is taken along the first dimension whose length is greater than 1.
cumsum(X, dim) lets you pick the dimension explicitly; if dim > ndims(X), the input is returned unchanged.
Passing [] for the dimension argument keeps the default dimension (MATLAB uses this as a placeholder).
cumsum(..., "reverse") works from the end toward the beginning, whereas "forward" (default) works from start to finish.
cumsum(..., "omitnan") treats NaN values as missing. Leading NaN values yield zeros until a valid number appears.
Synonyms such as "omitmissing" / "includemissing" are also 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.
Examples
Running totals down each column (default dimension)
A = [1 2 3; 4 5 6];
columnTotals = cumsum(A)Expected output:
columnTotals =
1 2 3
5 7 9Tracking cumulative sums across rows
A = [1 2 3; 4 5 6];
rowTotals = cumsum(A, 2)Expected output:
rowTotals =
1 3 6
4 9 15Reversing the direction of accumulation
v = [1 3 5 7];
reverseTotals = cumsum(v, "reverse")Expected output:
reverseTotals =
16 15 12 7Ignoring NaN values while accumulating
v = [2 NaN 5 NaN 1];
running = cumsum(v, "omitnan")Expected output:
running =
2 2 7 7 8Computing a cumulative sum inside a GPU workflow
G = gpuArray(rand(1, 5));
totals = cumsum(G);
hostResult = gather(totals)Using cumsum with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cumsum changes the result.
Run a small cumsum example, explain the result, then change one input and compare the output.
FAQ
Does cumsum change the size of the input?⌄
No. The output is always the same size as the input tensor.
What happens if I request a dimension larger than ndims(X)?⌄
The function returns X unchanged, matching MATLAB behaviour.
How are complex numbers handled?⌄
cumsum accumulates the real and imaginary parts independently. NaN checks treat a complex number as missing if either part is NaN.
What does "omitnan" do for leading NaN values?⌄
Leading NaN values contribute zeros so the running total remains 0 until a non-NaN value appears.
Does "reverse" affect which dimension is used?⌄
No. Direction only decides whether accumulation walks from the start or from the end along the selected dimension.
Can I combine "reverse" and "omitnan"?⌄
Yes. You can specify both options (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 · cumprod · 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 cumsum is executed, line by line, in Rust.
- View the source for cumsum 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.