I know A'A will give a symmetric positive definite matrix. But how can I generate random matrix in R that is symmetric, but not necessary to be positive definite?
            Asked
            
        
        
            Active
            
        
            Viewed 584 times
        
    1 Answers
4
            The details will of course depend on what distribution you'll want the matrix elements to have, but once you settle on that, you can adapt something like the following:
m <- matrix(sample(1:20, 36, replace=TRUE), nrow=6)
m[lower.tri(m)] <- t(m)[lower.tri(m)]
m
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]   19   20   15    6    5   14
# [2,]   20   20   20    3   18   17
# [3,]   15   20    6    5   11    3
# [4,]    6    3    5    6    9   20
# [5,]    5   18   11    9   10    2
# [6,]   14   17    3   20    2    7
For ease of use, you can then wrap up code like that in a function, like so:
f <- function(n) {
    m <- matrix(sample(1:20, n^2, replace=TRUE), nrow=n)
    m[lower.tri(m)] <- t(m)[lower.tri(m)]
    m
}
## Try it out
f(2)
#      [,1] [,2]
# [1,]    9   13
# [2,]   13   15
f(3)
#      [,1] [,2] [,3]
# [1,]    1    8    3
# [2,]    8   13    5
# [3,]    3    5   14
        Josh O'Brien
        
- 159,210
 - 26
 - 366
 - 455
 
- 
                    
 - 
                    Try `A[lower.tri(A)]=t(A)[upper.tri(A)]` instead of `A[lower.tri(A)]=A[upper.tri(A)]`. (i.e. replace `A` with `t(A)` on the right hand side. – Josh O'Brien Jan 17 '18 at 20:56
 -