sixtytrees
sixtytrees

Reputation: 1233

Find values corresponding to the minimum absolute difference of elements in a numpy array

I have an array of arrays of shape (n, m), as well as an array b of shape (m). I want to create an array c containing elements from a that are the closest to corresponding element of b. I can do it with this code:

a = [[11, 2, 9, 4, 5], [4, 4, 6, 1, -2]]
b = [1, 3, 12, 0, 0]
c = []

for inner in range(len(a[0])):
    min_distance = float('inf')
    best_index = 0
    for outer in range(len(a)):
        current_distance = abs(b[inner] - a[outer][inner])
        if min_distance > current_distance:
            min_distance = current_distance
            best_index = outer
    c.append(a[best_index][inner])

print(c)
# [4, 2, 9, 1, -2]

It doesnot matter which element to choose when two elements in a (e.i. a[0][1] and a[1][1]) are at equal distance, but on opposite sides of from an element in b (e.i. b[1]). How can I do this with numpy?

Upvotes: 0

Views: 27

Answers (1)

zuijiang
zuijiang

Reputation: 452

a = np.array(a)
b = np.array(b)
a[abs(a-b).argmin(0), np.arange(a.shape[1])]

Upvotes: 1

Related Questions