[Numpy-discussion] distance matrix speed

Johannes Loehnert a.u.r.e.l.i.a.n at gmx.net
Fri Jun 16 01:28:18 CDT 2006


Hi,

def dtest():
    A = random( [4,2])
    B = random( [1000,2])

    # drawback: memory usage temporarily doubled
    # solution see below
    d = A[:, newaxis, :] - B[newaxis, :, :]
    # written as 3 expressions for more clarity
    d = sqrt((d**2).sum(axis=2))
    return d


def dtest_lowmem():
    A = random( [4,2])
    B = random( [1000,2])

    d = zeros([4, 1000], dtype='f')  # stores result
    for i in range(len(A)):
        # the loop should not impose much loss in speed
        dtemp = A[i, newaxis, :] - B[:, :]
        dtemp = sqrt((dtemp**2).sum(axis=1))
        d[i] = dtemp
    return d

(both functions untested....)

HTH, Johannes




More information about the Numpy-discussion mailing list