【问题标题】:Merging multiple combination matrices together将多个组合矩阵合并在一起
【发布时间】: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


    【解决方案1】:

    使用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))
    

    【讨论】:

      【解决方案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)
      

      取决于你想先回收哪个组合矩阵。

      【讨论】:

      • (+1) 用于使用%x%。你能简要解释一下它是如何工作的吗?文档非常有限。
      • 也许这个链接会有所帮助:en.wikipedia.org/wiki/Kronecker_product。通过使两个矩阵中的一个矩阵成为一行,我有效地重复了整个矩阵,有点像rep 函数对向量所做的事情。再次使用相同的rep 类比,参数的顺序是使用timeseach 之间的区别。
      猜你喜欢
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2019-07-16
      • 2016-03-18
      • 2016-04-08
      • 1970-01-01
      相关资源
      最近更新 更多