logo

Calculating Jacobian and Hessian Matrices in R 📂R

Calculating Jacobian and Hessian Matrices in R

Code

To calculate the Jacobian matrix and Hessian matrix in R, you use the jacobian() and hessian() functions from the numDeriv package.

install.packages("numDeriv")
library(numDeriv)
 
f <- function(v) {c(v[1]^2 + v[2]^2 - 1,
                   sin(pi*v[1]/2) + v[2]^3)}
g <- function(v) {(v[1])^3+(v[2])^2}
 
jacobian(f, c(1,1))
hessian(g, c(1,1))

The results of executing the code are as follows. The top is the result of substituting $x=y=1$ into the Jacobian matrix of $f(x,y) := \begin{bmatrix} x^2 + y^2 -1 \\ \displaystyle \sin {{ \pi } \over {2} } x + y^3 \end{bmatrix}$, and the bottom is the result of substituting $x=y=1$ into the Hessian matrix of $g(x,y) := x^3 + y^2$.

20190325_172923.png In fact, since the Jacobian matrix of $f$ is $J = \begin{bmatrix} 2x & 2y \\ {{\pi } \over {2} } \cos {{\pi } \over {2} } x & 3 y^2 \end{bmatrix}$, $J(1,1) = \begin{bmatrix} 2 & 2 \\ 0 & 3 \end{bmatrix}$ was obtained, and since the Hessian matrix of $g$ is $H = \begin{bmatrix} 6x & 0 \\ 0 & 2 \end{bmatrix}$, $H(1,1) = \begin{bmatrix} 6 & 0 \\ 0 & 2 \end{bmatrix}$ was obtained.