Block-diagonal binding of matrices

前端 未结 1 539
无人共我
无人共我 2020-11-29 11:06

Does R have a base function to bind matrices in a block-diagonal shape?

The following does the job, but I\'d like to know if there is a standard way:



        
相关标签:
1条回答
  • 2020-11-29 11:49

    adiag from a package magic does what you want:

    library(magic)
    adiag(a,b)
         [,1] [,2] [,3] [,4] [,5]
    [1,]    1    3    5    0    0
    [2,]    2    4    6    0    0
    [3,]    0    0    0    7    9
    [4,]    0    0    0    8   10
    

    Alternatively, you could use a package Matrix and function bdiag

    library(Matrix)
    bdiag(a,b)
    4 x 5 sparse Matrix of class "dgCMatrix"
    
    [1,] 1 3 5 .  .
    [2,] 2 4 6 .  .
    [3,] . . . 7  9
    [4,] . . . 8 10
    

    that returns a sparse matrix and which might be more efficient. Use as.matrix(bdiag(a,b)) to get a regular one.

    0 讨论(0)
提交回复
热议问题