4

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?

4

1 回答 1

10

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.

于 2012-10-04T13:13:08.667 回答