Python實(shí)現(xiàn)矩陣運(yùn)算的方法代碼實(shí)例
Python實(shí)現(xiàn)矩陣運(yùn)算
想用python實(shí)現(xiàn)一個(gè)矩陣類,它可以像matlab或者numpy中的矩陣一樣進(jìn)行運(yùn)算。
所以我考慮了如下幾點(diǎn)
- 生成一個(gè)矩陣類Matrix之后,他接收一個(gè)二維列表作為輸入,然后將對(duì)應(yīng)的值寫到矩陣對(duì)應(yīng)的位置上;如果輸入為空列表,就返回空矩陣;還要檢查矩陣形狀,如果形狀不是正常的矩陣就拋出異常。
- 一般在控制臺(tái)中輸入已經(jīng)創(chuàng)建好的矩陣A時(shí),返回的是一個(gè)類,我想要向matlab那樣直接顯示矩陣形狀的話,就需要重寫方法__repr__()。
- 我還想要直接使用
+、-、*
來計(jì)算兩個(gè)矩陣的和,差,矩陣乘積,而不是使用A.add(B)
這種麻煩的寫法,就需要使用運(yùn)算符重載; - 方陣的冪運(yùn)算,可以采用矩陣快速冪的方法來計(jì)算,從而將其重寫冪運(yùn)算方法
__pow__()
- 矩陣轉(zhuǎn)置運(yùn)算,矩陣平鋪展開。
- 生成元素全為0的矩陣,生成單位矩陣,生成元素全為1的矩陣。
- 其它。
不多說了,直接放代碼
class Matrix: """docstring for Matrix""" def __init__(self, elem: list): check = [len(item) for item in elem] if set(check) == {0}: self.elem = [] self.row = 0 self.col = 0 elif len(set(check)) == 1: self.elem = elem self.row = len(elem) self.col = len(elem[0]) elif len(set(check)) > 1: raise ValueError("The column of each row is not equal") def __repr__(self): mat = "" for item in self.elem: mat += str(item) mat += '\n' return str(mat) def __iter__(self): return iter(self.elem) def __add__(self, other): if (self.row != other.row) or (self.col != other.col): raise TypeError("The two matrix's shape is not equal") else: new = [[i + j for i, j in zip(A, B)] \ for A, B in zip(self.elem, other.elem)] return Matrix(new) def __mul__(self, other): if self.col != other.row: raise TypeError("The first column must be equal to the second row") else: # 采用列表推導(dǎo)式的辦法生成矩陣 # 采用[[0] * other.col ] * self.row)]只是復(fù)制了第一個(gè)元素 self.row 遍,都是指向同一個(gè)內(nèi)存地址 new = [[0] * other.col for i in range(self.row)] for i in range(self.row): for j in range(other.col): for k in range(self.col): new[i][j] += self.elem[i][k] * other.elem[k][j] return Matrix(new) def __sub__(self, other): if (self.row != other.row) or (self.col != other.col): raise TypeError("The two matrix's shape is not equal") else: new = [[i - j for i, j in zip(A, B)] \ for A, B in zip(self.elem, other.elem)] return Matrix(new) def __neg__(self): new = [[-i for i in ele] for ele in self.elem] return Matrix(new) def __pow__(self, power, modulo=None): # quick pow if not self.is_square(): raise TypeError("The matrix is not square matrix") else: new = eyes(self.row) A = Matrix(self.elem) while power: if power & 1: new = new * A power >>= 1 A = A * A return new def shape(self): # 獲得矩陣形狀 print((self.row, self.col)) def is_square(self): # 判斷是否是方陣 return self.row == self.col def getitem(self, i: int, j: int): # 獲得矩陣第 (i, j) 個(gè)位置的元素 i -= 1 j -= 1 if (i < 0) or (i > self.row) or (j < 0) or (j > self.col): raise IndexError("list index out of range") else: return self.elem[i][j] def setitem(self, i: int, j: int, value) -> None: # 修改矩陣第 (i, j) 個(gè)位置的元素 i -= 1 j -= 1 if (i < 0) or (i > self.row) or (j < 0) or (j > self.col): raise IndexError("list index out of range") else: self.elem[i][j] = value def T(self): # Transposition new = [[0] * self.row for i in range(self.col)] for i in range(self.row): for j in range(self.col): new[j][i] = self.elem[i][j] return Matrix(new) def tiling(self): new = [[x for y in self.elem for x in y]] return Matrix(new) def zeros(row: int, col: int) -> Matrix: new = [[0] * col for i in range(row)] return Matrix(new) def eyes(n: int) -> Matrix: new = [[0] * n for i in range(n)] for i in range(n): new[i][i] = 1 return Matrix(new) def ones(row: int, col: int) -> Matrix: new = [[1] * col for i in range(row)] return Matrix(new)
來看看測(cè)試
>>> A = Matrix([[1,2,3],[4,5,6],[7,8,9]]) >>> B = ones(3,3) >>> A Out[5]: [1, 2, 3] [4, 5, 6] [7, 8, 9] >>> B Out[6]: [1, 1, 1] [1, 1, 1] [1, 1, 1] >>> A + B Out[7]: [2, 3, 4] [5, 6, 7] [8, 9, 10] >>> A*B Out[8]: [6, 6, 6] [15, 15, 15] [24, 24, 24] >>> A**3 Out[9]: [468, 576, 684] [1062, 1305, 1548] [1656, 2034, 2412] >>> A.T() Out[10]: [1, 4, 7] [2, 5, 8] [3, 6, 9] >>> A.tiling() Out[11]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
還有一些方法,比如計(jì)算方陣的行列式,計(jì)算矩陣的特征值,特征向量啥的,等把計(jì)算方法中關(guān)于這些的算法搞明白了就可以寫了。
到此這篇關(guān)于Python實(shí)現(xiàn)矩陣運(yùn)算的方法代碼實(shí)例的文章就介紹到這了,更多相關(guān)Python實(shí)現(xiàn)矩陣運(yùn)算內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 批量操作設(shè)備的實(shí)現(xiàn)步驟
本文將結(jié)合實(shí)例代碼,介紹Python 批量操作設(shè)備的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07使用Matplotlib制作動(dòng)態(tài)圖的示例詳解
matplotlib是一個(gè)著名的python繪圖庫,由于其靈活強(qiáng)大的繪圖功能使得在python中可視化變得非常容易,本文主要介紹了在matplotlib庫中制作動(dòng)態(tài)圖的方法,需要的可以參考一下2023-06-06Python中將語音轉(zhuǎn)換為文本的實(shí)現(xiàn)方法
語音識(shí)別是計(jì)算機(jī)軟件識(shí)別口語中的單詞和短語并將其轉(zhuǎn)換為人類可讀文本的能力,在本教程中,您將學(xué)習(xí)如何使用SpeechRecognition 庫在 Python 中將語音轉(zhuǎn)換為文本,文中有相關(guān)的代碼供大家參考,需要的朋友可以參考下2024-01-01Python Pandas 如何shuffle(打亂)數(shù)據(jù)
這篇文章主要介紹了Python Pandas 如何shuffle(打亂)數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07python人工智能tensorflow常見損失函數(shù)LOSS匯總
這篇文章主要為大家介紹了python人工智能tensorflowf常見損失函數(shù)LOSS匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05python分布式爬蟲中消息隊(duì)列知識(shí)點(diǎn)詳解
在本篇文章里小編給大家整理的是python分布式爬蟲中消息隊(duì)列知識(shí)點(diǎn)詳解內(nèi)容,有興趣的朋友們可以參考下。2020-11-11