user3294195 - 2 months ago 4x

R Question

I have a

`20 x 10`

`X`

`10 x 10 x 20`

`A`

`A[i,j,] = X[,i] * X[,j]`

`i,j`

`1:10`

`for`

`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.

Source (Stackoverflow)

Comments