Site icon R-bloggers

Block diagonal matrices in R

[This article was first published on Christophe Ladroue » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
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.

Selec All 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:

Selec All Code:
1
blockMatrix<-blockMatrixDiagonal(m1,m2,m2,m1)

Or a list of matrices:

Selec All Code:
1
blockMatrix<-blockMatrixDiagonal(list(m1,m2,m2,m1))

It produces:

Selec All 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:

Selec All 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
  }

To leave a comment for the author, please follow the link and comment on their blog: Christophe Ladroue » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.