Skip to content
Prev 17462 / 398513 Next

a trick ??

A more general solution (given a list of matrices [with any
dimensions] blockdiag(a1,a2,a3) gives the block diagonal concatenation of
the matrices).  I don't know if "kronecker" can do this or not.


blockdiag <- function(...) {
  args <- list(...)
  nr <- sapply(args,nrow)
  nc <- sapply(args,ncol)
  cumnc <- cumsum(nc)
  NR <- sum(nr)
  NC <- sum(nc)
  rowfun <- function(m,zbefore,zafter) {
    cbind(matrix(0,ncol=zbefore,nrow=nrow(m)),m,
          matrix(0,ncol=zafter,nrow=nrow(m)))
  }
  ret <- rowfun(args[[1]],0,NC-ncol(args[[1]]))
  for (i in 2:length(args)) {
    ret <- rbind(ret,rowfun(args[[i]],cumnc[i-1],NC-cumnc[i]))
  }
  ret
}
On Tue, 26 Feb 2002, Olivier Martin wrote: