9

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?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Majid
  • 13,853
  • 15
  • 77
  • 113

4 Answers4

9

Another quite interesting opportunity is based on the following mathematical fact: if A is some matrix, then A multiplied by its transpose is always symmetric.

> A <- matrix(runif(25), 5, 5)
> A %*% t(A)
         [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 1.727769 1.0337816 1.2195505 1.4661507 1.1041355
[2,] 1.033782 1.0037048 0.7368944 0.9073632 0.7643080
[3,] 1.219551 0.7368944 1.8383986 1.3309980 0.9867812
[4,] 1.466151 0.9073632 1.3309980 1.3845322 1.0034140
[5,] 1.104135 0.7643080 0.9867812 1.0034140 0.9376534
tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • It will not only be symmetric, but also positive definite. Is that something you want? – JohnRos Feb 15 '19 at 14:34
  • @sheß The original post doesn't mention any requirement about being "uniformly distributed". – tonytonov Aug 09 '19 at 12:17
  • 1
    that is correct. just wanted to make sure that anyone using this solution is aware that whatever distribution you chose in line 1 of your code does not correspond to the distribution you end up with. that's not per se bad, but it's certainly good to know – sheß Aug 09 '19 at 12:49
6

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
keegan
  • 2,892
  • 1
  • 17
  • 20
6

If you don't want to use a package:

n=3
x <- matrix(rnorm(n*n), n) 
ind <- lower.tri(x) 
x[ind] <- t(x)[ind] 
x 
Robert
  • 5,038
  • 1
  • 25
  • 43
0

I like this one:

n <- 3
aux <- matrix(NA, nrow = n, ncol = n)

for(i in c(1:n)){
    for(j in c(i:n)){
       aux[i,j] <- sample(c(1:n), 1) 
       aux[j,i] <- aux[i,j]
    }
}
thebilly
  • 47
  • 5