2

我有两个由组合构建的矩阵

mat1 <- combn(10, 2)
mat2 <- combn(20, 3)

mat1 是 2x45,mat2 是 3x1140。

我想要产生的是假设您按顺序执行这两种操作的可能组合。所以前10选2,紧接着20选3,都是什么组合。我想生成一个 5 行 51300 列的矩阵。第一列值为 (1, 2, 1, 2, 3)

实现这一点的最合适方法是什么?

4

2 回答 2

2

有趣的问题。这是一个使用几个 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)

取决于您要首先回收的组合矩阵。

于 2013-04-30T02:38:32.813 回答
2

另一种可能的解决方案是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))
于 2013-04-30T03:19:56.417 回答