import sympy as sp
# 求determinant---行列式
matrix_A = sp.Matrix([[1, 2, 3], [4, 6, 8], [7, 3, 2]])
determinant = matrix_A.det()
# 求rref---行最简形
matrix_B = sp.Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])
rrefMatrix = matrix_B.rref()
# tuple的第二个元素是pivot Column
# 求零空间 Nullspace of a matrix.
# returns a list of column vectors that span the nullspace of the matrix.
matrix_C = sp.Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])
nullSpace = matrix_C.nullspace()
# 求列空间 columnspace of a matrix.
# columnspace returns a list of column vectors that span the columnspace of the matrix.
matrix_D = sp.Matrix([[1, 1, 2], [2, 1, 3], [3, 1, 4]])
colSpace = matrix_D.columnspace()
# 求特征值 eigenvalues of a matrix.
# eigenvals returns a dictionary of eigenvalue: algebraic_multiplicity pairs (similar to the output of roots).
matrix_E = sp.Matrix([[3, -2, 4, -2], [5, 3, -3, -2],
[5, -2, 2, -2], [5, -2, -3, 3]])
matrix_E.eigenvals()
注意: matrix_E.eigenvals() 返回值为字典,其中键是特征值,值是特征值出现的个数
# 求特征向量 the eigenvectors of a matrix.
# eigenvects returns a list of tuples of the form (eigenvalue, algebraic_multiplicity, [eigenvectors]).
matrix_E.eigenvects()
注意:返回值为元组数据结构,特征向量、特征值、特征值个数全部放在元组中。
# 矩阵的对角化 diagonalize a matrix
S,D=matrix_E.diagonalize()
注意: S是特征向量组成的矩阵,D是特征值在对角线上的对角矩阵
# 成本低的计算lamda
lamda = sp.symbols('lamda')
p = matrix_E.charpoly(lamda)
print(sp.factor(p.as_expr()))
返回值为:(lamda - 5)**2*(lamda - 3)*(lamda + 2),计算成本较低。



