R: optimal way of computing the "product" of two vectors
Let's assume that I have a vector
r <- rnorm(4)
and a开发者_如何学Python matrix W
of dimension 20000*200 for example:
W <- matrix(rnorm(20000*200),20000,200)
I want to compute a new matrix M
of dimension 5000*200 such that m11 <- r%*%W[1:4,1]
, m21 <- r%*%W[5:8,1]
, m12 <- r%*%W[1:4,2]
etc. (i.e. grouping rows 4-by-4 and computing the product).
What's the optimal (speed,memory) way of doing this?
Thanks in advance.
This seems to run fastest for me:
array(r %*% array(W, c(4, 20000 * 200 / 4)), c(5000, 200))
First on my mind is apply
over shorter dim:
M <- apply(W, 2, function(x) r%*%matrix(x,4,5000))
m11 <- r%*%W[1:4,1]
m21 <- r%*%W[5:8,1]
m12 <- r%*%W[1:4,2]
m11 - M[1,1]
# [,1]
# [1,] 0
m21 - M[2,1]
# [,1]
# [1,] 0
m12 - M[1,2]
# [,1]
# [1,] 0
Profiled kohske answer:
M <- apply(array(W,c(4,5000,200)), 3, function(x) r%*%x)
to iterated over shorter dim (again).
I don't know if this is optimal in speed or memory, but probably one of the simple way:
m<-apply(array(W,c(4,5000,200)),c(2,3),"%*%",r)
> m[1,1:10]==r%*%W[1:4,1:10]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
> m[2,1:10]==r%*%W[5:8,1:10]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
精彩评论