【发布时间】:2013-04-30 01:52:17
【问题描述】:
我有两个由组合构建的矩阵
mat1 <- combn(10, 2)
mat2 <- combn(20, 3)
mat1 是 2x45,mat2 是 3x1140。
我想要生成的是假设您按顺序执行这两个操作的可能组合。所以前10选2,紧接着20选3,都是什么组合。我想生成一个 5 行 51300 列的矩阵。第一列的值为 (1, 2, 1, 2, 3)
什么是最合适的实现方式?
【问题讨论】:
标签: r
我有两个由组合构建的矩阵
mat1 <- combn(10, 2)
mat2 <- combn(20, 3)
mat1 是 2x45,mat2 是 3x1140。
我想要生成的是假设您按顺序执行这两个操作的可能组合。所以前10选2,紧接着20选3,都是什么组合。我想生成一个 5 行 51300 列的矩阵。第一列的值为 (1, 2, 1, 2, 3)
什么是最合适的实现方式?
【问题讨论】:
标签: r
使用expand.grid的另一种可能的解决方案:
idx = expand.grid((1:ncol(mat1)),(1:ncol(mat2)))
rbind(mat1[,idx[,1]], mat2[,idx[,2]])
泛化到任意数量的矩阵:
mat.list <- list(mat1, mat2)
idx <- expand.grid(lapply(lapply(mat.list, ncol), seq_len))
do.call(rbind, mapply(function(x, j)x[, j], mat.list, idx))
【讨论】:
有趣的问题。这是一个使用几个 Kronecker 产品的解决方案:
one1 <- matrix(1, ncol = ncol(mat1))
one2 <- matrix(1, ncol = ncol(mat2))
rbind(mat1 %x% one2, one1 %x% mat2)
或
rbind(one2 %x% mat1, mat2 %x% one1)
取决于你想先回收哪个组合矩阵。
【讨论】:
%x%。你能简要解释一下它是如何工作的吗?文档非常有限。
rep 函数对向量所做的事情。再次使用相同的rep 类比,参数的顺序是使用times 或each 之间的区别。