mardi 3 octobre 2017

how to avoid repeating iteration in a for loop

I have two n(about 2000 to 10000)X3 arrays that the each row of the array represent a point with it's xy coordinate and the 3rd number is the value. I want to match the points of two array by the coordinate, i.e find pairs of points from the two arrays that are within certain distance from each other. I tried two really simple arrays and have this:

ps_gen=np.array([[1,2,3],[4,5,6],[7,8,9]])
a=np.shape(ps_gen)
print a[0]
ps_det=np.array([[1,2.5,100],[2,5,6],[7,8,10]])
print ps_det[1,2]
b=np.shape(ps_det)


ps_match=[]
for i in range(a[0]):
    for j in range(b[0]):
        if (np.absolute(ps_gen[i,0]-ps_det[j,0])<0.5 and np.absolute(ps_gen[i,1]-ps_det[j,1])<0.5):
            c=[ps_gen[i,2],ps_det[j,2]]
        ps_match.append(c)
print ps_match

I expected it to have [[3,100],[9,10]], but strangely, it give me [[3, 100], [3, 100], [3, 100], [3, 100], [3, 100], [3, 100], [3, 100], [3, 100], [9, 10]], as if it redundantly run the loop for many times

I also tried something like this:

ps_match=[]
for i, j in itertools.product(range(a[0]), range(b[0])):
    if (np.absolute(ps_gen[i,0]-ps_det[j,0])<1 and np.absolute(ps_gen[i,1]-ps_det[j,1])<1):
        c=[ps_gen[i,2],ps_det[j,2]]
    ps_match.append(c)

And it give me the same result.... I know I can cut off the same row by doing np.unique, but I feel quite confused why this happened, and why only [3,100] repeat many times but [9,10] doesn't.

Aucun commentaire:

Enregistrer un commentaire