1. 程式人生 > >Python中Numpy mat的使用

Python中Numpy mat的使用

操作 .html 索引 個數 code recent ges .com 基本操作

前面介紹過用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

Python中Numpy mat的使用