Python implements a class-based matrix class
We will create a class-based matrix class that supports matrix initialization, matrix addition, matrix multiplication, and matrix transpose operations. This class will help us understand how to use classes in Python to encapsulate data and operations.
Example
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])
# Example usage
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])
# Example usage
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())
Code explanation:
__init__The method is used to initialize the matrix object, accepts a two-dimensional list as a parameter, and calculates the number of rows and columns of the matrix.__add__The method implements matrix addition. It first checks whether the dimensions of the two matrices are the same, then adds the elements one by one, and returns a new matrix object.__mul__The method implements matrix multiplication. It first checks whether the number of columns of the first matrix equals the number of rows of the second matrix, then performs the matrix multiplication operation, and returns a new matrix object.transposeThe method implements matrix transpose and returns a new transposed matrix object.__str__The method is used to convert the matrix object into a string form for easy print output.
Output result:
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 4Other extensions
Python3 Examples