TABLE OF CONTENTS
initRoutine/inverthessian [ Functions ]
NAME
inverthessian --- invert a Hessian matrix
FUNCTION
The Hessian matrices returned by optim() are not always positive-definite and invertible. This function adjusts the diagonal of an input matrix until it is invertible. This gives an acceptable covariance matrix for subsequent use.
SYNOPSIS
922 inverthessian <- function(hess){
INPUTS
hess a matrix
OUTPUTS
Sigma the inverse of hess, or of something very close to it
SOURCE
925 K <- dim(hess)[1] 926 # Try to invert the Hessian 927 Sigma <- try(solve(-hess), silent = TRUE) 928 d <- 10 929 # modify the diagonal until it is invertible 930 while(inherits(Sigma, "try-error")){ 931 Sigma <- try(solve(-(hess - 10^(-d) * mdiag(K))), silent = TRUE); 932 d <- d - 1 933 } 934 # modify the diagonal until it is positive definite 935 while(!all(eigen(Sigma)$val > 0)){ 936 Sigma <- solve(-(hess - 10^(-d) * mdiag(K))) ; 937 d <- d - 1 938 } 939 return(Sigma) 940 }