Skip to content
Advertisement

np.linalg.multi_dot for R

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement