4 矩阵 & 矩阵运算 & 在python中的实现 & 实现矩阵的乘法
程序员文章站
2022-03-05 20:28:43
...
创建 矩阵类文件 Matrix.py
创建 需要使用到的 矩阵函数功能
from.Vector import Vector
class Matrix:
def __init__(self,list2d):
self._values = [row[:]for row in list2d]
def row_vector(self,index):
'返回矩阵的第index个行向量'
return Vector(self._values[index])
def col_vector(self,index):
'返回矩阵的第index个列向量'
return Vector([row[index]] for row in self._values)
def __getitem__(self, pos):
'返回矩阵中pos位置的元素'
r,c = pos
return self._values[r][c]
def size(self):
'返回矩阵中元素的个数'
r,c = self.shape()
return r * c
def row_num(self):
'返回矩阵的行数'
return self.shape()[0]
__len__ = row_num
def col_num(self):
'返回矩阵的列数'
return self.shape()[1]
def shape(self):
'返回矩阵的形状:(行数,列数)'
return len(self._values), len(self._values[0]) # 返回第0个元素即知道了有几列
def __repr__(self):
return 'Matrix({})'.format(self._values)
__str__ = __repr__ # 返回同样的字符串,不再进行区分
与Vector相同,建立main_matrix.py文件去验证矩阵函数功能能否实现。
from playLA.Matrix import Matrix
if __name__ == '__main__':
matrix = Matrix([[1,2],[3,4]])
print(matrix)
print('matrix.shape = {}'.format(matrix.shape()))
print('matrix.size = {}'.format(matrix.size()))
print('len(matrix) = {}'.format(len(matrix)))
print('matrix[0][0] = {}'.format(matrix[0,0]))
# 输出结果为
Matrix([[1, 2], [3, 4]])
matrix.shape = (2, 2)
matrix.size = 4
len(matrix) = 2
matrix[0][0] = 1
加入矩阵基本运算函数
@classmethod
def zero(cls,r,c):
'返回一个r行c列的零矩阵'
return cls([[0] * c for _ in range (r)])
def __add__(self, another):
'返回两个矩阵的加法结果'
assert self.shape() == another.shape(), \
'Error in adding. Shape of matrix must be same'
return Matrix([[a + b for a,b in zip(self.row_vector(i),another.row_vector(i))]
for i in range(self.row_num())])
def __sub__(self, another):
'返回两个矩阵的减法结果'
assert self.shape() == another.shape(), \
'Error in adding. Shape of matrix must be same'
return Matrix([[a - b for a,b in zip(self.row_vector(i),another.row_vector(i))]
for i in range(self.row_num())])
def __mul__(self, k):
'返回矩阵的数量乘法结果: self * k'
return Matrix([[e * k for e in self.row_vector(i)]
for i in range(self.row_num())])
def __rmul__(self,k):
'返回矩阵的数量乘法结果:k * self'
return self * k
def __truediv__(self, k):
'返回矩阵的数量除法结果:self/k'
return (1/k) * self
def __pos__(self):
'返回矩阵取正结果'
return 1 * self
def __neg__(self):
'返回矩阵取负结果'
return -1 * self
验证函数功能
matrix2 = Matrix([[5,6],[7,8]])
print('add: {}'.format(matrix + matrix2))
print('subtract: {}'.format(matrix - matrix2))
print('scalar-mul: {}'.format(matrix * 2))
print('scalar-mul: {}'.format(2 * matrix))
print('zero_2_3: {}'.format(Matrix.zero(2,3)))
# 输出结果为
add: Matrix([[6, 8], [10, 12]])
subtract: Matrix([[-4, -4], [-4, -4]])
scalar-mul: Matrix([[2, 4], [6, 8]])
scalar-mul: Matrix([[2, 4], [6, 8]])
zero_2_3: Matrix([[0, 0, 0], [0, 0, 0]])
添加矩阵的乘法运算函数
def dot(self, another):
"""返回矩阵乘法的结果"""
if isinstance(another, Vector):
# 矩阵和向量的乘法
assert self.col_num() == len(another), \
"Error in Matrix-Vector Multiplication."
return Vector([self.row_vector(i).dot(another) for i in range(self.row_num())])
if isinstance(another, Matrix):
# 矩阵和矩阵的乘法
assert self.col_num() == another.row_num(), \
"Error in Matrix-Matrix Multiplication."
return Matrix([[self.row_vector(i).dot(another.col_vector(j)) for j in range(another.col_num())]
for i in range(self.row_num())])
验证函数
T = Matrix([[1.5, 0], [0, 2]])
p = Vector([5, 3])
print("T.dot(p) = {}".format(T.dot(p)))
P = Matrix([[0, 4, 5], [0, 0, 3]])
# print("T.dot(P) = {}".format(T.dot(P)))
# print("A.dot(B) = {}".format(matrix.dot(matrix2)))
# print("B.dot(A) = {}".format(matrix2.dot(matrix)))
下一篇: 音效更悦耳多媒体音箱摆放有门道