Computes the first derivative of f at x using forward-mode AD. Equivalent to D(f, x). For f: R^p -> R^m, returns an m x p matrix. For scalar-valued f, returns a length-p gradient vector.

jacobian(f, x)

Arguments

f

A function taking a parameter vector and returning a scalar, list of scalars, or a dual_vector.

x

A numeric vector of parameter values (length p).

Value

An m x p numeric matrix for vector-valued f, or a numeric vector of length p for scalar-valued f.

Examples

# Jacobian of f: R^2 -> R^3
f <- function(x) {
  a <- x[1]; b <- x[2]
  list(a * b, a^2, sin(b))
}
jacobian(f, c(2, pi/4))
#>           [,1]      [,2]
#> [1,] 0.7853982 2.0000000
#> [2,] 4.0000000 0.0000000
#> [3,] 0.0000000 0.7071068

# Scalar function: returns gradient vector
g <- function(x) x[1]^2 + x[2]^2
jacobian(g, c(3, 4))  # c(6, 8)
#> [1] 6 8