0

Is there an easy way to build a matrix in R based on several other block matrix?

Suppose that I have A1,A2,A3 and A4 matrix. I want to construct a Matrix A that is the equivalent in matlab of [A1,A2;A3;A4]. I know that i could use rbind(cbind(A1,A2),cbind(A3,A4)), is there a more efficient and direct way?

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. But generally in R you need to use `rbind` and `cbind` to combine matrices. You could write your own function to make it easier, but as far as base options go that's kind of it. – MrFlick Feb 27 '20 at 16:54
  • 3
    Out of curiosity, what do you find inefficient about your `rbind()` / `cbind()` approach? – Aaron Montgomery Feb 27 '20 at 17:02

1 Answers1

3

R doesn't really have a lot of shortcut notations for creating matrices like matlab. The most explicit it just to stick with the rbind and cbind as you've already done. If it's something you find yourself doing a lot, you could write a helper function like this

mat_shape <- function(expr) {
  env<-new.env(parent=parent.frame())
  env[[":"]] <- base::cbind
  env[["/"]] <- base::rbind
  eval(substitute(expr), envir = env)
}

here we re-refine : to be cbind and / to be rbind for this particular function input. Then you could do

A <- matrix(1:6, ncol=3)
B <- matrix(1:4, ncol=2)
C <- matrix(1:3, ncol=1)
D <- matrix(1:12, ncol=4)

mat_shape(A:B/C:D)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    3    5    1    3
# [2,]    2    4    6    2    4
# [3,]    1    1    4    7   10
# [4,]    2    2    5    8   11
# [5,]    3    3    6    9   12
MrFlick
  • 195,160
  • 17
  • 277
  • 295