Python中Numpy mat的使用

前面介紹過用dnarray來模擬,但mat更符合矩陣,這裏的mat與Matlab中的很類似。(mat與matrix等同)html

基本操做

>>> 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相同,可參考連接python

 

矩陣乘法

矩陣乘,與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方法了。python2.7

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

 

矩陣轉置

轉置有兩種方法:spa

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

值得一提的是,matrix中求逆還有一種簡便方法(ndarray中不行):.net

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

 

 

參考連接:code

一、http://www.javashuo.com/article/p-nlbxmqpd-kw.htmlhtm

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

三、https://blog.csdn.net/cqk0100/article/details/76221749排序

相關文章
相關標籤/搜索