加快对称矩阵的计算;外用

时间:2018-09-18 10:16:44

标签: r matrix vectorization

我需要加快产生对称矩阵的计算速度。目前我有这样的东西:

X <- 1:50
Y<- 1:50
M <- outer(X, Y, FUN = myfun)

其中myfun是一个非常复杂的矢量化但对称的函数(myfun(x,y)= myfun(y,x))。

所以我的代码不必要地浪费了计算下三角矩阵和上三角矩阵的时间。

如何在不使用慢速for循环的情况下避免重复?

1 个答案:

答案 0 :(得分:1)

如果您的函数运行缓慢且计时随输入大小而定,则可以使用combn

X <- 1:50
Y <- 1:50

#a slow function
myfun <- function(x, y) {
  res <- x * NA
  for (i in seq_along(x)) {
    Sys.sleep(0.01)
    res[i] <- x[i] * y[i]
    }
  res
}

system.time(M <- outer(X, Y, FUN = myfun))
#user  system elapsed 
#0.00    0.00   26.41 

system.time({
  inds <- combn(seq_len(length(X)), 2)
  M1 <- matrix(ncol = length(X), nrow = length(Y))

  M1[lower.tri(M1)] <-  myfun(X[inds[1,]], Y[inds[2,]])
  M1[upper.tri(M1)] <- t(M1)[upper.tri(M1)]
  diag(M1) <- myfun(X, Y)
})
#user  system elapsed 
#0.00    0.00   13.41

all.equal(M, M1)
#[1] TRUE

但是,最好的解决方案可能是通过Rcpp在C ++中实现。

相关问题