user3294195 user3294195 - 4 months ago 5
R Question

Column-wise "outer-product"

I have a

20 x 10
matrix
X
, and I want to create a
10 x 10 x 20
array
A
with
A[i,j,] = X[,i] * X[,j]
for
i,j
in
1:10
. Here is a simple solution using a
for
loop:

X <- matrix(seq(10*20),20,10)
A <- array(dim=c(10,10,20))
for (i in 1:10)
for (j in 1:10)
A[i,j,] <- X[,i] * X[,j]


How do I implement this with vectorization?

Thanks.

Answer

Use outer, is this what you want?

A2 = array(apply(X, 1L, function (x) outer(x,x)), dim=c(10,10,20))

# test
X <- matrix(seq(10*20),20,10)
A <- array(dim=c(10,10,20))
for (i in 1:10){
  for (j in 1:10){
    A[i,j,] <- X[,i] * X[,j]
  }
}

all.equal(A, A2) # TRUE

EDIT: updated answer after question example in question was changed.