2

I have two arrays of points: list1 with list1.shape = [N, 3] and list2 with list2.shape = [M, 3]. Within N, M: the total number of point, (x, y, z) are 3 coordinates in 3D.

Now I want to check if each point of list1 is within a distance r with each point of list2. A nature way to do this is a for loop:

for i in range(N):
    for j in range(M):
        if (list1[i, 0] - list2[j, 0])**2 + (list1[i, 1] - list2[j, 1])**2 + (list1[i, 2] - list2[j, 2])**2 < r**2:
        ''' Return 1 if list1[i] is within list2[j] '''
            return True
        else:
        ''' Return 0 if list1[i] is not within list2[j] '''
            return False

But it's horribly slow. Could I do the more efficient way?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
user2863620
  • 635
  • 3
  • 10
  • 17

1 Answers1

1

You can use the outer operations to calculate the distance matrix without the for loops:

s = np.subtract.outer

d_matrix = s(list1[:,0], list2[:,0])**2
d_matrix += s(list1[:,1], list2[:,1])**2
d_matrix += s(list1[:,2], list2[:,2])**2

Where each line is the distance of point i about all points. To find out if point i is close to any point using your criterion:

a = np.zeros_like(list1[:,0])
a[np.any(d_matrix < r**2, axis=1)] = 1
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234