cumtrapz — Compute cumulative trapezoidal integration in MATLAB and RunMat.
cumtrapz(Y) computes cumulative trapezoidal integrals of sampled data in Y. The output matches Y in size, with zero at the first element of the integration dimension and running integral values thereafter.
Syntax
Q = cumtrapz(Y)
Q = cumtrapz(Y, dim)
Q = cumtrapz(X, Y)
Q = cumtrapz(X, Y, dim)Inputs
Y- Type
Any- Required
- Yes
- Description
- Sample values.
dim- Type
Any- Required
- Yes
- Description
- Integration dimension.
X- Type
Any- Required
- Yes
- Description
- Sample points or spacing.
Returns
Q- Type
NumericArray- Description
- Cumulative trapezoidal integral output.
Errors
RunMat:cumtrapz:InvalidArgument- When
- Input argument count, dimension selector, or spacing arguments are invalid.
- Message
cumtrapz: invalid argument
RunMat:cumtrapz:InvalidInput- When
- Input values cannot be converted to supported numeric integration domains.
- Message
cumtrapz: invalid input
RunMat:cumtrapz:Internal- When
- Integration execution fails during gather, allocation, or provider promotion.
- Message
cumtrapz: internal integration failure
RunMat:cumtrapz:TooManyOutputs- When
- More outputs are requested than this public form returns.
- Message
cumtrapz: too many output arguments
Behavior
cumtrapz(Y) assumes unit spacing between adjacent samples.
cumtrapz(X, Y) accepts documented single- or double-precision scalar spacing or a coordinate vector whose length matches the working dimension. A same-size coordinate tensor is an explicitly gated RunMat extension.
cumtrapz(..., dim) selects the working dimension explicitly. Dimensions larger than ndims(Y) behave like singleton axes, so the result stays zero along those slices.
Documented Y classes are single and double, real or complex, and output preserves single versus double. Typed-integer and logical Y, typed-integer or logical X, and typed-integer dim are separate RunMat-only extensions.
Typed-integer Y and X cross the binary64 integration boundary only when every authoritative integer value is exactly representable; otherwise RunMat reports an error instead of silently rounding.
When the selected dimension has length 0 or 1, the output is zero along that dimension because there are no intervals to accumulate.
Forms, classes, and shapes
The two-argument parser selects Y/dim for nonscalar first input and scalar dimension candidate or accepted empty control; scalar first input instead selects X/Y. Three inputs select X/Y/dim. Empty spacing selects unit width. Scalar, vector, and gated same-size tensor coordinates preserve signed widths, including descending coordinates; nonfinite values propagate through arithmetic.
Every output keeps Y's full shape and starts at zero along the selected axis. Zero/singleton and virtual trailing axes contain zeros. Axes beyond the rank do not allocate dimension-sized metadata. Native single/double class and floating complex domain follow Y, not X; host arithmetic uses double component accumulators before matching single publication. Sparse and complex-integer samples are unsupported.
Execution and allocation
Inputs and controls retain their invocation owners across suspension. Each call uses its selected execution context and cancellation authority. Provider outputs are checked for owner, device, physical class, shape, and forbidden input aliasing. Operational errors, cancellation, authority loss, and invalid attempted outputs remain terminal; no host replay follows them.
Eligible resident forms stay with the input's exact provider. Automatic resident placement may select an admitted host-and-restore route only before a provider attempt. Explicit gpuArray data and resident controls that require host staging are rejected before gathering; allocation policy alone is not placement consent. A later no-attempt in a multi-stage operation is terminal after earlier provider effects.
Finite host allocation is not yet implemented for this operation's array scratch, shape, and output collections. Such paths reject a Managed allocation policy before unowned work; ordinary Unbounded host execution remains available. This restriction is an unfinished allocation capability, not a promise of a bounded host implementation. Native/browser execution shares the Runtime binding; long synchronous host loops do not promise browser yielding.
These operations execute through their Runtime bindings, not a certified fused reduction. The live planner declines fused prod and nnz execution. Distributed execution is not declared by these entries.
Examples
Computing a cumulative integral with explicit coordinates
x = [0 1 3];
y = [0 1 2];
q = cumtrapz(x, y)Expected output:
q = [0 0.5 3.5]Using unit spacing for sampled data
y = [1 2 3];
q = cumtrapz(y)Expected output:
q = [0 1.5 4]Accumulating across rows in a matrix
A = [1 2 3; 4 5 6];
q = cumtrapz(A, 2)Expected output:
q =
0 1.5 4
0 4.5 10Running cumtrapz on GPU data
G = gpuArray([1 2 3]);
q = cumtrapz(G);
result = gather(q)Expected output:
result = [0 1.5 4]Using cumtrapz with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cumtrapz changes the result.
Run a small cumtrapz example, explain the result, then change one input and compare the output.
FAQ
How is cumtrapz different from trapz?⌄
trapz returns the final integrated value, while cumtrapz returns the running integral at every sample.
Why is the first element zero?⌄
There is no interval before the first sample, so the cumulative integral begins at zero.
What forms of X are accepted?⌄
The compatibility surface is a single- or double-precision scalar spacing or coordinate vector matching the integration dimension. RunMat mode additionally admits same-size coordinate tensors behind the cumtrapz-tensor-spacing extension gate.
Does cumtrapz support complex inputs?⌄
Yes. RunMat accumulates the real and imaginary components independently and returns a complex result.
Does cumtrapz keep gpuArray residency?⌄
Eligible floating real or complex samples remain resident when the owning provider returns the required shape, class, precision, device, and fresh allocation. Automatic placement may use an admitted host route before a provider attempt. Explicit resident data or controls cannot silently gather; execution failures and malformed outputs are terminal.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · 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 cumtrapz is executed, line by line, in Rust.
- View the source for cumtrapz 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.