Take the matrix product of all the elements in an array in R?

How can one take the matrix product of all the elements in an array in R?
I have searched stack exchange, and have not found any results.

n <- 3
ARRAY <- array(NA, dim = c(4, 4, n))
for (i in 1:4) {
    for (j in 1:4) {
        ARRAY[i, j, ] <- rnorm(n)
    }
}

# this gives me a 1x1 matrix, which is wrong
Reduce("%*%", ARRAY)
mapply("%*%", ARRAY[,,1], ARRAY[,,2])

# this works, but I'd like a generalizable option
ARRAY[,,1]%*%ARRAY[,,2]%*%ARRAY[,,3]

>Solution :

We may use asplit to split by the third dimension into a list and then use Reduce

out2 <-  Reduce(`%*%`, asplit(ARRAY, 3))

-testing

> out1 <- ARRAY[,,1]%*%ARRAY[,,2]%*%ARRAY[,,3]
> identical(out1, out2)
[1] TRUE

Or may also loop over the last dim sequence, extract the elements in a list

out2 <- Reduce("%*%", lapply(seq(dim(ARRAY)[3]), function(i) ARRAY[,, i]))

Or may also use array_branch from purrr

library(purrr)
library(magrittr)
out3 <- array_branch(ARRAY, 3) %>%
    reduce(`%*%`)
> identical(out1, out3)
[1] TRUE

Leave a Reply