【问题标题】:What is the fastest way to construct this sparse matrix in R在 R 中构造这个稀疏矩阵的最快方法是什么
【发布时间】:2021-01-14 11:12:05
【问题描述】:

在R中构造上述矩阵的最快方法是什么?不知何故,我觉得必须有比下面更好的方法。

M <- t(matrix(c(1,1,1,-1,-1,-1),nrow=3))
M <- rbind(M, matrix(rep(0,9), nrow=3))
M <- cbind(M, matrix(rep(0,5*3), ncol=3))
M <- cbind(M,rbind(matrix(rep(0,2*3),ncol=3),diag(3)))

【问题讨论】:

    标签: r matrix sparse-matrix


    【解决方案1】:

    我们可以使用bdiag 在一行中完成此操作

    library(Matrix)
    as.matrix(bdiag(cbind(rbind(rep(1, 3), rep(-1, 3)), 0, 0),  diag(3)))
    

    -输出

    #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
    #[1,]    1    1    1    0    0    0    0    0
    #[2,]   -1   -1   -1    0    0    0    0    0
    #[3,]    0    0    0    0    0    1    0    0
    #[4,]    0    0    0    0    0    0    1    0
    #[5,]    0    0    0    0    0    0    0    1
    

    【讨论】:

      【解决方案2】:

      如果你想要单线,你可以这样做:

      t(`[<-`(`[<-`(`[<-`(matrix(0, 9, 5), 1:3, 1), 10:12, -1), 7:9, 3:5, diag(3)))
      #>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
      #> [1,]    1    1    1    0    0    0    0    0    0
      #> [2,]   -1   -1   -1    0    0    0    0    0    0
      #> [3,]    0    0    0    0    0    0    1    0    0
      #> [4,]    0    0    0    0    0    0    0    1    0
      #> [5,]    0    0    0    0    0    0    0    0    1
      
      

      或者如果你想要一些真正的代码高尔夫,

      `[<-`(`[<-`(matrix(0,5,9),c(1+0:2*5,0:2*6+33),1),2+0:2*5,-1)
      

      【讨论】:

      • 天哪,这看起来很酷。我需要一些时间来弄清楚!
      【解决方案3】:

      矩阵只是一个带有dim 属性的向量。 matrix(c(rep(c(1,-1,0,0,0),3), rep(0,17), 1, rep(c(rep(0,5), 1), 2)), ncol = 9)

      【讨论】:

        【解决方案4】:

        这个怎么样?

        M <- matrix(0,nrow = 5,ncol = 9)
        M[1,1:3] <- 1
        M[2,1:3] <- -1
        diag(M[3:5,7:9]) <- 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-29
          • 2018-03-09
          • 2020-09-04
          • 1970-01-01
          • 1970-01-01
          • 2011-04-08
          • 2015-01-30
          • 2018-03-10
          相关资源
          最近更新 更多