Block diagonal matrices in R

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.

Select 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:

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

Or a list of matrices:

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

It produces:

Select 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:

Select 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
  }
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

2 Responses to Block diagonal matrices in R

  1. Ben Bolker says:

    Hmmm. Did you try library(sos); findFn(“block diagonal”) ?

    library(Matrix)
    m1 <- matrix(runif(4),ncol=2)
    m2 <- matrix(1:4,ncol=2)
    as.matrix(bdiag(m1,m2))

  2. CL says:

    No I didn’t, although I suspected it had been done before (I started using R 2 months ago, I’m still climbing the learning curve).
    I didn’t know this ‘sos’ package, I’ve just installed it now. Thanks, it’ll probably save me time in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


six + 4 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">