Find elements of array one nearest to elements of array two

You can make few changes to extend it for an array of elements in value, like so –

idx = np.searchsorted(xx, yy, side="left").clip(max=xx.size-1)
mask = (idx > 0) &  \
       ( (idx == len(xx)) | (np.fabs(yy - xx[idx-1]) < np.fabs(yy - xx[idx])) )
out = xx[idx-mask]

Explanation

Nomenclature : array is the array in which we are looking to place elements from value to maintain the sorted nature of array.

Changes needed to extend the solution for a single element to many elements for searching :

1] Clip the indices array idx obtained from np.searchsorted at a max. of array.size-1, because for elements in value that are larger than the maximum of array, we need to make idx indexable by array.

2] Introduce numpy to replace math to do those operations in a vectorized manner.

3] Replace the conditional statement by the trick of idx - mask. In this case, internally Python would up-convert mask to an int array to match up with the datatype of idx. Thus, all the True elements become 1 and thus for True elements we would effectively have idx-1, which is the True case of the IF conditional statement in the original code.

Leave a Comment