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

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact
  • License
  • Privacy

Learn

  • Docs
  • Blog
  • Benchmarks
  • RunMat vs MATLAB Online

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.

/
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

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

NameTypeRequiredDefaultDescription
FAnyYes—Input scalar or array.
hAnyNo1Scalar spacing shared across all output dimensions, or a coordinate vector for vector inputs.
h_iAnyVariadic—Per-dimension scalar or coordinate-vector spacings (one per gradient dimension).

Returns

NameTypeDescription
GNumericArrayPrimary gradient component.
GiNumericArrayGradient components ordered by MATLAB axis semantics.

Returned values from gradient depend on how many outputs the caller requests.

Errors

IdentifierWhenMessage
RunMat:gradient:InvalidArgumentOutput-count or spacing argument grammar is invalid.gradient: invalid argument
RunMat:gradient:InvalidInputInput value cannot be converted to a supported gradient domain.gradient: invalid input
RunMat:gradient:InternalGradient 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 returns FX for dimension 2 (across columns) and FY for dimension 1 (down rows), matching MATLAB.
  • gradient(F, h) applies the same scalar spacing to every returned dimension. For vector inputs, h may be a coordinate vector with one point per element.
  • gradient(F, hx, hy, ...) accepts one scalar or coordinate-vector spacing per output dimension, ordered as MATLAB returns outputs (x/columns first for matrices, then y/rows).
  • Coordinate-vector spacings must be finite, match the corresponding dimension length, and avoid zero finite-difference denominators.
  • With scalar spacing, interior points use central differences (f(i+1) - f(i-1)) / (2*h), while the first and last points use one-sided differences.
  • With coordinate-vector spacing, denominators come from the supplied coordinates: boundary points use adjacent coordinate differences and interior points use x(i+1) - x(i-1).
  • 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 or gradient_dim_with_coordinates, scalar and coordinate-vector spacing gradients stay resident on the device. Real and complex-interleaved GPU tensors are supported.

Does RunMat run gradient on the GPU?

The WGPU backend implements gradient_dim and gradient_dim_with_coordinates for real and complex-interleaved tensors, so scalar and coordinate-vector 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 real and complex gradient hooks, allowing provider-level parity tests without requiring a physical GPU.

Coordinate-vector spacing is validated with MATLAB-compatible denominator rules before the provider hook runs; unsupported providers fall back to host evaluation.

GPU memory and residency

Manual gpuArray promotion is optional. When a gradient starts with GPU-resident data and the active provider implements gradient_dim for scalar spacing or gradient_dim_with_coordinates for coordinate-vector spacing, RunMat keeps the result on the device. Complex-interleaved GPU tensors preserve complex residency. If the provider lacks the required hook, 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     2

Using 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])

Using nonuniform coordinate spacing

x = [0 1 3];
v = [1 4 9];
g = gradient(v, x)

Expected output:

g = [3.0000 2.6667 2.5000]

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

Yes. Vector inputs support gradient(F, X), and arrays support per-dimension scalar or coordinate-vector spacings such as [FX, FY] = gradient(F, x, y). Coordinate vectors must match the corresponding dimension length.

Does gradient support GPU arrays?⌄

Yes for default spacing, scalar spacings, and coordinate-vector spacings when the active provider implements the corresponding gradient hooks. WGPU keeps those paths resident via gradient_dim and gradient_dim_with_coordinates.

Do complex inputs work?⌄

Yes. Host complex tensors are differentiated by real and imaginary parts independently, and providers with complex-interleaved gradient hook support keep complex GPU tensors resident.

Related Math functions

Reduction

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

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 gradient works
  • Does RunMat run gradient on the GPU?
  • GPU memory and residency
  • Examples
  • Differentiating a row vector
  • Requesting both matrix gradient components
  • Using scalar spacing on GPU data
  • Using nonuniform coordinate spacing
  • Feeding gradient into a vector-field plot
  • Using gradient 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