Not answering the question, but if you have the same dimensions of the matrices everywhere, it is much more efficient to sample all numbers in a row and put stuff into an array:

array(rnorm(5*4), dim=c(2,2,5)))

Best,
Uwe Ligges




On 09.11.2016 19:51, Marc Schwartz wrote:

On Nov 9, 2016, at 12:41 PM, Marc Schwartz <marc_schwa...@me.com> wrote:


On Nov 9, 2016, at 12:32 PM, Evan Cooch <evan.co...@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.

Thanks in advance...


Hi,

See ?replicate

Example:

## Create a list of 5 2x2 matrices



Sorry, correction on my reply.

I copied the wrong output, It should be:

replicate(5, matrix(rnorm(4), 2, 2), simplify = FALSE)
[[1]]
          [,1]      [,2]
[1,] 0.9700486 1.4249251
[2,] 0.7621312 0.8267747

[[2]]
          [,1]       [,2]
[1,] 0.4517927  0.2047509
[2,] 0.6336959 -0.6028124

[[3]]
          [,1]      [,2]
[1,] 0.6468823 0.4268734
[2,] 0.1664907 0.3905180

[[4]]
           [,1]       [,2]
[1,] -0.3170839 -1.0113201
[2,] -1.5356600  0.9658132

[[5]]
           [,1]       [,2]
[1,] -1.1937503 -0.2653502
[2,]  0.9319919  0.1780254


The 'simplify' argument should be FALSE, so that an array is not created.

Regards,

Marc Schwartz


        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to