[R] block diagonal matrix function

Robin Hankin rksh at soc.soton.ac.uk
Thu May 27 10:24:39 CEST 2004


Hello List

I have just written a little function that takes two matrices as
arguments and returns a large matrix that is composed of the two input
matrices in upper-left position and lower-right position with a padding
value everywhere else. (function definition and toy example below).  I
need nonsquare matrices and rowname() and colname() inherited appropriately.

Two questions:

(1) Is there a better way to do this? (kronecker() isn't applicable here)

(2) How do I generalize it to take an arbitrary number of matrices as
     inputs?


TIV

Robin



"blockdiag" <-
function (m1, m2, p.tr = 0, p.ll = 0)
{
     ## p.tr and p.ll are padding values
     topleft <- m1
     topright <- matrix(p.tr, nrow(m1), ncol(m2))
     colnames(topright) <- colnames(m2)
     lowleft <- matrix(p.ll, nrow(m2), ncol(m1))
     lowright <- m2
     rbind(cbind(topleft, topright), cbind(lowleft, lowright))
}

m1 <-
structure(c(1, 1, 3, 1, 3, 4), .Dim = as.integer(c(2, 3)), .Dimnames = list(
     c("a", "b"), c("x", "y", "z")))

m2 <-
structure(c(2, 1, 1, 0, 3, 2, 2, 2, 0), .Dim = as.integer(c(3,
3)), .Dimnames = list(c("I", "II", "III"), c("A", "B", "C")))

R> m1
   x y z
a 1 3 3
b 1 1 4

R> m2
     A B C
I   2 0 2
II  1 3 2
III 1 2 0

R> blockdiag(m1,m2)
     x y z A B C
a   1 3 3 0 0 0
b   1 1 4 0 0 0
I   0 0 0 2 0 2
II  0 0 0 1 3 2
III 0 0 0 1 2 0
R>
-- 
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
SO14 3ZH
tel +44(0)23-8059-7743
initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)




More information about the R-help mailing list