• 线性代数-Python-03:矩阵的变换 - 手写Matrix Transformation及numpy中的用法


    一、代码仓库

    https://github.com/Chufeng-Jiang/Python-Linear-Algebra-for-Beginner/tree/main

    二、旋转矩阵的推导及图形学中的矩阵变换

    2.1 让横坐标扩大a倍,纵坐标扩大b倍

    在这里插入图片描述

    2.2 关于x轴翻转

    在这里插入图片描述

    2.3 关于y轴翻转

    在这里插入图片描述

    2.4 关于原点翻转(x轴,y轴均翻转)

    在这里插入图片描述

    2.5 沿x方向错切

    在这里插入图片描述

    2.6 沿y方向错切

    在这里插入图片描述

    2.7 旋转

    theta = math.pi / 3
    T = Matrix([[math.cos(theta), math.sin(theta)], 
    	        [-math.sin(theta), math.cos(theta)]])
    
    • 1
    • 2
    • 3

    在这里插入图片描述在这里插入图片描述

    2.8 单位矩阵

    在这里插入图片描述

    2.9 矩阵的逆

    在这里插入图片描述

    三、看待矩阵的关键视角:用矩阵表示空间

    3.1 行视角

    在这里插入图片描述

    3.2 列视角

    在这里插入图片描述

    3.3 标准单位向量和列视角

    在这里插入图片描述

    3.4 矩阵表示空间

    在这里插入图片描述

    四、代码

    matrix.py

    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)])
    
        @classmethod
        def identity(cls, n):
            """返回一个n行n列的单位矩阵"""
            m = [[0]*n for _ in range(n)]
            for i in range(n):
                m[i][i] = 1;
            return cls(m)
    
        def T(self):
            """返回矩阵的转置矩阵"""
            return Matrix([[e for e in self.col_vector(i)]
                           for i in range(self.col_num())])
    
        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 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())])
    
        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__
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112

    matrix_transformation

    import matplotlib.pyplot as plt
    from playLA.Matrix import Matrix
    from playLA.Vector import Vector
    import math
    
    
    if __name__ == "__main__":
    
        points = [[0, 0], [0, 5], [3, 5], [3, 4], [1, 4], [1, 3], [2, 3], [2, 2], [1, 2], [1, 0]]
        x = [point[0] for point in points]
        y = [point[1] for point in points]
    
        plt.figure(figsize=(5, 5))
        plt.xlim(-10, 10)
        plt.ylim(-10, 10)
        plt.plot(x, y)
        # plt.show()
    
        P = Matrix(points)
    
        # T = Matrix([[2, 0], [0, 1.5]])
        # T = Matrix([[1, 0], [0, -1]])
        # T = Matrix([[-1, 0], [0, 1]])
        # T = Matrix([[-1, 0], [0, -1]])
        # T = Matrix([[1, 0.5], [0, 1]])
        # T = Matrix([[1, 0], [0.5, 1]])
    
        theta = math.pi / 3
        T = Matrix([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])
    
        # 逆时针旋转90度
        # theta = math.pi / -2
        # T = Matrix([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])
    
        # 根据矩阵表示空间的法则,直接写出的逆时针旋转90度的变换矩阵
        #T = Matrix([[0, -1], [1, 0]])
    
        P2 = T.dot(P.T())
        plt.plot([P2.col_vector(i)[0] for i in range(P2.col_num())],
                 [P2.col_vector(i)[1] for i in range(P2.col_num())])
        plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述

    numpy_matrix.py

    import numpy as np
    
    if __name__ == "__main__":
    
        # 矩阵的创建
        A = np.array([[1, 2], [3, 4]])
        print(A)
    
        # 矩阵的属性
        print(A.shape)
        print(A.T)
    
        # 获取矩阵的元素
        print(A[1, 1])
        print(A[0])
        print(A[:, 0])
        print(A[1, :])
    
        # 矩阵的基本运算
        B = np.array([[5, 6], [7, 8]])
        print(A + B)
        print(A - B)
        print(10 * A)
        print(A * 10)
        print(A * B)
        print(A.dot(B))
    
        p = np.array([10, 100])
        print(A + p)
        print(A + 1)
    
        print(A.dot(p))
    
        # 单位矩阵
        I = np.identity(2)
        print(I)
        print(A.dot(I))
        print(I.dot(A))
    
        # 逆矩阵
        invA = np.linalg.inv(A)
        print(invA)
        print(invA.dot(A))
        print(A.dot(invA))
    
        # C = np.array([[1, 2, 3], [4, 5, 6]])
        # np.linalg.inv(C)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    在这里插入图片描述

  • 相关阅读:
    Latex双栏文章
    安全扫描项目
    【408数据结构与算法】—排序(十四)
    2023年节假日JSON
    扒一扒Nacos、OpenFeign、Ribbon、loadbalancer组件协调工作的原理
    ASP.NET Core - 入口文件
    Go Web——Gin简介
    客如云×OceanBase:分布式云升级助力客如云降本增效
    openjudge 1.5.23 药房管理
    2022六边形JAVA面试八股文分享,我这一拳20年的功力你接得住吗?
  • 原文地址:https://blog.csdn.net/jiangchufeng123/article/details/133956925