Calculating euclidean distance between consecutive points of an array with numpy
euclidean-distance, numpy, python, scipy
Solution
Here's one way:
Use the vectorized `np.diff` to compute the deltas:
d = np.diff(points, axis=0)
Then use `np.hypot` to compute the lengths:
segdists = np.hypot(d[:,0], d[:,1])
Or use a more explicit computation:
segdists = np.sqrt((d ** 2).sum(axis=1))
Problem
I have an array which describes a polyline (ordered list of connected straight segments) as follows: ``` points = ((0,0), (1,2), (3,4), (6,5), (10,3), (15,4)) points = numpy.array(points, dtype=float) ``` Currently, I get a list of segment distances using the following loop: ``` segdists = [] for seg in xrange(points.shape[0]-1): seg = numpy.diff(points[seg:seg+2], axis=0) segdists.append(numpy.linalg.norm(seg)) ``` I would like, instead, to apply a single function call, without loops, using some native Scipy/Numpy function. The closest thing I could get is this: ``` from scipy.spatial.distance import pdist segdists = pdist(points, metric='euclidean') ``` but in this later case, segdists provides EVERY distance, and I want to get only the distances between adjacent rows. Also, I'd rather avoid creating custom functions (since I already have a working solution), but instead to use more "numpythonic" use of native functions.