Home > Back-end >  How can I determine which element in a matrix is closest to a given point using numpy?
How can I determine which element in a matrix is closest to a given point using numpy?

Time:12-01

I have a matrix data of (x,y) coordinates which looks like this:

array([[3,4], [10,4], [1,3], [5,8]])

I want to write a piece of code that, given a numpy array with generic coordinates (x,y), finds the index of the row of the matrix which corresponds to the closest point to (x,y) (in terms of euclidean distance).

So far what I have done is :

point = np.asarray([x, y])
closest_pt_idx = np.argmin(np.linalg.norm(np.subtract(data, point), axis=1))

Which for some reason doesnt seem to work well. What am i doing wrong?

CodePudding user response:

There is probably a single-liner for this.

import numpy as np
data = np.array([[3,4],[10,4],[1,3],[5,8],[2,3]])
point = np.tile([2,3], (len(data),1))
closest_pt_idx = np.argmin(np.linalg.norm(data-point,axis=1))
print(np.linalg.norm(data-point,axis=1),closest_pt_idx)
  • Related