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
A block diagonal matrix, also called a diagonal block matrix, is a square diagonal matrix in which the diagonal elements are square matrices of any size (possibly even. ), and the off-diagonal elements are 0.
The matrices can be either square or rectangular and can differ in size. If any of the input matrices are sparse, then the output block diagonal matrix is also sparse.
A block matrix is a matrix whose elements are themselves matrices, which are called submatrices. By allowing a matrix to be viewed at different levels of abstraction, the block matrix viewpoint enables elegant proofs of results and facilitates the development and understanding of numerical algorithms.
No, every symmetric matrix and the diagonal matrix doesnot commute. Hence the matrices will not commute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With