Tomas
Tomas

Reputation: 59455

Create matrix from smaller matrices in R

Is there a general function to build a matrix from smaller blocks, i.e. build matrix

A B
C D

from matrices A, B, C, D?

Of course there is this obvious way to create an empty big matrix and use sub-indexing, but isn't there anything simpler, easier and possibly faster?

Upvotes: 0

Views: 213

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

Here are some base R solutions. Maybe you can use

M <- rbind(cbind(A,B),cbind(C,D))

or

u <- list(list(A,B),list(C,D))
M <- do.call(rbind,Map(function(x) do.call(cbind,x),u))

Example

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

such that

> M
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    1    3    5
[2,]    2    4    2    4    6
[3,]    1    4    1    4    7
[4,]    2    5    2    5    8
[5,]    3    6    3    6    9

Upvotes: 3

Related Questions