cgradient

Gradient of a multivariate, scalar-valued function using the central difference approximation.

Back to Numerical Differentiation Toolbox Contents.

Contents

Syntax

g = cgradient(f,x0)
g = cgradient(f,x0,h)

Description

g = cgradient(f,x0) numerically evaluates the gradient of $f$ with respect to $\mathbf{x}$ at $\mathbf{x}=\mathbf{x}_{0}$ using the central difference approximation with a default relative step size of $h=\varepsilon^{1/3}$, where $\varepsilon$ is the machine zero.

g = cgradient(f,x0,h) numerically evaluates the gradient of $f$ with respect to $\mathbf{x}$ at $\mathbf{x}=\mathbf{x}_{0}$ using the central difference approximation with a user-specified relative step size $h$.

Input/Output Parameters

Variable Symbol Description Format
Input f multivariate, scalar-valued function () 1×1
function_handle
x0 evaluation point n×1
double
h (OPTIONAL) relative step size (defaults to $h=\varepsilon^{1/3}$) 1×1
double
Output g gradient of with respect to , evaluated at n×1
double

Note

Example

Approximate the gradient of $f(\mathbf{x})=x_{1}^{5}+\sin^{3}{x_{2}}$ at $\mathbf{x}=\mathbf{x}_{0}=(5,8)^{T}$ using the cgradient function, and compare the result to the true result of

$$\nabla f(\mathbf{x}_{0})=\pmatrix{3125\cr3\sin^{2}{(8)}\cos{(8)}}$$

Approximating the gradient,

f = @(x) x(1)^5+sin(x(2))^3;
x0 = [5;8];
g = cgradient(f,x0)
g =

   1.0e+03 *

    3.1250
   -0.0004

Calculating the error,

error = g-[3125;3*sin(8)^2*cos(8)]
error =

   1.0e-06 *

    0.3280
    0.0020

See also

fgradient | igradient