亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實現(xiàn)矩陣運算的方法代碼實例

 更新時間:2023年08月23日 09:31:29   作者:「已注銷」  
這篇文章主要介紹了Python實現(xiàn)矩陣運算的方法代碼實例,想用python實現(xiàn)一個矩陣類,它可以像matlab或者numpy中的矩陣一樣進行運算,生成一個矩陣類Matrix之后,他接收一個二維列表作為輸入,然后將對應的值寫到矩陣對應的位置,需要的朋友可以參考下

Python實現(xiàn)矩陣運算

想用python實現(xiàn)一個矩陣類,它可以像matlab或者numpy中的矩陣一樣進行運算。

所以我考慮了如下幾點

  1. 生成一個矩陣類Matrix之后,他接收一個二維列表作為輸入,然后將對應的值寫到矩陣對應的位置上;如果輸入為空列表,就返回空矩陣;還要檢查矩陣形狀,如果形狀不是正常的矩陣就拋出異常。
  2. 一般在控制臺中輸入已經(jīng)創(chuàng)建好的矩陣A時,返回的是一個類,我想要向matlab那樣直接顯示矩陣形狀的話,就需要重寫方法__repr__()。
  3. 我還想要直接使用+、-、*來計算兩個矩陣的和,差,矩陣乘積,而不是使用A.add(B)這種麻煩的寫法,就需要使用運算符重載;
  4. 方陣的冪運算,可以采用矩陣快速冪的方法來計算,從而將其重寫冪運算方法__pow__()
  5. 矩陣轉(zhuǎn)置運算,矩陣平鋪展開。
  6. 生成元素全為0的矩陣,生成單位矩陣,生成元素全為1的矩陣。
  7. 其它。

不多說了,直接放代碼

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:
            # 采用列表推導式的辦法生成矩陣
            # 采用[[0] * other.col ] * self.row)]只是復制了第一個元素 self.row 遍,都是指向同一個內(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) 個位置的元素
        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) 個位置的元素
        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)

來看看測試

>>> 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]

還有一些方法,比如計算方陣的行列式,計算矩陣的特征值,特征向量啥的,等把計算方法中關(guān)于這些的算法搞明白了就可以寫了。

到此這篇關(guān)于Python實現(xiàn)矩陣運算的方法代碼實例的文章就介紹到這了,更多相關(guān)Python實現(xiàn)矩陣運算內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python 制作磁力搜索工具

    python 制作磁力搜索工具

    這篇文章主要介紹了如何用python 制作磁力搜索工具,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
    2021-03-03
  • Python 批量操作設(shè)備的實現(xiàn)步驟

    Python 批量操作設(shè)備的實現(xiàn)步驟

    本文將結(jié)合實例代碼,介紹Python 批量操作設(shè)備的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學習學習吧
    2021-07-07
  • python中的字典及嵌套遍歷

    python中的字典及嵌套遍歷

    這篇文章主要介紹了python中的字典及嵌套遍歷,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 使用Matplotlib制作動態(tài)圖的示例詳解

    使用Matplotlib制作動態(tài)圖的示例詳解

    matplotlib是一個著名的python繪圖庫,由于其靈活強大的繪圖功能使得在python中可視化變得非常容易,本文主要介紹了在matplotlib庫中制作動態(tài)圖的方法,需要的可以參考一下
    2023-06-06
  • Python中將語音轉(zhuǎn)換為文本的實現(xiàn)方法

    Python中將語音轉(zhuǎn)換為文本的實現(xiàn)方法

    語音識別是計算機軟件識別口語中的單詞和短語并將其轉(zhuǎn)換為人類可讀文本的能力,在本教程中,您將學習如何使用SpeechRecognition 庫在 Python 中將語音轉(zhuǎn)換為文本,文中有相關(guān)的代碼供大家參考,需要的朋友可以參考下
    2024-01-01
  • Python Pandas 如何shuffle(打亂)數(shù)據(jù)

    Python Pandas 如何shuffle(打亂)數(shù)據(jù)

    這篇文章主要介紹了Python Pandas 如何shuffle(打亂)數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • Python文件及目錄操作實例詳解

    Python文件及目錄操作實例詳解

    這篇文章主要介紹了Python文件及目錄操作的方法,實例分析了Python中os模塊的使用技巧,需要的朋友可以參考下
    2015-06-06
  • python人工智能tensorflow常見損失函數(shù)LOSS匯總

    python人工智能tensorflow常見損失函數(shù)LOSS匯總

    這篇文章主要為大家介紹了python人工智能tensorflowf常見損失函數(shù)LOSS匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • Django開發(fā)中復選框用法示例

    Django開發(fā)中復選框用法示例

    這篇文章主要介紹了Django開發(fā)中復選框用法,結(jié)合實例形式分析了Django基于ajax的復選框遍歷、提交及后臺數(shù)據(jù)庫查詢等相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • python分布式爬蟲中消息隊列知識點詳解

    python分布式爬蟲中消息隊列知識點詳解

    在本篇文章里小編給大家整理的是python分布式爬蟲中消息隊列知識點詳解內(nèi)容,有興趣的朋友們可以參考下。
    2020-11-11

最新評論