[Numpy-discussion] Distance Matrix speed

Alan G Isaac aisaac at american.edu
Tue Jun 20 02:15:31 CDT 2006


I think the distance matrix version below is about as good 
as it gets with these basic strategies.

fwiw,
Alan Isaac

def dist(A,B):
    rowsA, rowsB = A.shape[0], B.shape[0]
    distanceAB = empty( [rowsA,rowsB] , dtype=float)
    if rowsA <= rowsB:
        temp = empty_like(B)
        for i in range(rowsA):
            #store A[i]-B in temp
            subtract( A[i], B, temp )
            temp *= temp
            sqrt( temp.sum(axis=1), distanceAB[i,:])
    else:
        temp = empty_like(A)
        for j in range(rowsB):
            #store A-B[j] in temp
            temp = subtract( A, B[j], temp )
            temp *= temp
            sqrt( temp.sum(axis=1), distanceAB[:,j])
    return distanceAB






More information about the Numpy-discussion mailing list