|
Version 1.1 (July 2015)
dbind
[R] Binding two matrices diagonally
dbind(M,A) returns the matrix
Menu
Top Syntax
dbind(m, a, rev=F)
Top dbind arguments
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
> a <- matrix(10*seq(9), ncol=3) > a
> d <- dbind(m, a) > d
d.rev <- dbind(m, a, rev=T) > d.rev
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. |