The following is the work, but I want 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
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 can use the package Matrix and the function bdiag
library(Matrix)< br />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
Returns a sparse matrix, which may be more efficient. Use as.mat rix(bdiag(a,b)) to get the regular.
Does R have a basis function that binds the matrix in a block diagonal shape?
The following is the work, but I want 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
adiag from package magic do what you want:
p>
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 can use the package Matrix and the 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
Returns a sparse matrix, which may be more efficient. Use as.matrix(bdiag(a,b)) to get the regular one.< /p>