如何生成对称随机矩阵?

9

我希望生成一个随机矩阵,该矩阵应当是对称的。

我尝试过以下方法:

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

但它不一定是对称的。

我该怎么做呢?


生成一半的随机矩阵,然后将其复制到另一半。 - Lee Daniel Crocker
2
类似于 m[lower.tri(m)] <- t(m)[lower.tri(m)] 这样的代码非常简洁。 - qzr
4个回答

9

另一个非常有趣的机会基于以下数学事实:如果 A 是某个矩阵,则 A 乘以其转置始终是对称的。

> 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

它不仅将是对称的,而且还将是正定的。这是你想要的吗? - JohnRos
@sheß 原帖没有提到任何“均匀分布”的要求。 - tonytonov
1
这是正确的。只是想确保使用此解决方案的人知道,您在代码第1行中选择的任何分布都不对应您最终得到的分布。这本身并不是坏事,但了解这一点肯定是好的。 - sheß

6

尝试使用 Matrix 包中的以下内容:

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

6
如果您不想使用一个软件包:
n=3
x <- matrix(rnorm(n*n), n) 
ind <- lower.tri(x) 
x[ind] <- t(x)[ind] 
x 

0

我喜欢这个:

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]
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接