Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enlarge matrix proportionally in R

Tags:

r

matrix

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.

like image 355
curbholes Avatar asked Dec 25 '22 09:12

curbholes


1 Answers

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
like image 116
Julius Vainora Avatar answered Jan 13 '23 01:01

Julius Vainora