RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

RunMat® is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • 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
    • trapz
    • var

diff — Compute forward finite differences or scalar symbolic derivatives in MATLAB and RunMat.

diff(X) computes adjacent forward finite differences. RunMat selects the first dimension with extent greater than one when dim is omitted and keeps that axis for every order. Scalar symbolic expressions instead construct derivatives.

Syntax

B = diff(X)
B = diff(X, n)
B = diff(X, n, dim)
D = diff(expr)
D = diff(expr, var)
D = diff(expr, n)
D = diff(expr, var, n)
D = diff(expr, n, var)

Inputs

X
Type
Any
Required
Yes
Description
Input scalar or array.
n
Type
Any
Required
No
Default
1
Description
Difference order (non-negative integer scalar or empty placeholder).
dim
Type
Any
Required
No
Default
[]
Description
Reduction dimension (positive integer scalar or empty placeholder).
expr
Type
Any
Required
Yes
Description
Scalar symbolic expression. An omitted variable is inferred only when unambiguous.
var
Type
Any
Required
Yes
Description
Symbolic variable identity or scalar text naming a variable; arbitrary numeric data is not a variable.
n
Type
Any
Required
Yes
Description
Constant nonnegative integer scalar order, no greater than uint32 maximum.
NameTypeRequiredDefaultDescription
XAnyYes—Input scalar or array.
nAnyNo1Difference order (non-negative integer scalar or empty placeholder).
dimAnyNo[]Reduction dimension (positive integer scalar or empty placeholder).
exprAnyYes—Scalar symbolic expression. An omitted variable is inferred only when unambiguous.
varAnyYes—Symbolic variable identity or scalar text naming a variable; arbitrary numeric data is not a variable.
nAnyYes—Constant nonnegative integer scalar order, no greater than uint32 maximum.

Returns

B
Type
NumericArray
Description
Finite differences along the selected dimension.
D
Type
Any
Description
Scalar symbolic derivative expression; no numerical finite differences are performed.
NameTypeDescription
BNumericArrayFinite differences along the selected dimension.
DAnyScalar symbolic derivative expression; no numerical finite differences are performed.

Errors

RunMat:diff:InvalidArgument
When
Argument count/order/dimension/order grammar is invalid.
Message
diff: invalid argument
RunMat:diff:InvalidInput
When
Input value cannot be converted to a supported diff domain.
Message
diff: invalid input
RunMat:diff:Internal
When
Finite-difference execution fails due to conversion, gather, allocation, or reshape operations.
Message
diff: internal failure
RunMat:diff:TooManyOutputs
When
More than one output is requested.
Message
diff: too many output arguments
IdentifierWhenMessage
RunMat:diff:InvalidArgumentArgument count/order/dimension/order grammar is invalid.diff: invalid argument
RunMat:diff:InvalidInputInput value cannot be converted to a supported diff domain.diff: invalid input
RunMat:diff:InternalFinite-difference execution fails due to conversion, gather, allocation, or reshape operations.diff: internal failure
RunMat:diff:TooManyOutputsMore than one output is requested.diff: too many output arguments

Behavior

Without dim, RunMat selects the first axis with extent greater than one, or axis one when none exists. Column vectors differentiate down rows and row vectors across columns; zero extents on other axes remain empty.

diff(X, N) computes the Nth forward difference without cascading into later dimensions when N exhausts the initially selected dimension. Each positive order reduces that dimension by one, so its output length becomes max(len - N, 0).

diff(X, N, dim) lets you choose the dimension explicitly. Dimensions larger than ndims(X) behave like length-1 axes, so any positive order yields an empty result. RunMat extension mode also accepts N = 0 and empty N or dim placeholders.

For scalar symbolic inputs, diff(expr, var) and diff(expr, var, N) return symbolic derivative expressions. diff(expr, N, var) is accepted for MATLAB-compatible argument order.

Floating and logical data follow their numeric domains. All eight integer classes preserve their input class and use saturating adjacent subtraction. Character data is a named RunMat-only extension that promotes character codes to double.

Empty slices propagate: if the selected dimension has length 0 or 1, the corresponding axis in the output has length 0.

Forms, classes, and shapes

Numerical differences preserve native single, double, and all eight integer classes. Recursive integer subtraction saturates at each step. Logical data and the gated character-code extension return double for positive orders. Selected-axis extent is max(length-order,0), even when another axis is empty; all remaining extents and column-major element order are retained.

The nonnegative order and positive dimension must be real scalar controls. Empty controls and zero order are gated RunMat extensions. Zero order returns the original value unchanged. Scalar symbolic expressions accept variable/order in either supported order, infer a sole variable when omitted, reject ambiguous variables, and restrict symbolic order to a nonnegative 32-bit integer.

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 first differences of a vector

v = [3 4 9 15];
d1 = diff(v)

Expected output:

d1 = [1 5 6]

Taking second-order differences

v = [1 4 9 16 25];
d2 = diff(v, 2)

Expected output:

d2 = [2 2 2]

Selecting the working dimension explicitly

A = [1 2 3; 4 5 6];
rowDiff = diff(A, 1, 2)

Expected output:

rowDiff =
     1     1
     1     1

Running diff on GPU arrays

G = gpuArray([1 4 9 16]);
gDiff = diff(G);
result = gather(gDiff)

Expected output:

result = [3 5 7]

N exceeding the dimension length returns an empty array

v = (1:3)';
emptyResult = diff(v, 5)

Expected output:

emptyResult =
  0×1 empty double column vector

Applying diff to character data

codes = diff('ACEG')

Expected output:

codes = [2 2 2]

Build a symbolic derivative

syms Y(X)
dydx = diff(Y, X)

Expected output:

dydx = diff(Y(X), X)

Using diff with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how diff changes the result.

Run a small diff example, explain the result, then change one input and compare the output.

FAQ

Does diff change the size of the input?⌄

diff reduces the length along the working dimension by N. All other dimensions are preserved. If the working dimension is shorter than N, the result is empty. With the WGPU backend the empty result remains GPU-resident.

How are higher-order differences computed?⌄

RunMat applies the first-order forward difference repeatedly along the initially selected dimension. Current MATLAB behavior does not cascade into a later dimension after that dimension is exhausted.

Can I pass [] for the order or dimension arguments?⌄

RunMat extension mode accepts empty placeholders and keeps the default value (N = 1, first non-singleton dimension).

Does diff support complex numbers?⌄

Floating complex inputs are differentiated componentwise in their native single or double storage, including empty outputs. Complex-integer data is unsupported for positive orders; the gated zero-order identity preserves its input unchanged.

What happens for character or logical inputs?⌄

Logical data is supported. Character data is a named RunMat-only extension and promotes character codes to double; integer data instead preserves its class and uses saturating subtraction.

Will the GPU path produce the same results as the CPU path?⌄

Eligible real floating resident input uses diff_dim. Automatic resident inputs may take an admitted exact-owner host fallback after a true no-attempt decision. Explicit gpuArray data without a resident route is rejected before gathering. Provider execution errors and malformed results are terminal.

What does diff do in MATLAB?⌄

diff(X) computes differences between adjacent elements. For a vector, it returns X(2:end) - X(1:end-1), producing an output one element shorter than the input.

How do I compute second differences with diff?⌄

Use diff(X, 2) to compute the second-order difference, equivalent to diff(diff(X)). The output is two elements shorter than the input.

How do I compute differences along columns vs rows?⌄

Use diff(X, 1, 1) for differences along columns (default for matrices) and diff(X, 1, 2) for differences along rows. The third argument specifies the dimension.

Can I use diff to compute numerical derivatives?⌄

Yes. For evenly spaced data with step h, the numerical derivative is approximately diff(y) / h. For non-uniform spacing, use diff(y) ./ diff(x).

Does diff support GPU acceleration in RunMat?⌄

Yes. Eligible real floating arrays use the owning provider's kernel. Complex, logical, and integer input has no native WGPU difference route; automatic placement can use an admitted host fallback, but explicit gpuArray input cannot silently gather.

Does diff support symbolic expressions?⌄

Yes. Scalar symbolic expressions return symbolic derivative expressions such as diff(Y(X), X). Numeric arrays still use finite-difference semantics.

Related Math functions

Reduction

all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · 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

Bitwise

bitand · bitcmp · bitget · bitor · bitset · bitshift · bitxor · swapbytes

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

Rounding

ceil · fix · floor · mod · rem · round

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

Solve

cond · det · inv · linsolve · norm · null · pinv · rank · rcond · rref · vecnorm

Ops

cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose

Symbolic

digits · int · limit · piecewise · sym · syms · vpa

Discrete

factor · factorial · gcd · isprime · lcm · primes

Fft

fft · fft2 · fftn · fftshift · ifft · ifft2 · ifftn · ifftshift

Interpolation

griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline

Integer Division

idivide

Ode

ode15s · ode23 · ode45 · odeset

Poly

poly · polyder · polyfit · polyint · polyval · roots

Source you can read

Every RunMat function's source is public. Read exactly how diff is executed, line by line, in Rust.

  • View the source for diff 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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • Behavior
  • Forms, classes, and shapes
  • Execution and allocation
  • Examples
  • Computing first differences of a vector
  • Taking second-order differences
  • Selecting the working dimension explicitly
  • Running diff on GPU arrays
  • N exceeding the dimension length returns an empty array
  • Applying diff to character data
  • Build a symbolic derivative
  • Using diff with coding agents
  • FAQ
  • Related Math functions
  • Reduction
  • Elementwise
  • Optim
  • Trigonometry
  • Structure
  • Bitwise
  • Signal
  • Rounding
  • Factor
  • Solve
  • Ops
  • Symbolic
  • Discrete
  • Fft
  • Interpolation
  • Integer Division
  • Ode
  • Poly
  • Source you can read
  • About RunMat