[R] efficiently multiply different matrices in 3-d array with different vectors?

Suzen, Mehmet msuzen at gmail.com
Sat Dec 29 19:19:32 CET 2012


What I had in mind was a tensor multiplication.
I think,  using tensor arithmetic for multidimensional arrays looks
more compacts
and efficient (~ 2-3 times). I am guessing that performance will be much more
pronounced for n-D arrays (n>3).

# Component Wise
set.seed(14)
Z<-array(sample(1:1000000,800000,replace=TRUE),dim=c(50000,2,8))
set.seed(21)
Y<-matrix(sample(1:400000,400000,replace=TRUE),nrow=8)
system.time(X<-do.call(cbind,lapply(seq_len(dim(Z)[1]),function(i)
Z[i,,]%*%Y[,i])))
#   user  system elapsed
#   0.58    0.00    0.58
R<-cbind(sum(X[1,]), sum(X[2,]))
# Tensor multiply
library(tensorA)
set.seed(14)
Zt <-to.tensor(sample(1:1000000,800000,replace=TRUE), c(a=50000, b=2, c=8))
set.seed(21)
Yt <-to.tensor(sample(1:400000,400000,replace=TRUE), c(c=8, a=50000))
system.time(Rt<-Zt %e% Yt)
#   user  system elapsed
#  0.124   0.000   0.126
# correct results?
R
#            [,1]         [,2]
#[1,] 4.00595e+16 3.997387e+16
Rt
#[1] 4.005950e+16 3.997387e+1




More information about the R-help mailing list