Clinician's
corner

Back to main page

Programmer's
corner
So, you use WinBUGS a lot? Want more?
Patrick Blisle
Division of Clinical Epidemiology
McGill University Health Center
Montreal, Quebec CANADA
patrick.belisle@rimuhc.ca

Last modification: 15 jul 2015















Version 1.1 (July 2015)
dbind
[R] Binding two matrices diagonally
[ dbind is an R function developped to bind two matrices diagonally. ]


dbind(M,A) returns the matrix
(M0)
0A


Menu



Top
Syntax

dbind(m, a, rev=F)


Top
dbind arguments

Argument Value Comment
m, a Two matrices to be combined. Note that m and/or a can be scalars.
rev Logical. Whether or not the matrices given in arguments should be used in the reverse order of their entry.
Default is F.


Top
Example

The code below reproduces the input and output of a call to dbind.

> source('c:/users/patrick/R/fcts/dbind.R') # load file where dbind R function is defined
> m <- matrix(seq(8), ncol=4)
> m


[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8

> a <- matrix(10*seq(9), ncol=3)
> a


[,1] [,2] [,3]
[1,] 10 40 70
[2,] 20 50 80
[3,] 30 60 90

> d <- dbind(m, a)
> d


[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 3 5 7 0 0 0
[2,] 2 4 6 8 0 0 0
[3,] 0 0 0 0 10 40 70
[4,] 0 0 0 0 20 50 80
[5,] 0 0 0 0 30 60 90

d.rev <- dbind(m, a, rev=T)
> d.rev


[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 10 40 70 0 0 0 0
[2,] 20 50 80 0 0 0 0
[3,] 30 60 90 0 0 0 0
[4,] 0 0 0 1 3 5 7
[5,] 0 0 0 2 4 6 8

Note that the first line of code in the block above reads in the dbind function code, if it was previously saved to the file referenced by that command. Alternatively, you can cut and paste the function (see code in section below) directly into R. Of course, if you save your session, this step needs to be done only the first time you use dbind.


Top
Code
dbind <- function(m, a, rev=F)
{
   # returns the matrix
   # ( m 0 ) or ( a 0 )
   # ( 0 a ) ( 0 m ) if rev = T

   if ((is.vector(m) & length(m) > 1) | (is.vector(a) & length(a) > 1)) stop("Both m and a must be matrix or scalar.")

   matrix.index <- function(m, row, col) {(col-1)*nrow(m)+row}

   if (!is.matrix(m)) m <- matrix(m, 1, 1)
   if (!is.matrix(a)) a <- matrix(a, 1, 1)

   if (rev)
   {
     tmp <- m
     m <- a
     a <- tmp
   }

   m.dim <- dim(m)
   a.dim <- dim(a)

   if (all(m.dim==0))
   {
     m <- a
   }
   else if (any(a.dim>0))
   {
     new.dim <- m.dim + a.dim

     new <- matrix(0, nrow=new.dim[1], ncol=new.dim[2])
     j <- as.vector(matrix.index(new, row(m), col(m)))
     new[j] <- m
     j <- as.vector(matrix.index(new, m.dim[1] + row(a), m.dim[2] + col(a)))
     new[j] <- a
     m <- new
   }

   m
} # end of dbind


Top
Download

dbind is a free R function. Download version 1.1 now.