[英]R - How can I make this loop faster?
Is there some way to make this loop faster in r?有什么方法可以让 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.其中,在这种情况下,
pixDF
是一个包含 490000 行和 4 列的矩阵,其中填充了双精度数。 n
= 5. Cov
is a (4,5,4) array filled with "doubles". n
= Cov
是一个 (4,5,4) 数组,其中填充了“双精度”。 Mean
is a (5,4) array filled with doubles as well. Mean
是一个 (5,4) 数组,也填充了双精度数。
This loop was taking about 30min on my computer.这个循环在我的电脑上大约需要 30 分钟。 (before editing).
(编辑前)。 Right now it's taking 1min.
现在需要1分钟。
As Ronak notes, it is hard to help without reproducible example.正如 Ronak 所指出的,如果没有可重复的示例,就很难提供帮助。 But, I think that
apply
could be avoided.但是,我认为可以避免
apply
。 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
.此外,正如 Roland 提到的那样,
inv
可能是 equal solve
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.