Monday, September 05, 2005

The block transpose of a matrix

Sometimes it's neat to be able to transpose the subblocks of a matrix: The "block transpose" of an n·k × m matrix can be defined as

Y =
Y1
||
Yk
YBn
Y1'
||
Yk'
where the Yi's are n × m matrices. The following routine performs this function in R:
# the function bt computes the block transpose
bt <-
function(y, n) {
  if(nrow(y)%%n!=0)
     stop(n,' is not a valid block size for this matrix.')
  m = ncol(y)
  k = nrow(y) %/% n
  matrix( aperm(array(t(y), c(m,n,k)), c(2,1,3)), , n, byrow=TRUE)
}
An example:
> idx = expand.grid(1:2,1:3,letters[1:4])
> m = matrix(paste(idx[,3],idx[,2],idx[,1],sep=''),nc=2,byrow=TRUE)
> m
      [,1]  [,2]
 [1,] "a11" "a12"
 [2,] "a21" "a22"
 [3,] "a31" "a32"
 [4,] "b11" "b12"
 [5,] "b21" "b22"
 [6,] "b31" "b32"
 [7,] "c11" "c12"
 [8,] "c21" "c22"
 [9,] "c31" "c32"
[10,] "d11" "d12"
[11,] "d21" "d22"
[12,] "d31" "d32"
> bt(m,3)
     [,1]  [,2]  [,3]
[1,] "a11" "a21" "a31"
[2,] "a12" "a22" "a32"
[3,] "b11" "b21" "b31"
[4,] "b12" "b22" "b32"
[5,] "c11" "c21" "c31"
[6,] "c12" "c22" "c32"
[7,] "d11" "d21" "d31"

Labels: , , ,