简体   繁体   中英

R - How can I make this loop faster?

Is there some way to make this loop faster in r?

    V=array(NA, dim=c(nrow(pixDF), n))

    for(i in 1:n)
    {
       sdC<-sqrt(det(Cov[,i,]))
       iC<-inv(Cov[,i,])
       V[,i]<-apply(pixDF,1,function(x)(sdC*exp(-0.5*((x-Mean[i,])%*%iC%*%as.matrix((x-Mean[i,]))))))
    }

where, in this case, pixDF is a matrix with 490000 rows and 4 columns filled with doubles. n = 5. Cov is a (4,5,4) array filled with "doubles". Mean is a (5,4) array filled with doubles as well.

This loop was taking about 30min on my computer. (before editing). Right now it's taking 1min.

As Ronak notes, it is hard to help without reproducible example. But, I think that apply could be avoided. Something like this COULD work:

V <- array(NA, dim = c(nrow(pixDF), n))
tpixDF <- t(pixDF)
for (i in 1:n) {
  x <- Cov[, i, ]
  sdC <- sqrt(det(x))
  iC <- solve(x)
  mi <- Mean[i, ]
  k <- t(tpixDF - mi)
  V[, i] <- sdC*exp(-0.5*rowSums(k %*% iC * k))
}

Also, as Roland mentions inv probably is equal solve .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM