Home > front end >  Find intersection of two Vectors with numpy
Find intersection of two Vectors with numpy

Time:11-01

Is there a way I can calculate the intersection of these two vectors? I am aware how to do that by hand, but not with numpy.

Question

I looked into numpy.intersect1d, but that wasn't a help.

CodePudding user response:

Essentially you are trying to solve 3 equations, with 2 unkowns. This does not always have a solution as vectors do not always intersect in 3d. You could solve for the best solution using least squares. If the error is 0 (or the rank is 2), then they do intersect:

v1 = np.array([4, 2, -1]).T
c1 = np.array([6, 3, 2]).T
v2 = np.array([5, -2, 3]).T
c2 = np.array([-3, 3, 0]).T
# in this case the solved x is [-1.  1.], error is 0, and rank is 2
x, err, rank = np.linalg.lstsq(np.array([v1, -v2]).T, c2-c1)[:3]
if rank == 2:
    # intersection exists
    print(v1 * x[0]   c1)
else:
    print("no intersection")
  • Related