Skip to content
Prev 76584 / 398502 Next

More block diagonal matrix construction code

hi Bert, List

well now seems a good time to adduce adiag() of package magic.
Function adiag binds together arrays of arbitrary dimension
corner-to-corner.  Sensible interpretation is made for
arguments at the "edge"  of acceptability (eg one array
being a scalar).


The "meat" of the code is as follows:

adiag <- function(a,b,pad=0){
s <- array(pad, dim.a + dim.b)
     s <- do.call("[<-", c(list(s), lapply(dim.a, seq.new), list(a)))
     ind <- lapply(seq(dim.b), function(i) seq.new(dim.b[[i]]) +
         dim.a[[i]])
     out <- do.call("[<-", c(list(s), ind, list(b)))
     return(out)
}

where

  seq.new <- function(i) {   if (i == 0) { return(NULL)} else { return 
(1:i)  }  }

[NB: untested].

so it creates an array "s" of the right size filled with "pad", and then
fills one corner with "a", then fills the other corner with "b".

Note the absence of any for() loops.

Hope this is useful

rksh
On 2 Sep 2005, at 00:08, Berton Gunter wrote:

            
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743