Maj*_*jid 4 random r symmetric matrix
我想生成一个应该是对称的随机矩阵.
我试过这个:
matrix(sample(0:1, 25, TRUE), 5, 5)
Run Code Online (Sandbox Code Playgroud)
但它不一定是对称的.
我怎样才能做到这一点?
另一个非常有趣的机会是基于以下数学事实:如果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
Run Code Online (Sandbox Code Playgroud)
从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
Run Code Online (Sandbox Code Playgroud)
如果您不想使用包:
n=3
x <- matrix(rnorm(n*n), n)
ind <- lower.tri(x)
x[ind] <- t(x)[ind]
x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1616 次 |
| 最近记录: |