Skip to content

Instantly share code, notes, and snippets.

@smidm
Last active October 25, 2018 05:45
Show Gist options
  • Save smidm/08eafc84c526586c03cd21a2147b4f92 to your computer and use it in GitHub Desktop.
Save smidm/08eafc84c526586c03cd21a2147b4f92 to your computer and use it in GitHub Desktop.
find stable matching of minimal distance between two sets of points
import numpy as np
import scipy.optimize
a = np.array([[0, 0], [1, 1], [2, 2]])
b = np.array([[0, 1], [2, 2.2], [1, 1.2], [0, 0]])
indices = np.indices((len(a), len(b)))
# array([[[0, 0, 0, 0],
# [1, 1, 1, 1],
# [2, 2, 2, 2]],
#
# [[0, 1, 2, 3],
# [0, 1, 2, 3],
# [0, 1, 2, 3]]])
distance_matrix = np.vectorize(lambda i, j: np.linalg.norm(a[i] - b[j]))\
(*indices)
# array([[1. , 2.97, 1.56, 0. ],
# [1. , 1.56, 0.2 , 1.41],
# [2.24, 0.2 , 1.28, 2.83]])
ii, jj = scipy.optimize.linear_sum_assignment(distance_matrix)
# (array([0, 1, 2]), array([3, 2, 1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment