Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block-diagonal binding of matrices

Tags:

r

matrix

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
like image 256
Ferdinand.kraft Avatar asked Jul 05 '13 19:07

Ferdinand.kraft


People also ask

What is the meaning of block diagonal matrix?

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.

Is block diagonal matrix a square matrix?

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.

What is block form of a matrix?

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.

Do block diagonal matrices commute?

No, every symmetric matrix and the diagonal matrix doesnot commute. Hence the matrices will not commute.


1 Answers

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.

like image 93
Julius Vainora Avatar answered Sep 28 '22 06:09

Julius Vainora