RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

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.

LicensePrivacy
/
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 forward finite differences along the first non-singleton dimension by default. Higher-order and explicit-dimension forms follow MATLAB semantics. When X is a scalar symbolic expression, diff builds a symbolic derivative expression.

Syntax

B = diff(X)
B = diff(X, n)
B = diff(X, n, dim)

Inputs

NameTypeRequiredDefaultDescription
XAnyYes—Input scalar or array.
nAnyNo1Difference order (non-negative integer scalar or empty placeholder).
dimAnyNo[]Reduction dimension (positive integer scalar or empty placeholder).

Returns

NameTypeDescription
BNumericArrayFinite differences along the selected dimension.

Errors

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

How diff works

  • diff(X) walks along the first non-singleton dimension. Column vectors therefore differentiate down the rows, while row vectors operate across columns.
  • 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.

Does RunMat run diff on the GPU?

For real floating storage, RunMat asks the handle's owning provider for diff_dim and accepts only a result with matching owner, device, shape, storage, precision, and no integer or logical metadata. Typed integer, logical, complex, and unsupported-provider paths gather explicitly and restore through the same validated owner/device path.

GPU memory and residency

Manual gpuArray promotion is optional. Real floating tensors use diff_dim when the owning provider supports it. Typed integer, logical, complex, and unsupported-provider paths gather through that owner, compute on the host, and re-upload a validated result to the same owner and device.

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?⌄

Yes. Differences are taken on the real and imaginary parts independently, and the result remains complex unless it becomes empty.

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?⌄

Real floating storage can use the provider kernel. Typed integer, logical, complex, and unsupported-provider paths gather through the input owner, compute with the matching host semantics, and restore a validated resident result.

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. Real floating arrays can execute in the provider kernel. Complex, logical, and typed integer arrays currently use owner-preserving host fallbacks rather than a native WGPU difference kernel.

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 · bsxfun · complex · conj · double · erf · erfcinv · exp · expm1 · factorial · flintmax · gamma · gammaln · heaviside · hypot · idivide · imag · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · swapbytes · times · typecast · uint16 · uint32 · uint8

Trigonometry

acos · acosh · asin · asinh · atan · atan2 · 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

Rounding

ceil · fix · floor · mod · rem · round

Factor

chol · decomposition · eig · eigs · lu · qr · svd

Solve

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

Optim

coneprog · fminbnd · fminunc · fsolve · fzero · integral · linprog · lsqcurvefit · lsqnonlin · optimoptions · optimset · quad · secondordercone

Ops

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

Symbolic

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

Fft

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

Interpolation

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

Discrete

lcm · primes

Ode

ode15s · ode23 · ode45

Poly

polyder · polyfit · polyint · polyval · roots

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. 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 an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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
  • How diff works
  • Does RunMat run diff on the GPU?
  • GPU memory and residency
  • 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
  • Trigonometry
  • Structure
  • Signal
  • Rounding
  • Factor
  • Solve
  • Optim
  • Ops
  • Symbolic
  • Fft
  • Interpolation
  • Discrete
  • Ode
  • Poly
  • Open-source implementation
  • About RunMat