Using Array Arguments in NumPy and Using 2D Arrays

The goal is to compute the distance matrix between two sets of points ( set1 and set2 ), use argsort() to get the sorted indices and take() to retrieve the sorted array. I know that I can do sort() directly, but I need indexes for the next steps.

I use the conceptual indices discussed here. I was not able to use take() directly with the resulting index matrix, but adding the appropriate number to each row makes it work, because take() aligns the original array, making the elements of the second row with the index + = len (set2), the third index of the row + = 2 * len (set2), etc. (see below):

 dist = np.subtract.outer( set1[:,0], set2[:,0] )**2 dist += np.subtract.outer( set1[:,1], set2[:,1] )**2 dist += np.subtract.outer( set1[:,2], set2[:,2] )**2 a = np.argsort( dist, axis=1 ) a += np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30, 30, 30, 30, 30]]) s1 = np.sort(dist,axis=1) s2 = np.take(dist,a) np.nonzero((s1-s2)) == False #True # meaning that it works... 

The main question is: is there a direct way to use take() without summing these indices?

Data to play:

 set1 = np.array([[ 250., 0., 0.], [ 250., 0., 510.], [-250., 0., 0.], [-250., 0., 0.]]) set2 = np.array([[ 61.0, 243.1, 8.3], [ -43.6, 246.8, 8.4], [ 102.5, 228.8, 8.4], [ 69.5, 240.9, 8.4], [ 133.4, 212.2, 8.4], [ -52.3, 245.1, 8.4], [-125.8, 216.8, 8.5], [-154.9, 197.1, 8.6], [ 61.0, 243.1, 8.7], [ -26.2, 249.3, 8.7]]) 

Other related issues:

- Euclidean distance between points in two different Numpy arrays, not within

+4
source share
1 answer

I don't think there is a way to use np.take without going over to flat indexes. Since the sizes are likely to change, you better use np.ravel_multi_index to do this, doing something like this:

 a = np.argsort(dist, axis=1) a = np.ravel_multi_index((np.arange(dist.shape[0])[:, None], a), dims=dist.shape) 

Alternatively, you can use fancy indexing without using take :

 s2 = dist[np.arange(4)[:, None], a] 
+4
source

Source: https://habr.com/ru/post/1482052/


All Articles