创建对称矩阵(numpy)

对称(实对称)矩阵也即:XT=X

step 1:创建一个方阵

>>> import numpy as np
>>> X = np.random.rand(5**2).reshape(5, 5)
>>> X
array([[ 0.26984148,  0.25408384,  0.12428487,  0.0194565 ,  0.91287708],
       [ 0.31837673,  0.35493156,  0.74336268,  0.31810561,  0.04409245],
       [ 0.06644445,  0.8967897 ,  0.10990936,  0.05036292,  0.72581982],
       [ 0.94758512,  0.21375975,  0.36781736,  0.1633904 ,  0.36070709],
       [ 0.53263787,  0.18380491,  0.0225521 ,  0.91239367,  0.75521585]])

step 2:保留其上三角部分

>>> X = np.triu(X)
                                # 保留其上三角部分
>>> X
array([[ 0.26984148,  0.25408384,  0.12428487,  0.0194565 ,  0.91287708],
       [ 0.        ,  0.35493156,  0.74336268,  0.31810561,  0.04409245],
       [ 0.        ,  0.        ,  0.10990936,  0.05036292,  0.72581982],
       [ 0.        ,  0.        ,  0.        ,  0.1633904 ,  0.36070709],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.75521585]])    

step 3:将上三角”拷贝”到下三角部分

>>> X += X.T - np.diag(X.diagonal())
>>> X
array([[ 0.26984148,  0.25408384,  0.12428487,  0.0194565 ,  0.91287708],
       [ 0.25408384,  0.35493156,  0.74336268,  0.31810561,  0.04409245],
       [ 0.12428487,  0.74336268,  0.10990936,  0.05036292,  0.72581982],
       [ 0.0194565 ,  0.31810561,  0.05036292,  0.1633904 ,  0.36070709],
       [ 0.91287708,  0.04409245,  0.72581982,  0.36070709,  0.75521585]])

注意,要减去一次对角线上的元素。因为上三角cov,和下三角cov.T在进行相加时会把主对角线上的元素相加两次。

step 4:测试

>>> X.T == X
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

你可能感兴趣的:(python)