I have two vectors of arbitrary and equal length
a <- c(0.8,0.8,0.8)
b <- c(0.4,0.4,0.4)
n <- length(a)
From these I need to assemble an 2n by 2n matrix of the form:
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]
I currently do this using
x <- matrix(rep(as.vector(rbind(
c(1-a,a),
c(b, 1-b))),
n),
ncol=n*2, byrow=TRUE)
How can I speed up this operation? Profiling indicates that matrix is taking the most time:
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
I don’t think there is an alternative to
matrixbeing the slowest part of your profile, but you can definitely save a little time by optimizing the rest. For example:Also, although I would not recommend it, you can save a little extra time by using the Internal matrix function:
Here are some benchmarks: