trapz — Approximate integrals of sampled data using the trapezoidal rule with MATLAB-compatible dimension handling.
trapz(Y) approximates integrals of single- or double-precision sampled data using trapezoidal segments. By default integration runs along the first non-singleton dimension, with MATLAB-compatible explicit-dimension forms supported. Typed-integer sample data and spacing are available in RunMat mode when every value can enter the binary64 integration domain exactly.
Syntax
Q = trapz(Y)
Q = trapz(Y, dim)
Q = trapz(X, Y)
Q = trapz(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
- Trapezoidal integral output.
Errors
RunMat:trapz:InvalidArgument- When
- Input argument count, dimension selector, or spacing arguments are invalid.
- Message
trapz: invalid argument
RunMat:trapz:InvalidInput- When
- Input values cannot be converted to supported numeric integration domains.
- Message
trapz: invalid input
RunMat:trapz:Internal- When
- Integration execution fails during gather, allocation, or provider promotion.
- Message
trapz: internal integration failure
RunMat:trapz:TooManyOutputs- When
- More outputs are requested than this public form returns.
- Message
trapz: too many output arguments
Behavior
trapz(Y) assumes unit spacing between adjacent samples.
trapz(X, Y) accepts a scalar spacing, a vector of coordinates whose length matches the working dimension, or an array X with the same size as Y.
trapz(..., dim) selects the working dimension explicitly. Dimensions larger than ndims(Y) behave like singleton axes, so the result is zero along those slices.
Logical inputs are promoted to double precision before integration. Complex-valued Y inputs are integrated component-wise and preserve their complex output type.
Single-precision sample data produces single-precision output; typed-integer sample data is a RunMat extension and produces double output.
Native typed-integer Y and X roles are independently compatibility-gated and require exact binary64 conversion. Native typed-integer dim is an ordinary exact structural selector.
When the selected dimension has length 0 or 1, trapz returns zeros because there are no intervals to integrate.
Forms, classes, and shapes
The two-argument parser selects Y/dim when the first input is nonscalar and the second is a scalar dimension candidate or accepted empty control; a scalar first input selects X/Y. Three inputs select X/Y/dim. Real scalar or empty spacing uses a constant or unit width; vector spacing supplies coordinate differences, and same-size X supplies per-lane coordinate differences. Nonfinite spacing propagates through arithmetic rather than being silently replaced.
Selected zero/singleton axes return zeros and become extent one. Axes beyond the stored rank are virtual singleton axes and return zeros in the stored shape without allocating trailing-axis metadata. Single samples return single; other admitted real samples return double. Floating complex samples preserve their domain and single/double class. Host trapezoidal arithmetic uses double component accumulators before single publication.
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
Integrating sampled sine data with explicit coordinates
x = 0:0.01:pi;
y = sin(x);
area = trapz(x, y)Expected output:
area ≈ 2Using unit spacing for a row vector
y = [1 2 3];
q = trapz(y)Expected output:
q = 4Integrating each row independently
A = [1 2 3; 4 5 6];
q = trapz(A, 2)Expected output:
q =
4
10Running trapz on GPU data
G = gpuArray([1 2 3]);
q = trapz(G);
result = gather(q)Expected output:
result = 4Using trapz with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how trapz changes the result.
Run a small trapz example, explain the result, then change one input and compare the output.
FAQ
What spacing does trapz(Y) assume?⌄
It assumes adjacent samples are one unit apart.
What forms of X are accepted?⌄
A scalar spacing, a vector of coordinates matching the integration dimension, or an array with the same size as Y.
What happens for a scalar or singleton slice?⌄
The integral is zero because there are no trapezoids to sum.
Does trapz support complex inputs?⌄
Yes. RunMat integrates the real and imaginary parts independently and returns a complex result.
Does trapz keep gpuArray residency?⌄
Eligible floating real or complex sample data can remain resident through the owning provider's trapz_dim operation. Logical and integer samples require admitted host conversion. Unsupported explicit gpuArray data or controls are rejected before input gathering; automatic placement may use admitted fallback after no attempt.
Related Math functions
Reduction
all · any · bounds · cummax · 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 · 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 trapz is executed, line by line, in Rust.
- View the source for trapz 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.