取R中数组中所有元素的矩阵乘积?

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

如何在 R 中获取数组中所有元素的矩阵乘积? 我搜索了堆栈交换,但没有找到任何结果。

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]

我们可以用asplit按三维分割成一个list然后用Reduce

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

-测试

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

或者也可以遍历最后一个 dim 序列,提取 list

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

或者也可以使用 purrr

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