Numerical gradient

collapse all in page

## Syntax

`FX = gradient(F)`

`[FX,FY]= gradient(F)`

`[FX,FY,FZ,...,FN]= gradient(F)`

`[___] = gradient(F,h)`

`[___] = gradient(F,hx,hy,...,hN)`

## Description

example

`FX = gradient(F)`

returnsthe one-dimensional numericalgradient of vector `F`

. The output `FX`

correspondsto ∂*F*/∂*x*, whichare the differences in the *x* (horizontal) direction.The spacing between points is assumed to be `1`

.

example

`[FX,FY]= gradient(F)`

returns the *x* and *y* componentsof the two-dimensional numericalgradient of matrix `F`

. The additional output `FY`

correspondsto ∂*F*/∂*y*, whichare the differences in the *y* (vertical) direction.The spacing between points in each direction is assumed to be `1`

.

`[FX,FY,FZ,...,FN]= gradient(F)`

returns the `N`

componentsof the numericalgradient of `F`

, where `F`

isan array with `N`

dimensions.

example

`[___] = gradient(F,h)`

uses `h`

asa uniform spacing between points in each direction. You can specifyany of the output arguments in previous syntaxes.

example

`[___] = gradient(F,hx,hy,...,hN)`

specifies `N`

spacingparameters for the spacing in each dimension of `F`

.

## Examples

collapse all

### Gradient of Vector

Open Live Script

Calculate the gradient of a monotonically increasing vector.

x = 1:10

`x = `*1×10* 1 2 3 4 5 6 7 8 9 10

fx = gradient(x)

### Contour Plot of Vector Field

Open Live Script

Calculate the 2-D gradient of $$x{e}^{-{x}^{2}-{y}^{2}}$$ on a grid.

x = -2:0.2:2;y = x';z = x .* exp(-x.^2 - y.^2);[px,py] = gradient(z);

Plot the contour lines and vectors in the same figure.

figurecontour(x,y,z)hold onquiver(x,y,px,py)hold off

### Linear Function Approximation

Open Live Script

Use the gradient at a particular point to linearly approximate the function value at a nearby point and compare it to the actual value.

The equation for linear approximation of a function value is

$$f(x)\approx f({x}_{0})+{(\nabla f)}_{{x}_{0}}\cdot (x-{x}_{0}).$$

That is, if you know the value of a function $$f({x}_{0})$$ and the slope of the derivative $${(\nabla f)}_{{x}_{0}}$$ at a particular point $${x}_{0}$$, then you can use this information to approximate the value of the function at a nearby point $$f(x)=f({x}_{0}+\u03f5)$$.

Calculate some values of the sine function between -1 and 0.5. Then calculate the gradient.

y = sin(-1:0.25:0.5);yp = gradient(y,0.25);

Use the function value and derivative at `x = 0.5`

to predict the value of `sin(0.5005)`

.

y_guess = y(end) + yp(end)*(0.5005 - 0.5)

y_guess = 0.4799

Compute the actual value for comparison.

y_actual = sin(0.5005)

y_actual = 0.4799

### Compute Gradient at Specified Point

Open Live Script

Find the value of the gradient of a multivariate function at a specified point.

Consider the multivariate function $$f(x,y)={x}^{2}{y}^{3}$$.

x = -3:0.2:3;y = x';f = x.^2 .* y.^3;surf(x,y,f)xlabel('x')ylabel('y')zlabel('z')

Calculate the gradient on the grid.

[fx,fy] = gradient(f,0.2);

Extract the value of the gradient at the point `(1,-2)`

. To do this, first obtain the indices of the point you want to work with. Then, use the indices to extract the corresponding gradient values from `fx`

and `fy`

.

x0 = 1;y0 = -2;t = (x == x0) & (y == y0);indt = find(t);f_grad = [fx(indt) fy(indt)]

`f_grad = `*1×2* -16.0000 12.0400

The exact value of the gradient of $$f(x,y)={x}^{2}{y}^{3}$$ at the point (1,-2) is

$$\begin{array}{cl}{(\nabla f)}_{(1,-2)}& =2x{y}^{3}\underset{}{\overset{\u02c6}{i}}+3{x}^{2}{y}^{2}\underset{}{\overset{\u02c6}{j}}\\ & =-16\underset{}{\overset{\u02c6}{i}}+12\underset{}{\overset{\u02c6}{j}}.\end{array}$$

## Input Arguments

collapse all

`F`

— Input array

vector | matrix | multidimensional array

Input array, specified as a vector, matrix, or multidimensionalarray.

**Data Types: **`single`

| `double`

**Complex Number Support: **Yes

`h`

— Uniform spacing between points

`1`

(default) | scalar

Uniform spacing between points in all directions, specifiedas a scalar.

**Example: **`[FX,FY] = gradient(F,2)`

**Data Types: **`single`

| `double`

**Complex Number Support: **Yes

`hx`

, `hy`

, `hN`

— Spacing between points (as separate inputs)

`1`

(default) | scalars | vectors

Spacing between points in each direction, specified as separateinputs of scalars or vectors. The number of inputs must match thenumber of array dimensions of `F`

. Each input canbe a scalar or vector:

A scalar specifies a constant spacing in that dimension.

A vector specifies the coordinates of the values alongthe corresponding dimension of

`F`

. In this case,the length of the vector must match the size of the correspondingdimension.

**Example: **`[FX,FY] = gradient(F,0.1,2)`

**Example: **`[FX,FY] = gradient(F,[0.1 0.3 0.5],2)`

**Example: **`[FX,FY] = gradient(F,[0.1 0.3 0.5],[2 3 5])`

**Data Types: **`single`

| `double`

**Complex Number Support: **Yes

## Output Arguments

collapse all

`FX`

, `FY`

, `FZ`

, `FN`

— Numerical gradients

arrays

Numerical gradients, returned as arrays of the same size as `F`

.The first output `FX`

is always the gradient alongthe 2nd dimension of `F`

, going across columns. The second output `FY`

is always the gradient alongthe 1st dimension of `F`

, going across rows. Forthe third output `FZ`

and the outputs that follow,the `N`

th output is the gradient along the `N`

thdimension of `F`

.

## More About

collapse all

### Numerical Gradient

The *numerical gradient* ofa function is a way to estimate the values of the partial derivativesin each dimension using the known values of the function at certainpoints.

For a function of two variables, *F*(*x*,*y*),the gradient is

$$\nabla F=\frac{\partial F}{\partial x}\widehat{i}+\frac{\partial F}{\partial y}\widehat{j}\text{\hspace{0.17em}}.$$

The gradient can be thought of as a collection of vectors pointingin the direction of increasing values of *F*. In MATLAB^{®},you can compute numerical gradients for functions with any numberof variables. For a function of *N* variables, *F*(*x*,*y*,*z*,...), the gradient is

$$\nabla F=\frac{\partial F}{\partial x}\widehat{i}+\frac{\partial F}{\partial y}\widehat{j}+\frac{\partial F}{\partial z}\widehat{k}+\mathrm{...}+\frac{\partial F}{\partial N}\widehat{n}\text{\hspace{0.17em}}.$$

## Tips

Use

`diff`

or a custom algorithm to compute multiple numerical derivatives, rather than calling`gradient`

multiple times.

## Algorithms

`gradient`

calculates the *centraldifference* for interior data points. For example, considera matrix with unit-spaced data, `A`

, that has horizontalgradient `G = gradient(A)`

. The interior gradientvalues, `G(:,j)`

, are

G(:,j) = 0.5*(A(:,j+1) - A(:,j-1));

The subscript `j`

varies between `2`

and `N-1`

,with `N = size(A,2)`

.

`gradient`

calculates values along the edgesof the matrix with *single-sided differences*:

G(:,1) = A(:,2) - A(:,1);G(:,N) = A(:,N) - A(:,N-1);

If you specify the point spacing, then `gradient`

scalesthe differences appropriately. If you specify two or more outputs,then the function also calculates differences along other dimensionsin a similar manner. Unlike the `diff`

function, `gradient`

returnsan array with the same number of elements as the input.

## Extended Capabilities

### C/C++ Code Generation

Generate C and C++ code using MATLAB® Coder™.

### Thread-Based Environment

Run code in the background using MATLAB® `backgroundPool`

or accelerate code with Parallel Computing Toolbox™ `ThreadPool`

.

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

### GPU Arrays

Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

## Version History

**Introduced before R2006a**

## See Also

del2 | diff

### Topics

- Calculate Tangent Plane to Surface

## MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

### Americas

- América Latina (Español)
- Canada (English)
- United States (English)

### Europe

- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)

- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français

- United Kingdom (English)

Contact your local office