0

I have a numpy array that I am using to complete a nearest neighbor calculation:

def all_distance_compute(matrix, vector):
    diff = matrix[0:] - matrix[vector]
    distances = np.sqrt(np.sum(diff**2, axis=1))

    for i in range(len(distances)):        
        print i
        print distances[i]
return  distances

It seems to be working based on the result distances that is returned, however, I don't know how to look at all of the values in distances and return which element in the array is the minimum.

The for loop that I have in my function is purely for diagnostics, but I was thinking I could iterate thru this way and perhaps determine the minimum this way, but I also figured numpy probably has a better means of doing this. EDIT: So as I was typing out the question, I figured I would try my suggestion of iterating to find the minimum, and I changed my function to be this: code

for i in range(len(distances)):
        if distances[i] < min and distances[i] > 0:
            min = distances[i]
            mindex = i

return  min, mindex
2
  • What is vector? Could you add a representative sample case? Commented May 11, 2017 at 16:24
  • See update above. Commented May 11, 2017 at 16:25

1 Answer 1

1

numpy.argsort will return you the array index sorted in ascending order.

For example:

In [1]: import numpy as np

In [2]: arr = np.array([5,3,8,2,1,9])

In [3]: np.argsort(arr)
Out [3]: array([4, 3, 1, 0, 2, 5])

In [4]: arr[np.argsort(arr)]
Out [4]: array([1, 2, 3, 5, 8, 9])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This also works. If I do np.argsort(distances) i get the same result as my mindex variable above.
Indeed. The numpy solution will be at least an order of magnitude faster though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.