Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading