通过交错向量加速组装矩阵?

时间:2012-11-12 20:12:44

标签: performance r matrix

我有两个任意长度相等的向量

a <- c(0.8,0.8,0.8) 
b <- c(0.4,0.4,0.4)
n <- length(a)

从这些我需要组建2n 2n形式的矩阵:

x = [1-a1  b1    1-a2  b2    1-a3  b3
     a1    1-b1  a2    1-b2  a3    1-b3
     1-a1  b1    1-a2  b2    1-a3  b3
     a1    1-b1  a2    1-b2  a3    1-b3
     1-a1  b1    1-a2  b2    1-a3  b3
     a1    1-b1  a2    1-b2  a3    1-b3]

我目前使用

执行此操作
x <- matrix(rep(as.vector(rbind(
                          c(1-a,a), 
                          c(b, 1-b))),
                n),
            ncol=n*2, byrow=TRUE)

如何加快此操作?分析表明matrix占用的时间最多:

Rprof("out.prof")
for (i in 1:100000) {

x <- matrix(rep(as.vector(rbind(
  c(1-a,a), 
  c(b, 1-b))),
                n),
            ncol=n*2, byrow=TRUE)

}
Rprof(NULL)
summaryRprof("out.prof")

##$by.self
##            self.time self.pct total.time total.pct
##"matrix"         1.02    63.75       1.60    100.00
##"rbind"          0.24    15.00       0.36     22.50
##"as.vector"      0.18    11.25       0.54     33.75
##"c"              0.10     6.25       0.10      6.25
##"*"              0.04     2.50       0.04      2.50
##"-"              0.02     1.25       0.02      1.25
##
##$by.total
##            total.time total.pct self.time self.pct
##"matrix"          1.60    100.00      1.02    63.75
##"as.vector"       0.54     33.75      0.18    11.25
##"rbind"           0.36     22.50      0.24    15.00
##"c"               0.10      6.25      0.10     6.25
##"*"               0.04      2.50      0.04     2.50
##"-"               0.02      1.25      0.02     1.25
##
##$sample.interval
##[1] 0.02
##
##$sampling.time
##[1] 1.6

2 个答案:

答案 0 :(得分:3)

我不认为matrix是您个人资料中最慢的部分,但您可以通过优化其余部分来节省一点时间。例如:

x <- matrix(rbind(c(1-a,a), c(b, 1-b)), 2*n, 2*n, byrow=TRUE)

此外,虽然我不推荐它,但您可以使用内部矩阵功能节省一点额外的时间:

x <- .Internal(matrix(rbind(c(1-a,a), c(b, 1-b)),
                      n*2, n*2, TRUE, NULL, FALSE, FALSE))

以下是一些基准:

benchmark(
   method0 = matrix(rep(as.vector(rbind(c(1-a,a), c(b, 1-b))), n),
                    ncol=n*2, byrow=TRUE),
   method1 = matrix(rbind(c(1-a,a), c(b, 1-b)), 2*n, 2*n, byrow=TRUE),
   method2 = .Internal(matrix(rbind(c(1-a,a), c(b, 1-b)),
                              n*2, n*2, TRUE, NULL, FALSE, FALSE)),
   replications = 100000,
   order = "relative")

#      test replications elapsed relative user.self sys.self user.child sys.child
# 3 method2       100000    1.00     1.00      0.99        0         NA        NA
# 2 method1       100000    1.13     1.13      1.12        0         NA        NA
# 1 method0       100000    1.46     1.46      1.46        0         NA        NA

答案 1 :(得分:0)

我通过以下方式获得了一个小的加速:

f = function(a, b, n){
  z = rbind(
    c(rbind(1 - a, b)),
    c(rbind(a, 1 - b))
  )

  do.call(rbind, lapply(1:n, function(i) z))
}

我会继续寻找。

编辑我很难过。如果这还不够好,我建议内联一些rcpp。