[R] building random matrices from vectors of random parameters
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Sep 28 11:11:09 CEST 2017
On 27/09/2017 8:47 PM, Evan Cooch wrote:
> Suppose I have interest in a matrix with the following symbolic
> structure (specified by 3 parameters: sa, so, m):
>
> matrix(c(0,sa*m,so,sa),2,2,byrow=T)
>
> What I can't figure out is how to construct a series of matrices, where
> the elements/parameters are rnorm values. I'd like to construct separate
> matrices, with each matrix in the series using the 'next random
> parameter value'. While the following works (for generating, say, 5 such
> random matrices)
>
> replicate(5,matrix(c(0,rnorm(1,0.8,0.1)*rnorm(1,1.2,0.1),rnorm(1,0.5,0.1),rnorm(1,0.8,0.1)),2,2,byrow=T))
>
> its inelegant, and a real pain if the matrix gets large (say, 20 x 20).
>
> I'm wondering if there is an easier way. I tried
>
> > sa <- rnorm(5,0.8,0.1)
> > so <- rnorm(5,0.5,0.1)
> > m <- rnorm(5,1.2,0.1)
>
> matrix(c(0,sa*m,so,sa),2,2,byrow=T)
>
> but that only returns a single matrix, not 5 matrices as I'd like. I
> also tried several variants of the 'replicate' approach (above), but
> didn't stumble across anything that seemed to work.
>
> So, is there a better way than something like:
>
> replicate(5,matrix(c(0,rnorm(1,0.8,0.1)*rnorm(1,1.2,0.1),rnorm(1,0.5,0.1),rnorm(1,0.8,0.1)),2,2,byrow=T))
>
Peter's mapply solution is probably the best. Another that might be a
little faster (but more obscure) is to use a 3-index array. I think
this is what you'd want, with sa, so, and m as defined above:
ms <- array(c(rep(0, 5),sa*m,so,sa), c(5, 2, 2))
Then matrix i will be stored as ms[i,,].
Duncan Murdoch
More information about the R-help
mailing list