Pythonでクラスベースの行列クラスを実装する
クラスベースの行列クラスを作成します。このクラスは、行列の初期化、行列の加算、行列の乗算、および行列の転置操作をサポートします。このクラスは、Pythonでクラスを使用してデータと操作をカプセル化する方法を理解するのに役立ちます。
サンプル
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 __add__(self, other):
if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrices must have the same dimensions for addition.")
result = [[self.data[i][j] + other.data[i][j] for j in range(self.cols)] for i in range(self.rows)]
return Matrix(result)
def __mul__(self, other):
if self.cols != other.rows:
raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix.")
result = [[sum(self.data[i][k] * other.data[k][j] for k in range(self.cols)) for j in range(other.cols)] for i in range(self.rows)]
return Matrix(result)
def transpose(self):
result = [[self.data[j][i] for j in range(self.rows)] for i in range(self.cols)]
return Matrix(result)
def __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 使用例
m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)
print("Matrix 1 + Matrix 2:")
print(m1 + m2)
print("Matrix 1 * Matrix 2:")
print(m1 * m2)
print("Transpose of Matrix 1:")
print(m1.transpose())
def __init__(self, data):
self.data = data
self.rows = len(data)
self.cols = len(data[0]) if self.rows > 0 else 0
def __add__(self, other):
if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrices must have the same dimensions for addition.")
result = [[self.data[i][j] + other.data[i][j] for j in range(self.cols)] for i in range(self.rows)]
return Matrix(result)
def __mul__(self, other):
if self.cols != other.rows:
raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix.")
result = [[sum(self.data[i][k] * other.data[k][j] for k in range(self.cols)) for j in range(other.cols)] for i in range(self.rows)]
return Matrix(result)
def transpose(self):
result = [[self.data[j][i] for j in range(self.rows)] for i in range(self.cols)]
return Matrix(result)
def __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 使用例
m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)
print("Matrix 1 + Matrix 2:")
print(m1 + m2)
print("Matrix 1 * Matrix 2:")
print(m1 * m2)
print("Transpose of Matrix 1:")
print(m1.transpose())
コード解析:
__init__メソッドは行列オブジェクトを初期化するために使用され、2次元リストを引数として受け取り、行列の行数と列数を計算します。__add__メソッドは行列の加算操作を実装し、まず2つの行列の次元が同じかどうかをチェックし、次に要素ごとに加算して、新しい行列オブジェクトを返します。__mul__メソッドは行列の乗算操作を実装し、まず最初の行列の列数が2番目の行列の行数と等しいかどうかをチェックし、次に行列乗算を実行して、新しい行列オブジェクトを返します。transposeメソッドは行列の転置操作を実装し、新しい転置行列オブジェクトを返します。__str__メソッドは行列オブジェクトを文字列形式に変換して、印刷出力を容易にするために使用されます。
出力結果:
Matrix 1: 1 2 3 4 Matrix 2: 5 6 7 8 Matrix 1 + Matrix 2: 6 8 10 12 Matrix 1 * Matrix 2: 19 22 43 50 Transpose of Matrix 1: 1 3 2 4その他の拡張
Python3 サンプル