【问题标题】:Transform rectangle with transformation matrix Python用变换矩阵Python变换矩形
【发布时间】:2020-11-27 09:14:08
【问题描述】:

我已经给出了以下矩形,我想将其转换(给定 ax 和 M)对应于转换矩阵 M。我的问题是矩阵“线”和“M”具有不同的维度。

lines = np.array([[-1, 1, 1, -1, -1], [-1, -1, 1, 1, -1]])
    
basis = np.array([[1, 0], [0, 1]]) 
    
# Transform lines and basis using M    
ax = M.dot(lines.T) # This is my attempt to transform the axis
    
    
ax.plot( lines[0,:], lines[1,:], '-', color="gray" )
ax.arrow( 0, 0, basis[0][0], basis[1][0], color='red', width=.04, length_includes_head=True )
ax.arrow( 0, 0, basis[0][1], basis[1][1], color='gold', width=.04, length_includes_head=True )

ax.set_xlim( -5, 5 )
ax.set_ylim( -5, 5 )
ax.grid()

我希望我已经足够清楚地指出了我的问题。

【问题讨论】:

    标签: python numpy matrix transpose


    【解决方案1】:

    您几乎完成了解决方案。这是您的代码,需要进行一些修复。

    from math import sin, cos
    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def get_rotation_2d(theta):
        """ Return 2D rotation matrix
        """
        R = np.array([
            [cos(theta), -sin(theta)],
            [sin(theta),  cos(theta)]
        ])
        return R
    
    
    # initial rectangle and basis
    lines = np.array([[-1, 1, 1, -1, -1], [-1, -1, 1, 1, -1]])
    basis = np.array([[1, 0], [0, 1]])
    
    # transformation
    M = get_rotation_2d(np.pi / 6)
    new_lines = M @ lines
    new_basis = M @ basis
    
    # plot results
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(new_lines[0, :], new_lines[1, :], '-', color='gray')
    ax.arrow( 0, 0, new_basis[0][0], new_basis[1][0], color='red', width=.04, length_includes_head=True )
    ax.arrow( 0, 0, new_basis[0][1], new_basis[1][1], color='gold', width=.04, length_includes_head=True )
    ax.set_xlim(-5, 5)
    ax.set_ylim(-5, 5)
    ax.grid()
    plt.show()
    

    我使用 Python 3.5+ matrix multiplication operator '@'。它使代码更清晰。

    结果是 transformed rectanlge

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多