Search code examples
numpylinenumpy-ndarray

Line equation of every two consecutive points in a NumPy array


I want to find the line equation of every two consecutive points (2-dimensional) in a NumPy array. I know how to do it robustly (i.e. using a loop), but I wonder if there's a more sophisticated approach.

Thanks.

Given below is a robust approach:

import numpy as np

a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
N = int(max(a.shape))
b = []
for i in range(N - 1):
    x = [a[i,0], a[i + 1,0]]
    y = [a[i,1], a[i + 1,1]]
    b.append(tuple(np.polyfit(x, y, 1)))

print(b)

Solution

  • For straight lines do the calculation longhand. y = mx + c where m is the gradient = change in y / change in x and c is the constant c = y0 - m*x0

    import numpy as np
    
    a = np.array([[1, 2], [2, 4], [3, 8], [5, 1]])
    
    x = a[:,0]
    y = a[:,1]
    
    dx = np.diff(x)  # Change in x
    dy = np.diff(y)  # Change in y
    
    # Amended for @Nan's comment below.
    # If any dx is zero this will now return +-inf in m and c without raising a warning
    # The code using m and c will need to handle this if it can occur.
    with np.errstate( divide = 'ignore' ):
        m = dy/dx  # Gradient
    c = y[1:] - m * x[1:]   # Constant
    
    m, c
    # (array([ 2. ,  4. , -3.5]), array([ 0. , -4. , 18.5]))
    # y = mx + c
    
    # Rerunning with              x=3     x=3
    a = np.array([[1, 2], [2, 4], [3, 8], [3, 12]])
    m, c
    (array([ 2.,  4., inf]), array([  0.,  -4., -inf]))