NumPy阵列中每两个连续点的直线方程
我想找到NumPy数组中每两个连续点(二维)的直线方程。我知道如何稳健地执行(即使用循环),但我想知道是否有更复杂的方法 谢谢 下面给出了一种稳健的方法:NumPy阵列中每两个连续点的直线方程,numpy,line,numpy-ndarray,Numpy,Line,Numpy Ndarray,我想找到NumPy数组中每两个连续点(二维)的直线方程。我知道如何稳健地执行(即使用循环),但我想知道是否有更复杂的方法 谢谢 下面给出了一种稳健的方法: 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
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)
对于直线,直接进行计算。y=mx+c,其中m是梯度=y的变化/x的变化,c是常数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]))
你能分享你的循环方法和样本数据吗?如果没有代码,很难提供帮助。您可能需要考虑像垂直线这样的情况,其中dx=0以避免运行时警告:在true_divide中遇到除以零这是一个很好的观点。这取决于如何使用直线方程。如果任何
dx
s为零,则y不再是x的函数。