Create block matrices with the same value in R

I want to create k blocks with the same values ​​in an n * n matrix (k can be divided exactly by the number of rows whose number of columns is n * n):

for example, when n = 4 and k = 4, (k can be divided exactly by 4 * 4 = 16), the matrix is ​​created as follows:

1 1 2 2 1 1 2 2 3 3 4 4 3 3 4 4 

How can I do this without a for loop?

+4
source share
1 answer

There is a fantastically useful math operator called the Kronecker product :

 m1 <- matrix(1:4,nrow=2,byrow=TRUE) m2 <- matrix(1,nrow=2,ncol=2) kronecker(m1,m2) 

The Matrix package has methods for Kronecker products with sparse matrices ( ?"kronecker-methods" ), so you can easily create huge sparse matrix matrices, while you can find a way to express the template in terms of Kronecker products.

+8
source

Source: https://habr.com/ru/post/1437802/