围绕另一个点旋转一组2D点

时间:2018-11-28 12:09:25

标签: python python-3.x

我想围绕给定点旋转坐标数组。要意识到我通过使用for循环来旋转每个坐标并将旋转后的坐标放回数组中。执行代码时,我得到IndexError: index 1 is out of bounds for axis 0 with size 1,所以循环中肯定有一个我无法识别的错误。

import math
import numpy as np

airfoil = np.array([[3349.67075, 2138.     ],
       [3225.86375, 2137.77425],
       [3060.79325, 2137.757  ],
       [2901.63575, 2136.89675],
       [2803.16825, 2136.89   ],
       [2728.33625, 2136.719  ],
       [2687.33225, 2136.89   ],
       [2611.475  , 2136.377  ],
       [2600.     , 2138.     ],
       [2602.24925, 2146.457  ],
       [2605.66625, 2152.2665 ],
       [2611.475  , 2158.7585 ],
       [2618.65025, 2164.39625],
       [2638.12775, 2176.0145 ],
       [2680.49825, 2193.95375],
       [2725.0895 , 2208.134  ],
       [2786.08325, 2220.2645 ],
       [2853.398  , 2227.61075]])


theta = 1.5708  # 90 degree
ox, oy = 2000, 2000  # point to rotate about

for i in range(airfoil.shape[0]-1):
    qx = ox + math.cos(theta) * (airfoil[i][0] - ox) - math.sin(theta) * 
        (airfoil[i][1] - oy)
    qy = oy + math.sin(theta) * (airfoil[i][0] - ox) + math.cos(theta) * 
        (airfoil[i][1] - oy)
    airfoil = np.column_stack((qx, qy))

可以使用airfoil[0][0]airfoil[0][1]airfoil[17][0]airfoil[17][1]调用元素(x和y坐标)而没有任何问题。所以错误一定在其他地方。

我已经读过类似的问题,这些问题对我没有帮助。

2 个答案:

答案 0 :(得分:1)

在循环中包含airfoil = np.column_stack((qx, qy))并不是一个好主意,因为它在每次迭代时都会修改airfoil数组。实际上,通过进行numpy.column_stack,您可以使机翼在第一次迭代后具有形状(1,2),而覆盖具有形状airfoil的原始(18,2)(因此,在第二次迭代中,它会为您提供形状错误)。

将旋转点存储在另一个变量中会更好。甚至更好的是,使用简单的A v = w一次执行旋转,其中A是您的旋转矩阵,v是您的机翼坐标,而w是旋转的坐标。

您可以使用旋转矩阵A

theta = 1.5708  # 90 degree
ox, oy = 2000, 2000  # point to rotate about
A = np.matrix([[np.cos(theta), -np.sin(theta)],
               [np.sin(theta), np.cos(theta)]])

w = np.zeros(airfoil.shape)
airfoil_shifted = airfoil-np.array([ox,oy])
for i,v in enumerate(airfoil_shifted):
  w[i] = A @ v

其中w将包含旋转的坐标。

答案 1 :(得分:0)

我修改了代码,现在可以使用了。

theta = 1.5708
ox, oy = 2000, 2000

qx = []
qy = []

for i in range(airfoil.shape[0]):
    qx.append(ox + math.cos(theta) * (airfoil[i][0] - ox) - math.sin(theta) * (airfoil[i][1] - oy))
    qy.append(oy + math.sin(theta) * (airfoil[i][0] - ox) + math.cos(theta) * (airfoil[i][1] - oy))

airfoil = np.column_stack((qx, qy))

尽管如此,我同意使用矩阵乘法比我的解决方案更为优雅。谢谢!