[R] vectorization instead of using loop

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Thu Oct 9 18:50:48 CEST 2008


Frank said:
> > This piece of code works, but it is very slow. We were wondering if 
it's 
> at
> > all possible to somehow vectorize this function. Any help would be 
> greatly
> > appreciated.

Richie said:
> You can save a substantial time by calling as.matrix before the loop

Patrick said:
> One thing that would speed it up is if you
> inverted 'covmat' once and then used
> 'inverted=TRUE' in the call to 'mahalanobis'.

The timings before:
> system.time(mahadist(x, covmat))
> #   user  system elapsed 
> #   2.82    0.06    2.95 
> system.time(mahadist2(x, covmat))
> #   user  system elapsed 
> #   1.39    0.04    1.45

With Patrick's modification, and moving the square root out of the loop:
mahadist3 <- function(x, covmat) #patrick's modification
{
   n <- nrow(x)
   dismat <- matrix(0,ncol=n,nrow=n)
   matx <- as.matrix(x)
   icovmat <- chol2inv(chol(covmat))
   for (i in 1:n) 
   {
      dismat[i,] <- mahalanobis(matx, matx[i,], icovmat, inverted=TRUE)
   }
   dismat^.5
}
system.time(mahadist3(x, covmat))
#   user  system elapsed 
#   0.80    0.00    0.85

Not bad - a better than threefold speed up, without worrying about 
vectorization.

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}



More information about the R-help mailing list