Home > Software engineering >  create block matrix in R
create block matrix in R

Time:02-24

I want to create a block matrix, yet not a diagonal one. For example

# Matrix M

M = matrix(c(1,1,1,3,3,3, rep(0,9),
             1,1,1,3,3,3, rep(0,9),
             5,5,5,2,2,2, rep(0,9),
             5,5,5,2,2,2, rep(0,9)), nrow = 15)

So, I want the block of 1's and next to it the block of 5's with specific dimensions. I can create a zero matrix as the base matrix then fills in the blocks.

Your help is appreciated

CodePudding user response:

Create a 2x2 matrix m1 from the 4 numbers and then take the kronecker product of that with a 3x2 matrix m2 of ones giving m3. rbind m3 to a 9x4 matrix m4 of zeros.

m1 <- matrix(c(1, 3, 5, 2), 2)
m2 <- matrix(1, 3, 2)
m3 <- m1 %x% m2
m4 <- matrix(0, 9, ncol(m3))
rbind(m3, m4)

giving:

      [,1] [,2] [,3] [,4]
 [1,]    1    1    5    5
 [2,]    1    1    5    5
 [3,]    1    1    5    5
 [4,]    3    3    2    2
 [5,]    3    3    2    2
 [6,]    3    3    2    2
 [7,]    0    0    0    0
 [8,]    0    0    0    0
 [9,]    0    0    0    0
[10,]    0    0    0    0
[11,]    0    0    0    0
[12,]    0    0    0    0
[13,]    0    0    0    0
[14,]    0    0    0    0
[15,]    0    0    0    0
  •  Tags:  
  • r
  • Related