-1

I've seen many of the posts on how to get closes value in a numpy array, how to get closest coordinate in a 2D array etc. But none of them seem to solve what I am looking for.

The problem is, I have a 2D numpy array as such:

[[77.62881735 12.91172607]          
 [77.6464534  12.9230648]
 [77.65330961 12.92020244]
 [77.63142413 12.90909731]]

And I have one numpy array like this:

[77.64000112 12.91602265]

Now I want to find a coordinate in the 2D numpy array that is closest to the co-ordinates in 1D array.

That said, I am a beginner in these stuffs..So any input is appreciated.

Sudhanwa
  • 3
  • 2
  • 1
    You need to define what you mean by *closest*. Also add the expected output and anything you have tried so far – Dani Mesejo Jul 22 '22 at 09:01
  • Does this answer your question? [Finding index of nearest point in numpy arrays of x and y coordinates](https://stackoverflow.com/questions/10818546/finding-index-of-nearest-point-in-numpy-arrays-of-x-and-y-coordinates) – Michael Szczesny Jul 22 '22 at 09:02
  • @DaniMesejo well, in this case my expected output would be like: [77.65330961 12.92020244].. which seems the closest – Sudhanwa Jul 22 '22 at 09:35
  • @MichaelSzczesny No, I'v tried implementing but not the answer I am expecting – Sudhanwa Jul 22 '22 at 09:38

2 Answers2

1

I assume you mean euclidean distance. Try this:

a = np.array([[77.62881735, 12.91172607],          
              [77.6464534,  12.9230648],
 [77.65330961,12.92020244],
 [77.63142413 ,12.90909731]])

b = np.array([77.64000112, 12.91602265])

idx_min = np.sum( (a-b)**2, axis=1, keepdims=True).argmin(axis=0)
idx_min, a[idx_min]

Output:

(array([1], dtype=int64), array([[77.6464534, 12.9230648]]))
bpfrd
  • 945
  • 3
  • 11
  • Hi.. this example seems to provide solution to my problem.. would you explain what ***idx_min = np.sum( (a-b)**2, axis=1, keepdims=True).argmin(axis=0)*** this does exactly please – Sudhanwa Jul 22 '22 at 09:41
  • `np.sum((a-b)**2, axis=1, keepdims=True)` calculates the distance between coordinates in a from b. `argmin(axis=0)` finds the index of the minimum distance. You can get the coordinate of closest point then by `a[idx_min]` – bpfrd Jul 22 '22 at 09:47
0

You need to implement your own "distance" computing function.
My example implements Euclidean Distance for simple

import numpy as np
import math

def compute_distance(coord1, coord2):
    return math.sqrt(pow(coord1[0] - coord2[0], 2) + pow(coord1[1] - coord2[1], 2))

gallery = np.asarray([[77.62881735, 12.91172607],          
    [77.6464534, 12.9230648],
    [77.65330961, 12.92020244],
    [77.63142413, 12.90909731]])

query = np.asarray([77.64000112, 12.91602265])

distances = [compute_distance(i, query) for i in gallery]
min_coord = gallery[np.argmin(distances)]
AnhPC03
  • 622
  • 5
  • 15