3
votes

So I'm trying to create a 2000 * 2000 matrix that has 50*50 blocks of zeroes along the diagonal, and 1's everywhere else.

Here is a miniature example of what I mean. a is a 6x6 matrix with 1's and each block is a 2*2 matrix with zeroes along the diagonal

a <- matrix(rep(1, times = 36), nrow = 6, byrow = TRUE)

a[1:2,1:2] <- 0
a[3:4,3:4] <- 0
a[5:6,5:6] <- 0

giving

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

Of course my choice of code is bad for creating such a big matrix, as I would have to repeat the bottom part 50 times.

What would be a much better code to create this type of matrix?

1
I think you would be interested in kronecker products.Dason
+!kronecker(diag(1, 3), matrix(1, 2, 2))rawr
For the 2000 * 2000 matrix example, would +!kronecker(diag(1, 40), matrix(1, 50, 50)) work?Adrian

1 Answers

2
votes

rawr is correct,

a <- +!kronecker(diag(1, 3), matrix(1, 2, 2))

gives

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

and +!kronecker(diag(1, 40), matrix(1, 50, 50)) solves my original question with the 2000*2000 matrix