Python中Numpy mat的使用

前面介绍过用dnarray来模拟,但mat更符合矩阵,这里的mat与Matlab中的很相似。(mat与matrix等同)

基本操作

复制代码

>>> m= np.mat([1,2,3])  #创建矩阵
>>> m
matrix([[1, 2, 3]])

>>> m[0]                #取一行
matrix([[1, 2, 3]])
>>> m[0,1]              #第一行,第2个数据
2
>>> m[0][1]             #注意不能像数组那样取值了
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 305, in __getitem__
    out = N.ndarray.__getitem__(self, index)
IndexError: index 1 is out of bounds for axis 0 with size 1

#将Python的列表转换成NumPy的矩阵
>>> list=[1,2,3]
>>> mat(list)
matrix([[1, 2, 3]])

#Numpy dnarray转换成Numpy矩阵
>>> n = np.array([1,2,3])
>>> n
array([1, 2, 3])
>>> np.mat(n)
matrix([[1, 2, 3]])

#排序
>>> m=np.mat([[2,5,1],[4,6,2]])    #创建2行3列矩阵
>>> m
matrix([[2, 5, 1],
        [4, 6, 2]])
>>> m.sort()                    #对每一行进行排序
>>> m
matrix([[1, 2, 5],
        [2, 4, 6]])

>>> m.shape                     #获得矩阵的行列数
(2, 3)
>>> m.shape[0]                  #获得矩阵的行数
2
>>> m.shape[1]                  #获得矩阵的列数
3

#索引取值
>>> m[1,:]                      #取得第一行的所有元素
matrix([[2, 4, 6]])
>>> m[1,0:1]                    #第一行第0个元素,注意左闭右开
matrix([[2]])
>>> m[1,0:3]
matrix([[2, 4, 6]])
>>> m[1,0:2]
matrix([[2, 4]])

复制代码

 

矩阵求逆、行列式

与Numpy array相同,可参考链接

 

矩阵乘法

矩阵乘,与Numpy dnarray类似,可以使用np.dot()和np.matmul(),除此之外,由于matrix中重载了“*”,因此“*”也能用于矩阵乘。

复制代码

>>> a = np.mat([[1,2,3], [2,3,4]])
>>> b = np.mat([[1,2], [3,4], [5,6]])
>>> a
matrix([[1, 2, 3],
        [2, 3, 4]])
>>> b
matrix([[1, 2],
        [3, 4],
        [5, 6]])
>>> a * b         #方法一
matrix([[22, 28],
        [31, 40]])
>>> np.matmul(a, b)   #方法二
matrix([[22, 28],
        [31, 40]])
>>> np.dot(a, b)     #方法三
matrix([[22, 28],
        [31, 40]])

复制代码

点乘,只剩下multiply方法了。

>>> a = np.mat([[1,2], [3,4]])
>>> b = np.mat([[2,2], [3,3]])
>>> np.multiply(a, b)
matrix([[ 2,  4],
        [ 9, 12]])

 

矩阵转置

转置有两种方法:

复制代码

>>> a
matrix([[1, 2],
        [3, 4]])
>>> a.T           #方法一,ndarray也行
matrix([[1, 3],
        [2, 4]])
>>> np.transpose(a)   #方法二
matrix([[1, 3],
        [2, 4]])

复制代码

值得一提的是,matrix中求逆还有一种简便方法(ndarray中不行):

>>> a
matrix([[1, 2],
        [3, 4]])
>>> a.I
matrix([[-2. ,  1. ],
        [ 1.5, -0.5]])

 

 

参考链接:

1、https://blog.csdn.net/taoyanqi8932/article/details/52703686

2、https://blog.csdn.net/Asher117/article/details/82934857

3、https://blog.csdn.net/cqk0100/article/details/76221749

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章