Jon
Jon

Reputation: 15

How to duplicate matrices in an array

Say that I have a matrix a with dimensions 2x2. How would I create a 2x2xk array that is just k iterations of matrix a?

I suspect that the abind package is my friend, but so far I haven't figured out how to do some sort of rep(a,k) formula that replicates the entire matrix, not just the elements. I can't find a way to do this short of listing out matrix a k times in the abind formula, like in the code below for a 2x2x6 array.

a <- matrix(c(1,0,0,1), nrow=2)
library(abind)
axk <- abind(a,a,a,a,a,a,along=3)

I want the output to be the equivalent of axk, but without needing to list out the matrix k times.

Upvotes: 0

Views: 98

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84559

You can do

> replicate(6, a)
, , 1

     [,1] [,2]
[1,]    1    0
[2,]    0    1

, , 2

     [,1] [,2]
[1,]    1    0
[2,]    0    1

, , 3

     [,1] [,2]
[1,]    1    0
[2,]    0    1

, , 4

     [,1] [,2]
[1,]    1    0
[2,]    0    1

, , 5

     [,1] [,2]
[1,]    1    0
[2,]    0    1

, , 6

     [,1] [,2]
[1,]    1    0
[2,]    0    1

Upvotes: 1

Related Questions