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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | Any | Yes | — | Input scalar or array. |
n | Any | No | 1 | Difference order (non-negative integer scalar or empty placeholder). |
dim | Any | No | [] | Reduction dimension (positive integer scalar or empty placeholder). |
Returns
| Name | Type | Description |
|---|---|---|
B | NumericArray | Finite differences along the selected dimension. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:diff:InvalidArgument | Argument count/order/dimension/order grammar is invalid. | diff: invalid argument |
RunMat:diff:InvalidInput | Input value cannot be converted to a supported diff domain. | diff: invalid input |
RunMat:diff:Internal | Finite-difference execution fails due to conversion, gather, allocation, or reshape operations. | diff: internal failure |
RunMat:diff:TooManyOutputs | More 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 becomesmax(len - N, 0).diff(X, N, dim)lets you choose the dimension explicitly. Dimensions larger thanndims(X)behave like length-1 axes, so any positive order yields an empty result. RunMat extension mode also acceptsN = 0and emptyNordimplaceholders.- For scalar symbolic inputs,
diff(expr, var)anddiff(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 1Running 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 vectorApplying 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
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
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.