1.官方给出的解释:(看不懂就直接略过看下面实例)
%GRADIENT Approximate gradient.
% [FX,FY] = GRADIENT(F) returns the numerical gradient of the
% matrix F. FX corresponds to dF/dx, the differences in x (horizontal)
% direction. FY corresponds to dF/dy, the differences in y (vertical)
% direction. The spacing between points in each direction is assumed to
% be one. When F is a vector, DF = GRADIENT(F) is the 1-D gradient.
%
% [FX,FY] = GRADIENT(F,H), where H is a scalar, uses H as the
% spacing between points in each direction.
%
% [FX,FY] = GRADIENT(F,HX,HY), when F is 2-D, uses the spacing
% specified by HX and HY. HX and HY can either be scalars to specify
% the spacing between coordinates or vectors to specify the
% coordinates of the points. If HX and HY are vectors, their length
% must match the corresponding dimension of F.
%
% [FX,FY,FZ] = GRADIENT(F), when F is a 3-D array, returns the
% numerical gradient of F. FZ corresponds to dF/dz, the differences
% in the z direction. GRADIENT(F,H), where H is a scalar,
% uses H as the spacing between points in each direction.
%
% [FX,FY,FZ] = GRADIENT(F,HX,HY,HZ) uses the spacing given by
% HX, HY, HZ.
%
% [FX,FY,FZ,...] = GRADIENT(F,...) extends similarly when F is N-D
% and must be invoked with N outputs and either 2 or N+1 inputs.
%
% Note: The first output FX is always the gradient along the 2nd
% dimension of F, going across columns. The second output FY is always
% the gradient along the 1st dimension of F, going across rows. For the
% third output FZ and the outputs that follow, the Nth output is the
% gradient along the Nth dimension of F.
2.举个栗子
定义一个二维矩阵x,求其梯度:
由上图可知,梯度值Fx(i,j)可分为三个部分:
左边界梯度: Fx(:,j) = Fx(:,j+1) - Fx(:,j) ;
右边界梯度: Fx(:,j) = Fx(:,j) - Fx(:,j-1);
中间区域梯度: Fx(:,j) = (Fx(:,j+1) - Fx(:,j-1)) / 2.
同理,可以得出Fy,此处不再赘述。