I have a matrix of 2 rows and 2 columns and want to enlarge this matrix so that it has 4 rows and 4 columns with the same values in it. As if one would "zoom into" the matrix.
This is my 2*2 matrix:
a<-matrix(1:4,nrow=2,byrow=TRUE)
[,1] [,2]
[1,] 1 2
[2,] 3 4
And I want to convert this matrix so it looks like this:
[,1] [,2] [,3] [,4]
[1,] 1 1 2 2
[2,] 1 1 2 2
[3,] 3 3 4 4
[4,] 3 3 4 4
I simplified the problem: the values in the matrix just serve as an example. The true matrix I want to convert consists of 10 rows and columns and should be converted to 30 rows and 30 columns but the principle should be the same.
I am about to solve that problem with a loop but I am sure there must be a more elegant way.
See Kronecker product
enlarge <- function(m, k) kronecker(m, matrix(1, k, k))
enlarge(a, 2)
# [,1] [,2] [,3] [,4]
# [1,] 1 1 2 2
# [2,] 1 1 2 2
# [3,] 3 3 4 4
# [4,] 3 3 4 4
enlarge(a, 3)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 1 2 2 2
# [2,] 1 1 1 2 2 2
# [3,] 1 1 1 2 2 2
# [4,] 3 3 3 4 4 4
# [5,] 3 3 3 4 4 4
# [6,] 3 3 3 4 4 4
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