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

送分小仙女□ 提交于 2019-12-10 16:17:16

问题


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

回答1:


We could do:

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

Or, here is an even faster way:

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

Note, the above will include the multiplication of a column to itself. If you want to forbid that, use

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

and

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

Actually, j1 and j2 created above are just the 1st and 2nd row of combn(1:ncol(mat),2). So, if you still want to stay with combn, use

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


来源:https://stackoverflow.com/questions/40139534/fast-way-to-get-all-pairs-of-matrix-column-element-wise-products

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!