获取所有矩阵列元素乘积的快速方法

Fast way to get all pairs of matrix column element-wise products

假设我有一个数字 matrix:

set.seed(1)
mat <- matrix(rnorm(1000), ncol = 100)

我想生成所有向量,这些向量是 mat 中所有唯一向量对的逐元素乘积的结果。

我们如何改进以下代码:

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]]))

我们可以做到:

n <- ncol(mat)
lst <- lapply(1:n, function (i) mat[,i] * mat[,i:n])
do.call(cbind, lst)

或者,这里有一个更快的方法:

n <- ncol(mat)
j1 <- rep.int(1:n, n:1)
j2 <- sequence(n:1) - 1L + j1
mat[, j1] * mat[, j2]

注意,上面将包括列与自身的乘法。如果你想禁止它,使用

n <- ncol(mat)
lst <- lapply(1:(n-1), function (i) mat[,i] * mat[,(i+1):n])
do.call(cbind, lst)

n <- ncol(mat)
j1 <- rep.int(1:(n-1), (n-1):1)
j2 <- sequence((n-1):1) + j1
mat[, j1] * mat[, j2]

实际上,上面创建的j1j2只是combn(1:ncol(mat),2)的第一行和第二行。因此,如果您仍想继续使用 combn,请使用

all.pairs <- combn(1:ncol(mat),2)
mat[, all.pairs[1,]] * mat[, all.pairs[2,]]