Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do this operation in numPy?

I have an array X of 3D coords of N points (N*3) and want to calculate the eukledian distance between each pair of points.

I can do this by iterating over X and comparing them with the threshold.

coords = array([v.xyz for v in vertices])
for vertice in vertices:
    tests = np.sum(array(coords - vertice.xyz) ** 2, 1) < threshold
    closest = [v for v, t in zip(vertices, tests) if t]

Is this possible to do in one operation? I recall linear algebra from 10 years ago and can't find a way to do this.

Probably this should be a 3D array (point a, point b, axis) and then summed by axis dimension.

edit: found the solution myself, but it doesn't work on big datasets.

    coords = array([v.xyz for v in vertices])
    big = np.repeat(array([coords]), len(coords), 0)
    big_same = np.swapaxes(big, 0, 1)
    tests = np.sum((big - big_same) ** 2, 0) < thr_square

    for v, test_vector in zip(vertices, tests):
        v.closest = self.filter(vertices, test_vector)
like image 219
culebrón Avatar asked Jan 20 '26 22:01

culebrón


1 Answers

Use scipy.spatial.distance. If X is an n×3 array of points, you can get an n×n distance matrix from

from scipy.spatial import distance
D = distance.squareform(distance.pdist(X))

Then, the closest to point i is the point with index

np.argsort(D[i])[1]

(The [1] skips over the value in the diagonal, which will be returned first.)

like image 74
Fred Foo Avatar answered Jan 23 '26 11:01

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!