FInd a corner values in 2D array

Viewed 80

I have a randomly distributed points inside the ((0,1), (0,1)) domain. I need to find the corner values. (min along 0 axis, min along 1 axis) (max along 0 axis, min along 1 axis) (max along 0 axis, max along 1 axis) (min along 0 axis, max along 1 axis) The problem is in the simultanuosly searching the min/max values along the 2 axes. How to realize this simulataneous search in numpy?

import numpy as np    
np.random.seed(42)
points = np.random.random((100,2))   
1 Answers

You could use the Euclidean distance to find the closest point. Which is eqivalent to finding the length of the vector from the corner to that point. For (0,0) it's trivial:

points[np.argmin(np.sum(np.square(points), axis=1)), :]

For the other corners you need to find the vector between them first, e.g. for (0,1):

points[np.argmin(np.sum(np.square(points - [0, 1]), axis=1)), :]

What this line does is first compute the vectors points - [0, 1] and then squares both values in that vector. It then sums across each row, finds the argument or index, of the smallest value using np.argmin and uses this to re-index the original points array to extract the point co-ords.

N.B. The true Euclidean distance would also take the square root of the sum of the squares, but since we're just looking for the smallest, we don't need to take that step.

Related