FX = gradient(F)
[FX,FY] = gradient(F)
[FX,FY,FZ,...] = gradient(F)
[...] = gradient(F,h)
[...] = gradient(F,h1,h2,...)
The gradient of a function of two variables, F(x,y), is defined as
and can be thought of as a collection of vectors pointing in the direction of increasing values of F. In MATLAB® software, numerical gradients (differences) can be computed for functions with any number of variables. For a function of N variables, F(x,y,z, ...),
FX = gradient(F), where
a vector, returns the one-dimensional numerical gradient of
FX corresponds to ∂F/∂x,
the differences in x (horizontal) direction.
[FX,FY] = gradient(F),
F is a matrix, returns the x and y components
of the two-dimensional numerical gradient.
to ∂F/∂x, the
differences in x (horizontal) direction.
to ∂F/∂y, the
differences in the y (vertical) direction. The
spacing between points in each direction is assumed to be one.
[FX,FY,FZ,...] = gradient(F),
N dimensions, returns
N components of the gradient of
There are two ways to control the spacing between values in
A single spacing value,
the spacing between points in every direction.
N spacing values (
specifies the spacing for each dimension of
Scalar spacing parameters specify a constant spacing for each dimension.
Vector parameters specify the coordinates of the values along corresponding
F. In this case, the length of the
vector must match the size of the corresponding dimension.
The first output
[...] = gradient(F,h),
h is a scalar, uses
the spacing between points in each direction.
[...] = gradient(F,h1,h2,...) with
parameters specifies the spacing for each dimension of
Calculate the 2-D gradient of on a grid.
v = -2:0.2:2; [x,y] = meshgrid(v); z = x .* exp(-x.^2 - y.^2); [px,py] = gradient(z,.2,.2);
Plot the contour lines and vectors in the same figure.
contour(v,v,z) hold on quiver(v,v,px,py) hold off
Create a 3-D array.
F(:,:,1) = magic(3); F(:,:,2) = pascal(3);
However, the command,
[PX,PY,PZ] = gradient(F,0.2,0.1,0.2)
dx = 0.2,
dy = 0.1,
dz = 0.2.
gradient calculates the central
difference for interior data points. For example, consider
a matrix with unit-spaced data,
A, that has horizontal
G = gradient(A). The interior gradient
G(:,j) = 0.5*(A(:,j+1) - A(:,j-1));
j varies between
The gradient values along the edges of the matrix are calculated with single-sided differences, so that
G(:,1) = A(:,2) - A(:,1); G(:,N) = A(:,N) - A(:,N-1);
If the point spacing is specified, then the differences are
scaled appropriately. If two or more outputs are specified,
calculates differences along other dimensions in a similar manner.
an array with the same number of elements as the input.