4

I have a 2D numpy array that represents the coordinates (x, y) of a curve, and I want to split that curve into parts of the same length, obtaining the coordinates of the division points.

The most easy example is a line defined for two points, for example [[0,0],[1,1]], and if I want to split it in two parts the result would be [0.5,0.5], and for three parts [[0.33,0.33],[0.67,0.67]] and so on.

How can I do that in a large array where the data is less simple? I'm trying to split the array by its length but the results aren't good.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
efirvida
  • 4,592
  • 3
  • 42
  • 68

2 Answers2

2

If I understand well, what you want is a simple interpolation. For that, you can use scipy.interpolate (http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html):

from scipy.interpolate import interp1d
f = interp1d(x, y) ## for linear interpolation
f2 = interp1d(x, y, kind='cubic') ## for cubic interpolation
xnew = np.linspace(x.min(), x.max(), num=41, endpoint=False)
ynew = f(xnew) ## or f2(xnew) for cubic interpolation

You can create a function that returns the coordinates of the split points, given x, y and the number of desired points:

def split_curve(x, y, npts):
    from scipy.interpolate import interp1d
    f = interp1d(x, y)
    xnew = np.linspace(x.min(), x.max(), num=npts, endpoint=False)
    ynew = f(xnew)
    return zip(xnew[1:], ynew[1:])

For example,

split_curve(np.array([0, 1]), np.array([0, 1]), 2) ## returns [(0.5, 0.5)]
split_curve(np.array([0, 1]), np.array([0, 1]), 3) ## [(0.33333333333333331, 0.33333333333333331), (0.66666666666666663, 0.66666666666666663)]

Note that x and y are numpy arrays and not lists.

Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Ok, in review, I think I have misread the question, as the code I posted below splits each segment of the curve rather than the whole curve... fail. – ebarr Feb 24 '16 at 23:36
1

take the length of the line on every axes, the split as you want.

example: point 1: [0,0] point 2: [1,1]

then: length of the line on X axes: 1-0 = 1 also in the Y axes.

now, if you want to split it in two, just divide these lengths, and create a new array.

[0,0],[.5,.5],[1,1]

Anon273
  • 11
  • 1