Home > other >  np.linalg.multi_dot for R
np.linalg.multi_dot for R

Time:04-23

I'm trying to do a nested dot

M <- matrix(1:9,ncol=3)
x <- c(1,2,3)

m <- M
for (op in 1:1){
m <- m %*% M
}

z = x %*% m

result is effectively x.dot(M.dot(M)):

228, 516, 804

In python this loop can be reduced by:

x.dot(np.linalg.multi_dot([M]*2))

Is there something similar for R?

CodePudding user response:

library(expm)

x %*% (M %^% 2)

     [,1] [,2] [,3]
[1,]  228  516  804

As @akrun commented, you could also use Reduce:

Reduce('%*%', rep(list(M), 2), init = x)

     [,1] [,2] [,3]
[1,]  228  516  804
  • Related