Search code examples
pythonvector

how to fit random vector into list of vectors python


say I have the following list of vectors

vectors=[(10,0),(-10,0),(0,10),(0,-10)]

and I have the following random vector:

vector=(200,-300)

how can I get the vector from the list that is the most similar to the vector that I am inputting in python?


Solution

  • You can use scipy.spatial to find nearest neighbor.

    Eg:

    import numpy as np
    from scipy import spatial
    
    vectors = np.array([(10, 0), (-10, 0), (0, 10), (0, -10)])
    tree = spatial.KDTree(vectors)
    
    vector = np.array([200, -300])
    
    distance, i = tree.query(vector)
    
    nearest = vectors[i]