避免使用numpy向量进行循环

时间:2017-08-14 10:54:56

标签: python numpy vectorization

我在许多不同的角度创建一条线的x和y坐标。我如何矢量化以下代码,并避免需要for循环?

# set up vector line equation that goes through 180 deg
v_1 = np.array([0,0]) #step on vector
mu = np.linspace(0, 2.5, 1000)
angle_step = 100
theta = np.linspace(0, np.pi, angle_step) #180 deg range
v_2 = np.array([np.cos(theta), np.sin(theta)]) #gradient vector

for i in range(angle_step):
    # for every angle, generate x and y coordinates in +ve and -ve mu direction from centre
    x1, y1 = np.rint(v_1[0] + mu * v_2[:, i][0]).astype(int), np.rint(v_1[1] + mu * v_2[:, i][1]).astype(int)
    x2, y2 = np.rint(v_1[0] - mu * v_2[:, i][0]).astype(int), np.rint(v_1[1] - mu * v_2[:, i][1]).astype(int)

1 个答案:

答案 0 :(得分:0)

我认为这就是你所需要的:

x1, y1 = np.rint(v_1[0] + mu[:,None] * v_2[0]).astype(int), np.rint(v_1[1] + mu[:,None] * v_2[:, i][1]).astype(int)
x2, y2 = np.rint(v_1[0] - mu[:,None] * v_2[:, i][0]).astype(int), np.rint(v_1[1] - mu[:,None] * v_2[:, i][1]).astype(int)

mu[:,None]mu更改为形状(1000,1)的数组,可以使用v_2[0]进行广播。