Python でクラスを作成し、カスタムメソッドで行列乗算を実行する

Document 对象参考手册Python3 実例

次の名前のクラスを作成します。Matrixそのクラスにはカスタムメソッドが含まれています。multiply行列乗算を実行するために使用されます。行列乗算では、最初の行列の列数が2番目の行列の行数と等しい必要があります。

実例

class Matrix:
    def __init__(self, data):
        self.data = data
        self.rows = len(data)
        self.cols = len(data[0]) if self.rows > 0 else 0

    def multiply(self, other):
        if self.cols != other.rows:
            raise ValueError("The number of columns in the first matrix must be equal to the number of rows in the second matrix.")

        result = [[0 for _ in range(other.cols)] for _ in range(self.rows)]

        for i in range(self.rows):
            for j in range(other.cols):
                for k in range(self.cols):
                    result[i][j] += self.data[i][k] * other.data[k][j]

        return Matrix(result)

    def __str__(self):
        return 'n'.join([' '.join(map(str, row)) for row in self.data])

# 使用例
matrix1 = Matrix([[1, 2, 3], [4, 5, 6]])
matrix2 = Matrix([[7, 8], [9, 10], [11, 12]])

result_matrix = matrix1.multiply(matrix2)
print(result_matrix)

コードの解説:

  1. __init__メソッドは行列オブジェクトを初期化し、2次元リストを受け取ります。dataをパラメータとして、行列の行数と列数を計算します。
  2. multiplyメソッドは行列乗算を実行します。まず、最初の行列の列数が2番目の行列の行数と等しいかどうかを確認し、等しくない場合は例外をスローします。次に、結果の行列を作成し、三重ループを使用して各要素の値を計算します。
  3. __str__メソッドは行列オブジェクトを文字列形式に変換し、出力を簡単にするために使用されます。
  4. 例では2つの行列を作成しました。matrix1とmatrix2そして、呼び出します。multiplyメソッドを使用して行列乗算を実行し、最後に結果を出力します。

出力結果:

58 64
139 154

Document 对象参考手册Python3 実例

その他の拡張