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
F- Type
Any- Required
- Yes
- Description
- Input scalar or array.
h- Type
Any- Required
- No
- Default
1- Description
- Scalar spacing shared across all output dimensions, or a coordinate vector for vector inputs.
h_i- Type
Any- Required
- Variadic
- Description
- Per-dimension scalar or coordinate-vector spacings (one per gradient dimension).
Returns
G- Type
NumericArray- Description
- Primary gradient component.
Gi- Type
NumericArray- Description
- Gradient components ordered by MATLAB axis semantics.
Returned values from gradient depend on how many outputs the caller requests.
Errors
RunMat:gradient:InvalidArgument- When
- Output-count or spacing argument grammar is invalid.
- Message
gradient: invalid argument
RunMat:gradient:InvalidInput- When
- Input value cannot be converted to a supported gradient domain.
- Message
gradient: invalid input
RunMat:gradient:Internal- When
- Gradient execution fails due to gather, conversion, allocation, or indexing operations.
- Message
gradient: internal failure
Behavior
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.
Eligible real or complex floating resident samples use gradient_dim for unit or scalar spacing. Coordinate spacing currently selects host evaluation; the public Runtime does not call gradient_dim_with_coordinates. Explicit resident data or controls requiring host fallback are rejected before gathering.
Forms, classes, and shapes
Each result keeps the sample shape; rank-one storage is exposed as a MATLAB-style row vector. A vector or scalar has one gradient output; a nonvector matrix has two. Higher-rank arrays expose one output per axis, ordered 2,1,3,... . Requests beyond the available components fail before execution. Singleton axes produce zeros and empty shapes remain empty.
Single samples return single; other admitted real samples return double. Floating complex samples return matching complex precision. Host stencil arithmetic uses double component accumulators before single publication. Integer/logical data and spacing are separately gated RunMat extensions; integer values must enter binary64 exactly. Sparse and complex-integer samples are unsupported.
A shared scalar spacing must be finite and nonzero. Coordinate data is read in column-major order, must match its axis length, be finite, and have nonzero adjacent and central denominators. For array gradients, coordinate spacing requires one argument per gradient dimension; no missing spacing is invented.
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. The Runtime currently calls gradient_dim only for unit/scalar spacing; provider gradient_dim_with_coordinates exists but is not used by this public binding.
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
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])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?⌄
Eligible floating real or complex samples with default or scalar spacing can remain resident through gradient_dim. Coordinate spacing uses admitted host evaluation only for automatic placement. Explicit inputs requiring a missing resident route are rejected before gathering; provider failures do not trigger replay.
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 · 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
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
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
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. 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 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.