当学习完矩阵的定义以后,我们来学习矩阵的基本运算,与基本性质
矩阵的基本运算:矩阵的加法,每一个对应元素相加,对应结果的矩阵
例子:矩阵A和矩阵B表示的是同学上学期和下学期的课程的成绩,两个矩阵相加就表示一学年科目成绩的总和
矩阵的数量乘法:一个数乘于一个矩阵
还是接着上面学生成绩的例子:
矩阵数量乘法可以理解为,求两学期学生科目成绩的平均分1/2(A+B),因为之前我们已经算出了一学年科目的成绩总和,现在只需要乘于二分之一就可以了。
矩阵的数量乘法还有一个几何的直观理解:
下图的矩阵P可以理解为3个行向量组成,这3个行向量表示的是二维平面坐标系中的一个点,就是表示一个三角形,矩阵的数量乘法2.P之后,这个三角形就缩放变大了
矩阵的基本运算性质
简单证明:k ⋅(A + B) = k ⋅ A + k ⋅ B(这都还用证????不过出于数学逻辑思维的严谨,还是需要证明的)
两个矩阵:
实现矩阵的基本运算
之前定义的向量类Vector:
import math
from ._globals import EPSILON
class Vector:
def __init__(self, lst):
self._values = list(lst)
@classmethod
def zero(cls, dim):
"""返回一个dim维的零向量"""
return cls([0] * dim)
def __add__(self, another):
"""向量加法,返回结果向量"""
assert len(self) == len(another), \
"Error in adding. Length of vectors must be same."
return Vector([a + b for a, b in zip(self, another)])
def __sub__(self, another):
"""向量减法,返回结果向量"""
assert len(self) == len(another), \
"Error in subtracting. Length of vectors must be same."
return Vector([a - b for a, b in zip(self, another)])
def norm(self):
"""返回向量的模"""
return math.sqrt(sum(e**2 for e in self))
def normalize(self):
"""返回向量的单位向量"""
if self.norm() < EPSILON:
raise ZeroDivisionError("Normalize error! norm is zero.")
return Vector(self._values) / self.norm()
def dot(self, another):
"""向量点乘,返回结果标量"""
assert len(self) == len(another), \
"Error in dot product. Length of vectors must be same."
return sum(a * b for a, b in zip(self, another))
def __mul__(self, k):
"""返回数量乘法的结果向量:self * k"""
return Vector([k * e for e in self])
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
def __iter__(self):
"""返回向量的迭代器"""
return self._values.__iter__()
def __getitem__(self, index):
"""取向量的第index个元素"""
return self._values[index]
def __len__(self):
"""返回向量长度(有多少个元素)"""
return len(self._values)
def __repr__(self):
return "Vector({})".format(self._values)
def __str__(self):
return "({})".format(", ".join(str(e) for e in self._values))
定义一个内部使用的文件_globals,用来存储全局使用的变量 EPSILON,用来判断精度用的
EPSILON = 1e-8
定义的矩阵类Matrix:
from .Vector import Vector
class Matrix:
def __init__(self, list2d):
self._values = [row[:] for row in list2d]
@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 subtracting. 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
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])
def __repr__(self):
return "Matrix({})".format(self._values)
__str__ = __repr__
测试代码:
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]))
matrix2 = Matrix([[5, 6], [7, 8]])
print(matrix2)
print("add: {}".format(matrix + matrix2))
print("subtract: {}".format(matrix - matrix2))
print("scalar-mul: {}".format(2 * matrix))
print("scalar-mul: {}".format(matrix * 2))
print("zero_2_3: {}".format(Matrix.zero(2, 3)))
python 矩阵除法_Python线性代数学习笔记——矩阵的基本运算和基本性质 实现矩阵的基本运算...