2
votes

I have a smaller kxk matrix m given from which I want to create multiple larger NxN diagonal block matrices Q1, Q2, ..., QN. It is ensured that N is always a multiple of k.

A simple example should illustrate better what I mean:

m <- matrix(c(1,3,2,4),2,2) # the small kxk matrix

m
      [,1] [,2]
[1,]    1    2
[2,]    3    4

And I want to get for let's say a 6x6 matrix the following diagonal block matrices:

Q1
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    0    0    0    0
[2,]    3    4    0    0    0    0
[3,]    0    0    0    0    0    0
[4,]    0    0    0    0    0    0
[5,]    0    0    0    0    0    0
[6,]    0    0    0    0    0    0


Q2
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    0    0    0    0
[2,]    0    0    0    0    0    0
[3,]    0    0    1    2    0    0
[4,]    0    0    3    4    0    0
[5,]    0    0    0    0    0    0
[6,]    0    0    0    0    0    0


Q3
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    0    0    0    0
[2,]    0    0    0    0    0    0
[3,]    0    0    0    0    0    0
[4,]    0    0    0    0    0    0
[5,]    0    0    0    0    1    2
[6,]    0    0    0    0    3    4

Any ideas how I could achieve this e.g. with lapply such that I can do the same for large matrices?

1

1 Answers

2
votes

We can do this with bdiag from Matrix

library(Matrix)
lst <- list(bdiag(m, diag(4)*0), bdiag(0*diag(2), m, 0*diag(2)), bdiag(diag(4)*0, m))

If we want to change it to matrix, then use as.matrix

lapply(lst, as.matrix)

Also, this can be created as a single sparseMatrix

bdiag(list(m, 0*diag(6))[rep(1:2, length.out=5)])