Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create block matrices with identical value in R

Tags:

r

matrix

I want to create k blocks with identical values in a n*n matrix (k can be divided exactly by the row number times the columns number as n*n ):

for example, when n = 4 and k = 4, (k can be divided exactly by 4*4=16), a matrix is create like this:

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?

like image 587
Seen Avatar asked Dec 27 '22 16:12

Seen


1 Answers

There's a fantastically useful mathematical operator called a 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 of sparse matrices (?"kronecker-methods"), so that you can easily build huge sparse patterned matrices as long as you can find a way to express the pattern in terms of Kronecker products.

like image 119
Ben Bolker Avatar answered Jan 10 '23 17:01

Ben Bolker