【发布时间】:2018-01-17 20:38:36
【问题描述】:
我知道 A'A 会给出一个对称的正定矩阵。但是如何在 R 中生成对称但不一定是正定的随机矩阵?
【问题讨论】:
-
@MrFlick 我知道如何编写 for 循环,但希望在 R 中实现矢量化
我知道 A'A 会给出一个对称的正定矩阵。但是如何在 R 中生成对称但不一定是正定的随机矩阵?
【问题讨论】:
细节当然取决于您希望矩阵元素具有什么样的分布,但是一旦确定了这一点,您就可以进行如下调整:
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
为了方便使用,你可以将这样的代码封装在一个函数中,如下所示:
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
【讨论】:
A[lower.tri(A)]=t(A)[upper.tri(A)] 而不是A[lower.tri(A)]=A[upper.tri(A)]。 (即在右侧将A 替换为t(A)。