Python でクラスを使用して行列加算を計算するプログラム
Python のクラスを使用して、簡単な行列加算プログラムを実装します。行列加算では2つの行列の次元が同じである必要があるため、次のようなクラスを作成します。Matrixそのクラスの中に行列加算のメソッドを実装します。
サンプル
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 __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 使用例
matrix1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = Matrix([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result_matrix = matrix1 + matrix2
print(result_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 __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 使用例
matrix1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = Matrix([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result_matrix = matrix1 + matrix2
print(result_matrix)
コードの説明:
__init__メソッド:行列オブジェクトを初期化し、2次元リストを入力として受け取ります。dataそして、行列の行数と列数を計算します。__add__メソッド:行列加算を実装します。まず2つの行列の次元が同じかどうかを確認し、異なる場合はエラーを発生させます。次にリスト内包表記を使用して要素ごとに加算し、結果の行列を生成します。__str__メソッド:行列を文字列形式に変換し、出力を簡単にします。
出力結果:
10 10 10 10 10 10 10 10 10その他の拡張
Python3 サンプル