cummax — Compute cumulative maxima (with optional indices) in MATLAB and RunMat.
cummax(X) computes running maxima along a chosen dimension. Optional second output returns indices of each running maximum, with behavior aligned to MATLAB and RunMat.
Syntax
[M, I] = cummax(A)
[M, I] = cummax(A, dim)
[M, I] = cummax(A, direction)
[M, I] = cummax(A, nanflag)
[M, I] = cummax(A, dim, direction)
[M, I] = cummax(A, direction, dim)All supported cummax forms
[M, I] = cummax(A)
[M, I] = cummax(A, dim)
[M, I] = cummax(A, direction)
[M, I] = cummax(A, nanflag)
[M, I] = cummax(A, dim, direction)
[M, I] = cummax(A, direction, dim)
[M, I] = cummax(A, dim, nanflag)
[M, I] = cummax(A, nanflag, dim)
[M, I] = cummax(A, direction, nanflag)
[M, I] = cummax(A, nanflag, direction)
[M, I] = cummax(A, dim, direction, nanflag)
[M, I] = cummax(A, dim, nanflag, direction)
[M, I] = cummax(A, direction, dim, nanflag)
[M, I] = cummax(A, direction, nanflag, dim)
[M, I] = cummax(A, nanflag, dim, direction)
[M, I] = cummax(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
M- Type
NumericArray- Description
- Cumulative maximum values.
I- Type
NumericArray- Description
- One-based double indices along the scan dimension.
Returned values from cummax depend on how many outputs the caller requests.
Errors
RunMat:cummax:InvalidArgument- When
- Input or output count, dimension, direction, or missing-value argument grammar is invalid.
- Message
cummax: invalid argument
RunMat:cummax:InvalidInput- When
- Input value type is unsupported for cumulative maximum reduction.
- Message
cummax: invalid input
RunMat:cummax:Internal- When
- Reduction execution fails due to conversion, provider, or allocation operations.
- Message
cummax: internal reduction failure
Cumulative behavior
By default the running maximum follows the first non-singleton dimension. Use cummax(X, dim) to choose a dimension explicitly; if dim > ndims(X), the input is returned unchanged and the indices are ones.
[Y, I] = cummax(X, ...) returns both the running maxima (Y) and the indices of where those maxima were observed (I). Indices are one-based positions along the chosen dimension.
Add "reverse" (or "forward") to control the scan direction. Reverse mode walks from the end of the chosen dimension back to the beginning.
"omitnan" skips NaN values when choosing the running maximum, returning NaN only when every value seen so far is NaN. "includenan" (default) propagates NaN once one is encountered.
Synonyms such as "omitmissing" / "includemissing" are accepted for MATLAB compatibility.
Real and complex inputs are supported. Complex numbers are ordered using MATLAB's magnitude-and-angle rules.
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 and produces all-one double indices. Zero, one or two outputs are accepted; more outputs fail 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.
Public indices are double on every route. A provider unable to produce exact double indices declines a two-output request before execution. A one-output request may still use its native value kernel and retire unrequested internal index scratch. GPU missing-value flags are a gated RunMat extension.
Examples
Tracking column-wise running maxima
A = [4 2 7; 3 5 1];
[Y, I] = cummax(A);
disp(Y);
disp(I)Expected output:
Y =
4 2 7
4 5 7
I =
1 1 1
1 2 1Requesting running maxima across rows
A = [4 2 7; 3 5 1];
[Y, I] = cummax(A, 2);
disp(Y);
disp(I)Expected output:
Y =
4 4 7
3 5 5
I =
1 1 3
1 2 2Getting cumulative maxima in reverse order
v = [8 3 6 2];
[Y, I] = cummax(v, "reverse")Expected output:
Y = [8 6 6 2]
I = [1 3 3 4]Ignoring NaN values in running maxima
v = [NaN 5 NaN 3];
[Y, I] = cummax(v, "omitnan")Expected output:
Y = [NaN 5 5 5]
I = [NaN 2 2 2]Capturing running maxima and indices on the GPU
G = gpuArray([3 1 4 1 5]);
[Y, I] = cummax(G);
hostY = gather(Y)
hostI = gather(I)Expected output:
hostY = [3 3 4 4 5];
hostI = [1 1 3 3 5]Using cummax with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cummax changes the result.
Run a small cummax example, explain the result, then change one input and compare the output.
FAQ
Does cummax always return indices?⌄
One output returns cumulative values. Two outputs return values and one-based double indices. More than two outputs fail before execution. Current provider kernels may compute internal index scratch even when only values are requested.
How are complex numbers ordered?⌄
Complex maxima follow MATLAB's rules: values compare by magnitude, and ties break by phase angle. "omitnan" treats elements with NaN real or imaginary parts as missing.
What happens when all elements seen so far are NaN with "omitnan"?⌄
The running maximum stays NaN and the corresponding index is NaN until a finite value is encountered. Once a finite value appears, subsequent NaNs leave the maximum and index unchanged.
Does the "reverse" option change the reported indices?⌄
Indices are still reported using 1-based positions along the chosen dimension. "reverse" simply walks the dimension from end to start before writing the outputs.
What if the requested dimension exceeds ndims(X)?⌄
The input is returned unchanged. Every index is 1, matching MATLAB's treatment of singleton trailing dimensions.
Related Math functions
Reduction
all · any · bounds · 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 · 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 cummax is executed, line by line, in Rust.
- View the source for cummax 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.