8

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.

1 Answer 1

17

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))
Sign up to request clarification or add additional context in comments.

3 Comments

After some dead-ends by myself, when you put it that way it's actually very straightforward. I've seen hypot being mentioned before, but googling "numpy hypot" doesn't return anything, I had to search at the numpy docs page. Thanks!
Is this also possible in 3D ?
@Varlor: Not with hypot, but the second version, segdists = np.sqrt((d ** 2).sum(axis=1)), works in 3D.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.