Alex
Alex

Reputation: 115

Multiply Corresponding Matrices in Separate Arrays in R

Suppose I have two arrays, A and B, each containing n square mxm matrices; that is, the dimensions of both A and B are dim=c(m,m,n). What is the most efficient way using R to obtain an array of the same dimension of the product A[,,j]%*%B[,,j]%*%t(A[,,j]) for every j between one and n?

Thanks!

Upvotes: 1

Views: 90

Answers (1)

lmo
lmo

Reputation: 38500

Here is one method using Map:

# create some data
set.seed(1234)
A <- replicate(3, matrix(rnorm(4), 2))
B <- replicate(3, matrix(rnorm(4), 2))

# get the results
Map(function(j) A[,,j]%*%B[,,j]%*%t(A[,,j]), 1:3)

The arrays are 2X2X3. Map applies your function to each of the three 3rd dimensional matrices in A and B.

You could also use lapply:

lapply(1:3, function(j) A[,,j]%*%B[,,j]%*%t(A[,,j]))

Upvotes: 2

Related Questions