Example of how to create a symmetric matrix using Python [numpy module] And pythonnumpy
This example describes how to create a symmetric matrix in Python. We will share this with you for your reference. The details are as follows:
The symmetric (Real Symmetric) matrix is also:
Step 1: Create a square matrix
>>> import numpy as np>>> X = np.random.rand(5**2).reshape(5, 5)>>> Xarray([[ 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: retain the upper triangle
>>> X = np. triu (X) # reserve the upper triangle of X> Xarray ([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: copy the top triangle to the bottom triangle
>>> X += X.T - np.diag(X.diagonal())>>> Xarray([[ 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]])
Note: subtract the element on the diagonal line. Because the upper trianglecov
, And lower trianglecov.T
In addition, the elements on the diagonal line of the primary node are added twice.
Step 4: Test
>>> X.T == Xarray([[ 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)