简体   繁体   中英

Avoid for loop using numpy vectors

I am creating x and y coordinates of a line at many different angles. How can I vectorise the following code, and avoid the need for a for loop?

# 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)

I think this is what you need:

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] changes mu into an array of shape (1000,1) which can be broadcast with v_2[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM