gradient — Compute numerical gradients in MATLAB and RunMat.
gradient(F) computes numerical derivatives using central differences in the interior and one-sided differences at boundaries. Default dimension behavior and multi-output ordering follow MATLAB semantics.
Syntax
G = gradient(F)
G = gradient(F, h)
[G1, G2, ...] = gradient(F)
[G1, G2, ...] = gradient(F, h1, h2, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
F | Any | Yes | — | Input scalar or array. |
h | Any | No | 1 | Scalar spacing shared across all output dimensions. |
h_i | Any | Variadic | — | Per-dimension scalar spacings (one per requested gradient component). |
Returns
| Name | Type | Description |
|---|---|---|
G | NumericArray | Primary gradient component. |
Gi | NumericArray | Gradient components ordered by MATLAB axis semantics. |
Returned values from gradient depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:gradient:InvalidArgument | Output-count or spacing argument grammar is invalid. | gradient: invalid argument |
RunMat:gradient:InvalidInput | Input value cannot be converted to a supported gradient domain. | gradient: invalid input |
RunMat:gradient:Internal | Gradient execution fails due to gather, conversion, allocation, or indexing operations. | gradient: internal failure |
How gradient works
gradient(F)chooses the first non-singleton dimension for vectors and returns the column-direction derivative for matrices.[FX, FY] = gradient(F)on a matrix returnsFXfor dimension 2 (across columns) andFYfor dimension 1 (down rows), matching MATLAB.gradient(F, h)applies the same scalar spacing to every returned dimension.gradient(F, hx, hy, ...)accepts one scalar spacing per output dimension. In v1, each spacing must be scalar.- Interior points use central differences
(f(i+1) - f(i-1)) / (2*h), while the first and last points use one-sided differences. - Real, logical, and scalar numeric inputs promote through the standard tensor conversion path. Complex host inputs are supported by differentiating the real and imaginary parts independently.
- When a GPU tensor is passed and the active provider implements
gradient_dim, scalar-spacing gradients stay resident on the device. Complex GPU tensors and coordinate-vector spacing currently gather to the host.
Does RunMat run gradient on the GPU?
The WGPU backend implements gradient_dim, so scalar-spacing gradients execute on the device and return GPU tensors for both single-output and multi-output calls.
The simple in-process provider also exposes gradient_dim, allowing provider-level parity tests without requiring a physical GPU.
Coordinate-vector spacing is intentionally out of scope for this version and falls back to host evaluation.
GPU memory and residency
Manual gpuArray promotion is optional. When a scalar-spacing gradient starts with GPU-resident data and the active provider implements gradient_dim, RunMat keeps the result on the device. If the provider lacks the hook, if spacing is specified with coordinate vectors, or if the input is complex GPU data, RunMat gathers to the host and preserves MATLAB-compatible results.
Examples
Differentiating a row vector
v = [1 4 9];
g = gradient(v)Expected output:
g = [3 4 5]Requesting both matrix gradient components
A = [1 2; 3 4];
[FX, FY] = gradient(A)Expected output:
FX =
1 1
1 1
FY =
2 2
2 2Using scalar spacing on GPU data
G = gpuArray(single([1 4 9]));
D = gradient(G, 2);
out = gather(D)Expected output:
out = single([1.5 2.0 2.5])Feeding gradient into a vector-field plot
[X, Y] = meshgrid(linspace(-2, 2, 25), linspace(-2, 2, 25));
Z = X .* exp(-X.^2 - Y.^2);
[DX, DY] = gradient(Z, X(1,2)-X(1,1), Y(2,1)-Y(1,1));
quiver(X, Y, DX, DY)Using gradient with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how gradient changes the result.
Run a small gradient example, explain the result, then change one input and compare the output.
FAQ
What finite-difference stencil does gradient use?⌄
RunMat matches MATLAB's shape-preserving behavior: central differences in the interior and first-order one-sided differences at the boundaries.
Why does a matrix return the x-direction first?⌄
MATLAB defines the first matrix output along dimension 2 (columns), then dimension 1 (rows). RunMat preserves that ordering so plotting workflows like quiver line up correctly.
Can I pass coordinate vectors for spacing?⌄
Not in this version. gradient(F, X) and vector-valued hx, hy, ... are reserved for a follow-up implementation.
Does gradient support GPU arrays?⌄
Yes for default spacing and scalar spacings. With an active provider such as WGPU, the scalar-spacing path stays on the GPU via the gradient_dim hook.
Do complex inputs work?⌄
Yes on the host. Complex GPU tensors currently gather to the host before differencing.
Related Math functions
Reduction
all · any · cummax · cummin · cumprod · cumsum · cumtrapz · diff · max · mean · median · min · nnz · prod · std · sum · trapz · var
Elementwise
abs · angle · complex · conj · double · exp · expm1 · factorial · gamma · hypot · imag · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · sign · single · sqrt · times
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cos · cosd · cosh · deg2rad · rad2deg · sin · sind · sinh · tan · tand · tanh
Structure
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how gradient is executed, line by line, in Rust.
- View the source for gradient 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.