Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

r - Block-diagonal binding of matrices

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:

a <- matrix(1:6, 2, 3)
b <- matrix(7:10, 2, 2)

rbind(cbind(a, matrix(0, nrow=nrow(a), ncol=ncol(b))),
      cbind(matrix(0, nrow=nrow(b), ncol=ncol(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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...