国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python中Numpy mat的使用詳解

2020-02-15 21:30:46
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

前面介紹過(guò)用dnarray來(lái)模擬,但mat更符合矩陣,這里的mat與Matlab中的很相似。(mat與matrix等同)

基本操作

>>> m= np.mat([1,2,3]) #創(chuàng)建矩陣>>> mmatrix([[1, 2, 3]])>>> m[0]        #取一行matrix([[1, 2, 3]])>>> m[0,1]       #第一行,第2個(gè)數(shù)據(jù)2>>> m[0][1]       #注意不能像數(shù)組那樣取值了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的列表轉(zhuǎn)換成NumPy的矩陣>>> list=[1,2,3]>>> mat(list)matrix([[1, 2, 3]])#Numpy dnarray轉(zhuǎn)換成Numpy矩陣>>> n = np.array([1,2,3])>>> narray([1, 2, 3])>>> np.mat(n)matrix([[1, 2, 3]])#排序>>> m=np.mat([[2,5,1],[4,6,2]])  #創(chuàng)建2行3列矩陣>>> mmatrix([[2, 5, 1],    [4, 6, 2]])>>> m.sort()          #對(duì)每一行進(jìn)行排序>>> mmatrix([[1, 2, 5],    [2, 4, 6]])>>> m.shape           #獲得矩陣的行列數(shù)(2, 3)>>> m.shape[0]         #獲得矩陣的行數(shù)2>>> m.shape[1]         #獲得矩陣的列數(shù)3#索引取值>>> m[1,:]           #取得第一行的所有元素matrix([[2, 4, 6]])>>> m[1,0:1]          #第一行第0個(gè)元素,注意左閉右開(kāi)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]])>>> amatrix([[1, 2, 3],    [2, 3, 4]])>>> bmatrix([[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]])

點(diǎn)乘,只剩下multiply方法了。

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

矩陣轉(zhuǎn)置

轉(zhuǎn)置有兩種方法:

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

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

>>> amatrix([[1, 2],    [3, 4]])>>> a.Imatrix([[-2. , 1. ],    [ 1.5, -0.5]])            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 囊谦县| 响水县| 霍城县| 黔江区| 溧水县| 丽水市| 云南省| 宝兴县| 海阳市| 屏东市| 盐边县| 平度市| 湟中县| 卢湾区| 东安县| 乐清市| 巴里| 盘山县| 汝城县| 灌云县| 西充县| 凤庆县| 潼关县| 萨嘎县| 囊谦县| 浙江省| 鹰潭市| 乌鲁木齐县| 伊宁县| 灌南县| 梁山县| 凉城县| 泌阳县| 宕昌县| 太仓市| 遂平县| 正镶白旗| 松江区| 永胜县| 肇源县| 彰化县|