[R] creating lists of random matrices

Marc Schwartz marc_schwartz at me.com
Wed Nov 9 19:41:38 CET 2016

```> On Nov 9, 2016, at 12:32 PM, Evan Cooch <evan.cooch at gmail.com> wrote:
>
> So, its easy enough to create a random matrix, using something like (say)
>
> matrix(rnorm(4),2,2)
>
> which generates a (2x2) matrix with random N(0,1) in each cell.
>
> But, what I need to be able to do is create a 'list' of such random matrices, where the length of the list (i.e., the number of said random matrices I store in the list) is some variable I can pass to the function (or loop).
>
> I tried the obvious like
>
> hold <- list()
> for (i in 1:5) {
>    hold[[i]] <- matrix(rnorm(4),2,2)
>    }
>
>
> While this works, it seems inelegant, and I'm wondering if there is a better (more efficient) way to accomplish the same thing -- perhaps avoiding the loop.
>

Hi,

See ?replicate

Example:

## Create a list of 5 2x2 matrices

> replicate(5, matrix(rnorm(4), 2, 2))
, , 1

[,1]      [,2]
[1,] -0.1695775 1.0306685
[2,]  0.1636667 0.1044762

, , 2

[,1]      [,2]
[1,] -0.3098566 2.1758363
[2,] -0.8029768 0.9697776

, , 3

[,1]      [,2]
[1,]  0.5702972 0.7165806
[2,] -0.9731331 0.8332827

, , 4

[,1]       [,2]
[1,] -0.8089588 0.09195256
[2,] -0.2026994 0.67545827

, , 5

[,1]       [,2]
[1,] 0.5093008 -0.3097362
[2,] 0.6467358  0.3536414

Regards,

Marc Schwartz

[[alternative HTML version deleted]]

```