Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. As far as I can tell, R doesn’t have a function for building block diagonal matrices so as I needed one, I’ve coded it myself. It might save someone some time.

Example:
Let m1 and m2 two square matrices.

Code:

 ```1 2 ``` ```m1=matrix(runif(10*10),nrow=10,ncol=10) m2=matrix(runif(5*5),nrow=5,ncol=5)```

By passing any number of matrices as argument:

Code:

 ```1 ``` `blockMatrix<-blockMatrixDiagonal(m1,m2,m2,m1)`

Or a list of matrices:

Code:

 ```1 ``` `blockMatrix<-blockMatrixDiagonal(list(m1,m2,m2,m1))`

It produces:

Code:

 ```1 2 ``` ```colourScale<-seq(0,1,length.out=100) image(blockMatrix[30:1,],asp=1,col=rgb(colourScale,colourScale,colourScale),ann=FALSE,xaxt="n",yaxt="n",axes=FALSE)``` That is, a matrix which is zero everywhere but with m1,m2,m2 and m1 on the diagonal.
Code:

Code:

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ``` ```# builds a block matrix whose diagonals are the square matrices provided. # m1=matrix(runif(10*10),nrow=10,ncol=10) # m2=matrix(runif(5*5),nrow=5,ncol=5) # blockMatrix<-blockMatrixDiagonal(m1,m2,m2,m1) # or # blockMatrix<-blockMatrixDiagonal(list(m1,m2,m2,m1)) # C.Ladroue   blockMatrixDiagonal<-function(...){ matrixList<-list(...) if(is.list(matrixList[])) matrixList<-matrixList[]   dimensions<-sapply(matrixList,FUN=function(x) dim(x)) finalDimension<-sum(dimensions) finalMatrix<-matrix(0,nrow=finalDimension,ncol=finalDimension) index<-1 for(k in 1:length(dimensions)){ finalMatrix[index:(index+dimensions[k]-1),index:(index+dimensions[k]-1)]<-matrixList[[k]] index<-index+dimensions[k] } finalMatrix }```