Documentation Center

  • Trial Software
  • Product Updates

gradient

Gradient vector of scalar function

Syntax

gradient(f,x)
gradient(f)

Description

gradient(f,x) computes the gradient vector of the scalar function f with respect to vector x in Cartesian coordinates.

gradient(f) computes the gradient vector of the scalar function f with respect to a vector constructed from all symbolic variables found in f. The order of variables in this vector is defined by symvar.

Input Arguments

f

Scalar function represented by symbolic expression or symbolic function.

x

Vector with respect to which you compute the gradient vector.

Default: Vector constructed from all symbolic variables found in f. The order of variables in this vector is defined by symvar.

Examples

Compute the gradient vector of f(x, y, z) with respect to vector [x, y, z]. The gradient is a vector with these components:

syms x y z
f = 2*y*z*sin(x) + 3*x*sin(z)*cos(y);
gradient(f, [x, y, z])
ans =
 3*cos(y)*sin(z) + 2*y*z*cos(x)
 2*z*sin(x) - 3*x*sin(y)*sin(z)
 2*y*sin(x) + 3*x*cos(y)*cos(z)
 

Compute the gradient vector of f(x, y, z) with respect to vector [x, y]. The gradient is vector g with these components:

syms x y
f = -(sin(x) + sin(y))^2;
g = gradient(f, [x, y])
g =
 -2*cos(x)*(sin(x) + sin(y))
 -2*cos(y)*(sin(x) + sin(y))

Now plot the vector field defined by these components. MATLAB® provides the quiver plotting function for this task. The function does not accept symbolic arguments. First, replace symbolic variables in expressions for components of g with numeric values. Then use quiver:

[X, Y] = meshgrid(-1:.1:1,-1:.1:1);
G1 = subs(g(1), [x y], {X,Y}); G2 = subs(g(2), [x y], {X,Y});
quiver(X, Y, G1, G2)

More About

expand all

Gradient Vector

The gradient vector of f(x) with respect to the vector x is the vector of the first partial derivatives of f:

Tips

  • If x is a scalar, gradient(f, x) = diff(f, x).

See Also

| | | | | | | |

Was this topic helpful?