# [R] NumDeriv - derivatives of covariance matrix

Wed Apr 30 16:27:43 CEST 2008

```Your calculation can be thought of as a function from R^m to R^(n*n),
and functions in numDeriv can be used to calculate a numerical
approximation to the derivative of the function. However, the functions
in numDeriv try to calculate accurate approximations, as opposed to
quick approximations like one might want in an optimization problem.
Given that you already have an analytic solution, I doubt that even a
quick approximation will be faster. You might better look at trying to
convert parts of your double loop into vector or matrix calculations, or
focusing on the fact that the matrix is symmetric.

Paul Gilbert

Daomeng Gao wrote:
> Hello R-help,
>
> I need to compute matrices of first derivatives of a covariance matrix C
> with entries given by c_ij=theta*exp(-0.5* sum(eta*(x[i,]-x[j,])^2)), wrt to
> elements of eta, a m-dimensional vector of parameters, given a n*m data
> matrix x. So far, I have been computing matrices for each parameter (given
> by par[index]) analytically, using the following
>
> kmatder<- function(x, par, index) {
>     ## x: n*m matrix
>     ## par: vector of parameters, m=length(par)=ncol(x)
>     ## compute matrix of partial derivatives wrt parameter par[index]: Cder
> = d C/d par[index]
>     theta<-1
>       eta<-par
>     n<-nrow(x)
>     Cder<-matrix(0,n,n)
>     for (i in 1:n) {
>         for (j in i:n) {
>             Cder[i,j]<-(-0.5*((x[i,index]-x[j,index])^2))*theta*exp(-0.5*
> sum(eta*(x[i,]-x[j,])^2))
>         }
>     }
>     Cder<-0.5*(Cder+t(Cder))
>     Cder
> }
>
> I was wondering whether it might be possible to speed up things using
> numDeriv (jacobian). If so, what would be the right way to implement a
> suitable method ?
>
> Cheers,
> Gao Daomeng
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help