Block diagonal matrices in R

April 13, 2011
By

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[[1]])) matrixList<-matrixList[[1]]   dimensions<-sapply(matrixList,FUN=function(x) dim(x)[1]) 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 }

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...