Let's say I have a numerical matrix
:
set.seed(1)
mat <- matrix(rnorm(1000), ncol = 100)
I want to generate all vectors that are the result of the element-wise product of all unique pairs of vectors in mat
.
How can we improve below code:
all.pairs <- t(combn(1:ncol(mat), 2))
res <-
do.call(cbind,
lapply(1:nrow(all.pairs),
function(p) mat[, all.pairs[p, 1]] * mat[, all.pairs[p, 2]]))