Search code examples
rrandommatrixsymmetric

How to generate symmetric random matrix?


I want to generate a random matrix which should be symmetric.

I have tried this:

matrix(sample(0:1, 25, TRUE), 5, 5)

but it is not necessarily symmetric.

How can I do that?


Solution

  • Try this from the Matrix package

    library(Matrix)
    x<-Matrix(rnorm(9),3)
    x
    3 x 3 Matrix of class "dgeMatrix"
               [,1]       [,2]       [,3]
    [1,] -0.9873338  0.8965887 -0.6041742
    [2,] -0.3729662 -0.5882091 -0.2383262
    [3,]  2.1263985 -0.3550972  0.1067264
    
    X<-forceSymmetric(x)
    X
    3 x 3 Matrix of class "dsyMatrix"
               [,1]       [,2]       [,3]
    [1,] -0.9873338  0.8965887 -0.6041742
    [2,]  0.8965887 -0.5882091 -0.2383262
    [3,] -0.6041742 -0.2383262  0.1067264