gradient
Numerical gradient (finite-difference derivative) of sampled data.
Category: Mathematics > Numerical Integration and Differential Equations
Syntax
g = gradient(f)
Derivative of a vector with unit spacing.
g = gradient(f, h)
Derivative with uniform spacing h, or with the coordinate vector h.
[gx, gy] = gradient(F, hx, hy)
Partial derivatives of a matrix with respect to columns (gx) and rows (gy).
Description
Interior points use central differences, (f(i+1) - f(i-1))/(2h). The end points use one-sided differences, which are less accurate.
For a matrix, the first output is the derivative along the columns direction (left to right) and the second along the rows direction (top to bottom), which is the opposite order from what the layout of F might suggest.
Input arguments
f, F- Vector or N-D array of samples.
h, hx, hy- Scalar spacing or vector of sample coordinates.
Output arguments
g, gx, gy- Arrays the same size as the input.
Example
Derivative of squares
gradient([1 4 9 16])
[gx, gy] = gradient([1 2 4; 2 3 5; 4 5 7])
Output
ans = 1×4
3 4 6 7
gx = 3×3
1.0000 1.5000 2.0000
1.0000 1.5000 2.0000
1.0000 1.5000 2.0000
gy = 3×3
1.0000 1.0000 1.0000
1.5000 1.5000 1.5000
2.0000 2.0000 2.0000