Python3矩阵求最简⾏阶梯矩阵
由于在Python numpy库中没有直接对Matrix求RREF的⽅法,度娘了好久发现在另⼀个科学计算包sympy中可以利⽤A.rref()的⽅法对Matrix直接求RREF,但是有另⼀个问题,⼤家⼀般常⽤的是numpy,⽽sympy和numpy使⽤的是不同的数据类型,numpy中声明Matrix⼀般使⽤array(),sympy中声明Matrix则使⽤Matrix()⽅法,所以需要先将array()类型的矩阵转换为Matrix()类型求RREF,然后再转回array()类型。
1. sympy Matrix类型与numpy array类型的相互转换
array -> Matrix
直接使⽤sympy Matrix(np.array())⽅法构造⼀个matrix
Matrix -> array
查看了sympy官⽅⽂档其提供了两种Matrix convert to array的⽅法:
(1) sympy.matrices.dense.matrix2numpy(m, dtyp=<'class object'>)
- 其对于sympy Matrix类型返回⼀个numpy array类型
这⾥要注意的是不能忘了数据转换的对象类型type,如果没有指定类型那么会出现“未定义数据类型”的提⽰
(2) tolist()
- 其对于sympy Matrix类型返回⼀个嵌套的python列表
使⽤这种⽅法需要注意的是,若不加处理直接使⽤tolist()⽅法,其返回的数据类似于“列表的索引”,在Spyder中查看数据是这样的:
所以需要对数据进⾏处理,即通过np.list()).astype()操作将其转换为对应的numpy类型
2. 使⽤sympy库计算Matrix的最简⾏阶梯矩阵
sympy库中提供了rref()⽅法将Matrix通过初等⾏变换,转化为简化⾏阶梯矩阵。rref()将返回的是⼀个元组,包括两个值,第⼀个是简化⾏阶梯矩阵,第⼆个是主元位置的列表。注意:返回的元组第⼀个类型是Matrix,第⼆个是list
所以对于numpy array()的matrix求最简⾏阶梯矩阵,先转为symbol Matrix计算rref,再转回numpy类型
代码实现
# Python 3.7
from sympy import Matrix
from sympy.matrices import dense
# Matrix convert to array
A_mat = Matrix([[1, 2, 1, 1], [2, 1, -2, -2], [1, -1, -4, 3]]) A_arr1 = np.array(list()).astype(np.int32)
A_arr2 = dense.matrix2numpy(A_mat, dtype=np.int32)
spyder python下载
# array convert to Matrix
B_arr = np.array([[1, 2, 1, 1], [2, 1, -2, -2], [1, -1, -4, 3]]) B_mat = Matrix(B_arr)
# RREF
A_rref = np.f()[0].tolist()).astype(np.int32)
B_rref = (Matrix(B_arr).rref()[0].tolist()).astype(np.int32)