两个数组的交点(作为数据集)

时间:2019-03-12 10:46:55

标签: python arrays intersection

我有两个数组(x1,y1)(x2,y2)。我可以分别绘制它们并查看交点(xi,yi)

但是我想找到代码中的交点,而不是通过绘制和查看它们。我写道:

idx = Numeric.argwhere(np.diff(np.sign(y2-y1))).flatten()
print x[idx]

我在做错什么吗?

1 个答案:

答案 0 :(得分:0)

使用对this question的回答中给出的函数,您可以计算两条线之间的交点:

# Function from referenced question
def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

# Sample line arrays
x1 = (1,5)
y1 = (3,3)

x2 = (1,1)
y2 = (3,6)

# Compute intersection
xi, yi = line_intersection((x1, y1), (x2, y2))

# Visualize results
plt.figure()
plt.plot((x1[0], y1[0]), 
         (x1[1], y1[1]))
plt.plot((x2[0], y2[0]), 
         (x2[1], y2[1]))
plt.scatter(xi, yi, c='k', s=50)

enter image description here