使矩阵对称 [英] Make a matrix symmetric
问题描述
我有一个矩阵,根据理论应该是对称的,但是在我的数据中可能不会被视为对称的.我想通过使用两个比较的单元格中的最大值来使它对称.
I have a matrix that should be symmetric according to theory, but might not be observed as symmetric in my data. I would like to force this to be symmetric by using the maximum of the two compared cells.
test_matrix <- matrix(c(0,1,2,1,0,1,1.5,1,0), nrow = 3)
test_matrix
#> [,1] [,2] [,3]
#>[1,] 0 1 1.5
#>[2,] 1 0 1.0
#>[3,] 2 1 0.0
使用双循环执行此操作很容易.
It's easy enough to do this with a double loop.
for(i in 1:3){
for(j in 1:3){
test_matrix[i, j] <- max(test_matrix[i, j], test_matrix[j, i])
}
}
test_matrix
#> [,1] [,2] [,3]
#> [1,] 0 1 2
#> [2,] 1 0 1
#> [3,] 2 1 0
但是我的矩阵大于$ 3x3 $,R的循环问题已得到充分证明.我也对使我的代码尽可能整洁感兴趣.实际上,我考虑过将其放在代码高尔夫上,但这是一个真正的问题,我认为其他人可能对此感兴趣.
But my matrix is larger than $3x3$, and R's problems with loops are well-documented. I'm also interested in making my code as clean as possible. In fact, I considered putting this on code golf, but this is a real problem that I think others might be interested in.
我见过这以及
I've seen this one as well as this one, but mine is different in that those op's seemed to actually have a symmetric matrix that just needed reordering, and I have a matrix that I need to change to be symmetric.
推荐答案
您可以使用pmax()
,它返回一对向量的逐元素最大值.
You could use pmax()
, which returns the element-wise maxima of a pair of vectors.
pmax(test_matrix, t(test_matrix))
# [,1] [,2] [,3]
# [1,] 0 1 2
# [2,] 1 0 1
# [3,] 2 1 0
它将与一对矩阵一起使用,因为在这里,因为:(1)在R中,矩阵是具有(维)属性的正好"向量; (2)用于实现pmax()
的代码足以将其第一个参数的属性重新附加到它返回的值上.
It'll work with a pair of matrices, as here, because: (1) in R, matrices are 'just' vectors with attached (dimension) attributes; and (2) the code used to implement pmax()
is nice enough to reattach the attributes of it's first argument to the value that it returns.
这篇关于使矩阵对称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!