[Numpy-discussion] finding minimum distance using arrays

Robert Kern robert.kern@gmail....
Wed Apr 23 01:10:15 CDT 2008

On Wed, Apr 23, 2008 at 1:00 AM, wilson <wilson.t.thompson@gmail.com> wrote:
> hi
>  i wrote a function to find euclidian distance between two vectors and
>  applied it to the rows of a 2d array of floats  as below
>  from math import sqrt
>  from numpy import array,sum
>  def distance(vec1, vec2):
>     return sqrt(sum([(x-y)**2 for x,y in zip(vec1, vec2)]))
>  def findmatch(wts,inputwt):
>     mindist=99.0
>     index=0
>     for i in range(len(wts)):
>         d=distance(wts[i],inputwt)
>         if d == 0.0:
>             mindist=d
>             index=i
>             break
>         elif d < mindist:
>             mindist=d
>             index=i
>     return index,mindist
>  inputwt is a 1 dim array,wts is a 2d array .i want to find the
>  distance between inputwt and each row of wts...I used mindist=99.0  as
>  an improbable value for distance for  the sample float arrays which i
>  used to test it...
>  i am not sure if this is the proper way to write this function..can
>  someone suggest how i can make it better?

import numpy

def findmatch(wts, inputwts):
    wts = numpy.asarray(wts)
    inputwts = numpy.asarray(wts)
    dx = wts - inputwts
    distances = (dx * dx).sum(axis=1)
    index = distances.argmin()
    mindist = distances[index]
    return index, mindist

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco

More information about the Numpy-discussion mailing list