[R] Multiple matrix multiplication with two 3-dimensional arrays

Gabor Grothendieck ggrothendieck at gmail.com
Fri Sep 8 15:59:38 CEST 2006


If the arrays are a1 and a2 then:

library(abind)
abind(lapply(1:dim(a1)[3], function(i) a1[,,i] %*% a2[,,i]), along = 3)


On 9/8/06, Sophie Baillargeon <Sophie.Baillargeon at mat.ulaval.ca> wrote:
>
> Hi,
>
> I need to do several matrix multiplications with
> the corresponding matrices forming two
> 3-dimentional arrays. To illustrate my problem,
> let's say I have the following 3-dimensional arrays:
>
> array1 <- array(1:30,dim=c(3,2,5))
> array2 <- array(1:20,dim=c(2,2,5))
>
> I know that I can get what I want with the following computation :
>
> result <- array(dim=c(dim(array1)[1], dim(array2)[2], dim(array1)[3]))
> for (i in 1: dim(array1)[3])
> {
>             result[,,i] <- array1[,,i]%*%array2[,,i]
> }
>
> My question is :
> Is there a more efficient way to do that computation, i.e. without a loop?
>
> Maybe I could use an "apply" or something but I
> can't figure out how. I would have hoped that simply doing
>
> array1%*%array2
>
> would work, but it doesn't…
>
>
> Thank you very much!
>
>
> Sophie Baillargeon
>
> __________________________________________
>
> Sophie Baillargeon, M.Sc.
>
> Professionnelle de recherche en statistique
> Département de mathématiques et de statistique
> Université Laval
> téléphone: (418) 656-2131 poste 2333
> courriel: Sophie.Baillargeon at mat.ulaval.ca
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list