Skip to content

How to 'explode' a matrix

5 messages · Kevin Ummel, Henrique Dallazuanna, Ben Bolker +1 more

#
Hi everyone,

I'm looking for a way to 'explode' a matrix like this:
[,1] [,2]
[1,]    1    3
[2,]    2    4

into a matrix like this:
[,1] [,2] [,3] [,4]
[1,]    1    1    3    3
[2,]    1    1    3    3
[3,]    2    2    4    4
[4,]    2    2    4    4

My current kludge is this:

v1=rep(1:4,each=2,times=2)
v2=v1[order(rep(1:2,each=4,times=2))]
matrix(v2,4,4)

But I'm hoping there's a more efficient solution that I'm not aware of.

Many thanks,
Kevin
#
Kevin Ummel <kevinummel <at> gmail.com> writes:
This is the Kronecker product of your matrix with the
matrix  (1 1 ; 1 1)

m <- matrix(1:4,2,2)
kronecker(m,matrix(1,2,2))

  cheers
    Ben Bolker