加速对称矩阵的计算;使用外 [英] Speeding up calculation of symmetric matrices; use of outer
问题描述
我需要加快生成对称矩阵的计算.目前我有这样的事情:
<块引用>X <- 1:50Y<- 1:50M <-外(X,Y,FUN = myfun)
其中 myfun 是一个相当复杂的矢量化但对称的函数 (myfun(x, y) = myfun(y, x)).
所以我的代码不必要地浪费时间计算下三角矩阵和上三角矩阵.
如何在不使用慢速 for 循环的情况下避免重复?
如果你的函数很慢并且时间随着输入的大小而变化,你可以使用combn
:
X <- 1:50Y <- 1:50#一个慢函数myfun <- 函数(x,y){res <- x * NAfor (i in seq_along(x)) {系统睡眠(0.01)res[i] <- x[i] * y[i]}资源}system.time(M <-外层(X, Y, FUN = myfun))#用户系统已过期#0.00 0.00 26.41系统时间({inds <- 组合(seq_len(长度(X)),2)M1 <- 矩阵(ncol = 长度(X),nrow = 长度(Y))M1[lower.tri(M1)] <- myfun(X[inds[1,]], Y[inds[2,]])M1[上.tri(M1)] <-t(M1)[上.tri(M1)]diag(M1) <- myfun(X, Y)})#用户系统已过期#0.00 0.00 13.41all.equal(M, M1)#[1] 真
然而,最好的解决方案可能是通过 Rcpp 在 C++ 中实现.
I need to speed up a calculation that produces a symmetric matrix. Currently I have something like this:
X <- 1:50 Y<- 1:50 M <- outer(X, Y, FUN = myfun)
where myfun is a quite complicated, vectorized, but symmetrical function (myfun(x, y) = myfun(y, x)).
So my code unnecessarily wastes time calculating the lower triangular matrix as well as the upper triangular matrix.
How can I avoid that duplication without using slow for-loops?
If your function is slow and timing scales with size of its input, you could use 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
However, the best solution is probably to implement this in C++ via Rcpp.
这篇关于加速对称矩阵的计算;使用外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!