[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Need Help with Distance Algorithm in Numeric



Magnus Lie Hetland wrote:
...
print second[argmin(dist(first, second[..., NewAxis]), 0)]


Thanks so much for your help. I'm trying to get it running in Python 2.3, but I'm getting the following error:


>>>
Traceback (most recent call last):
File "C:/Documents and Settings/Administrator/Desktop/numarray distance.py", line 27, in ?
print second[Numeric.argmin(dist(first, second[..., Numeric.NewAxis]), 0)]
IndexError: invalid index
>>>


Here's the code that I've modified, trying to get it to work in Numeric:

#-----------------------------------------------------------

import Numeric

# Your distance function, for measuring how similar two RGB triples
# are. I'm just using plain ol' Euclidean distance here. Note that it
# returns the pairwise distances for all elements in a and b (which
# must have the same shapes).
def dist(a, b):
    "Euclidean distance"
    return Numeric.sqrt(sum((a - b)**2, -1))

# In order to compare two arrays of different sizes, I'll just add a
# new axis (to get "all-against-all" comparisons). Then I use argmin
# to get the indices of the smallest distances and use the result as
# an index array in the second array, returning an array with the
# shape of the first array but with elements from the second:

first = Numeric.array([[10, 20, 30],
               [ 0,  0,  1],
               [50, 60, 50]])

second = Numeric.array([[10, 10, 10],
                [20, 20, 20],
                [30, 30, 30],
                [40, 40, 40],
                [50, 50, 50]])

print second[Numeric.argmin(dist(first, second[..., Numeric.NewAxis]), 0)]