Python method to create symmetric matrix based on numpy module

黄舟
Release: 2017-10-12 10:55:51
Original
5267 people have browsed it

This article mainly introduces the method of creating symmetric matrices in Python, and analyzes the related operating skills of Python based on the numpy module to implement matrix operations in the form of examples. Friends in need can refer to the following

The examples in this article describe Python Methods for creating symmetric matrices. Share it with everyone for your reference, the details are as follows:

Symmetric (real symmetric) matrix is:

step 1: Create a square matrix


>>> 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]])
Copy after login

step 2: Keep its upper triangle part


>>> 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]])
Copy after login

step 3: "Copy" the upper triangle to the lower triangle


>>> 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]])
Copy after login

Note , subtract the elements on the diagonal once. Because the upper triangle cov and the lower triangle cov.T will add the elements on the main diagonal twice when adding.

step 4: Test


>>> 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)
Copy after login

The above is the detailed content of Python method to create symmetric matrix based on numpy module. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template