编程语言
首页 > 编程语言> > Python SymPy4:SymPy 线性代数

Python SymPy4:SymPy 线性代数

作者:互联网

1. 矩阵与行列式

1.1 定义矩阵

Matrix([行向量1, 行向量2, 行向量3...])

from sympy import *

mat = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(mat)

 1.2 矩阵运算

from sympy import *

mat1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
mat2 = Matrix([[10, 11, 12], [13, 14, 15], [16, 17, 19]])
print(mat1 + mat2)
print(mat1 - mat2)
print(mat1 * mat2)
print(mat1 * 2)
print(mat1 ** 2)
# 逆矩阵
print(mat1 ** -1)

输出:

Matrix([[11, 13, 15], [17, 19, 21], [23, 25, 29]])
Matrix([[-9, -9, -9], [-9, -9, -9], [-9, -9, -9]])
Matrix([[84, 90, 99], [201, 216, 237], [334, 359, 394]])
Matrix([[2, 4, 6], [8, 10, 12], [14, 16, 20]])
Matrix([[30, 36, 45], [66, 81, 102], [109, 134, 169]])
Matrix([[-2/3, -4/3, 1], [-2/3, 11/3, -2], [1, -2, 1]])

1.3 矩阵行和列相关操作

mat.shape 矩阵形状

mat.row(n) 取第n行

mat.col(n) 取第n列

mat.row_del(n) 删除第n行

mat.col_del(n) 删除第n列

mat.row_insert(n, 行向量) 在n行处插入1行

mat.col_insert(n, 列向量) 在n列处插入1列

from sympy import *

mat1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
print(mat1.shape)
print(mat1.row(0))
print(mat1.col(0))
print(mat1.row_del(0))
print(mat1.col_del(0))
mat1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
print(mat1.row_insert(0, Matrix([[1, 2, 3]])))
print(mat1.col_insert(0, Matrix([1, 2, 3])))

 1.4 矩阵操作

mat.T 转置矩阵

mat.adjugate() 伴随矩阵

mat.det() 行列式

mat.rank() 秩

from sympy import *

mat = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
print(mat.T)
print(mat.adjugate())
print(mat.det())
print(mat.rank())

 输出:

Matrix([[1, 4, 7], [2, 5, 8], [3, 6, 10]])
Matrix([[2, 4, -3], [2, -11, 6], [-3, 6, -3]])
-3
3

1.5 创建特殊矩阵

eye(n) n*n单位矩阵

zeros(m, n) 0矩阵

ones(m, n) 全1矩阵

diag(a, b, c...) 对角矩阵,参数可以是数、矩阵

2. 矩阵方程

linsolve(mat) 求增广矩阵对应的解/解集

from sympy import *

a = symbols("a")
mat = Matrix([[1, 2, 3], [4, 5, 7]])
print(linsolve(mat))
mat = Matrix([[1, 2, 3, 4], [4, 5, 7, 8]])
print(linsolve(mat))
mat = Matrix([[a, 2, 3, 4], [4, 5, a, 8]])
print(linsolve(mat))

输出:

FiniteSet((-1/3, 5/3))
FiniteSet((tau0/3 - 4/3, 8/3 - 5*tau0/3, tau0))
FiniteSet(((2*a*tau0 - 15*tau0 + 4)/(5*a - 8), (8*a - tau0*(a**2 - 12) - 16)/(5*a - 8), tau0))

3. 特征值、特征向量

mat.eigenvals() 特征值,返回值为字典{特征值1: 重数1, 特征值2: 重数2...}

mat.eigenvects() 特征值和特征向量

mat.diagonalize() 特征矩阵和相似对角阵

mat.charpoly() 特征多项式

from sympy import *

mat = Matrix([[-2, 1, 1], [0, 2, 0], [-4, 1, 3]])
print("特征值", mat.eigenvals())
print("特征向量", mat.eigenvects())
print("特征矩阵和对角阵", mat.diagonalize())
print("特征多项式", mat.charpoly())

输出:

特征值 {-1: 1, 2: 2}
特征向量 [(-1, 1, [Matrix([
[1],
[0],
[1]])]), (2, 2, [Matrix([
[1/4],
[  1],
[  0]]), Matrix([
[1/4],
[  0],
[  1]])])]
特征矩阵和相似对角阵 (Matrix([
[1, 1, 1],
[0, 4, 0],
[1, 0, 4]]), Matrix([
[-1, 0, 0],
[ 0, 2, 0],
[ 0, 0, 2]]))
特征多项式 PurePoly(lambda**3 - 3*lambda**2 + 4, lambda, domain='ZZ')

标签:mat,SymPy4,mat1,Python,矩阵,tau0,print,SymPy,Matrix
来源: https://blog.csdn.net/Amzmks/article/details/119217087