Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 249
Daycent Avatar asked Oct 19 '25 01:10

Daycent


1 Answers

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
like image 144
akrun Avatar answered Oct 21 '25 14:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!