Find the closest values of an array

Recently, I face a quite simple problem : I have an array A (100,200) containing values I want to interpolate and I have another array I (5000), containing interpolated values. How to efficiently find tthe closest interpolated values of rach elements of A in I ?
That post give me 90% of the answer. It details how to efficiently find the index of a single value v  into an array arr. The one line magic formula is :

idx = (np.abs(arr - v)).argmin()

but here v is a number and arr is a 1 dimensional array. How my problem can fit in that solution ?

By using broadcasting of course !

I must find for each dimensions of my array the one which fits the values of I. So the solution of my problem is :

idx = (np.abs(A - I[:,None,None])).argmin(axis=0)

Hence idx is idx.shape == A.shape, and it contains indexes where I has the closest values of A.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s