I have a piece of code ported from Python to R. The original Python version uses np.einsum. Since I could not find an np.einsum equivalent in R, and I wanted to be sure I understood it, I directly coded it using for loops. Now, I'm wondering if there is a faster alternative.
Example code:
n = 2 ; d = 3 ; nx = 4 ; v = 5
array4d <- array( runif(n*nx*v*d ,-1,0),
dim = c(n, nx, v, d) )
array3d <- array( runif(n*v*d ,-1,0),
dim = c(n, v, d) )
einsum_result <- array( rep(0, n*nx*d),
dim = c(n, nx, d))
# original Python version: np.einsum('ikl,ijkl->ijl', array3d, array4d, optimize=False)
# R version
for (i in 1: n) {
for( j in 1: nx) {
for( l in 1: d ) {
einsum_result[i, j, l] <- einsum_result[i, j, l] +
sum( array3d[i, , l] * array4d[i, j, , l])
}}}
I have tried to remove the j
loop (since j
/ nx
will usually be the biggest number) using matrix multiplication, but could not work it out correctly.
Any advise appreciated!