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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With