Plot a point of intersection between 2 lines or curves

4 views (last 30 days)
Hi,
If I have a case where x = [1 2 3 4 5] and y1=[2 4 6 8 10] and y2=[4.2 5 5.8 6.1 7.2], and I plot(x,y1) and plot(x,y2) how do I plot the point of intersection. There is a possibility that these two lines dont actually intersect as I came up with the problem on the spot. But, I want a simplified version of how I can plot the point of intersection so I can hover over it and get the co-ordinates.
Thanks.

Accepted Answer

Star Strider
Star Strider on 28 Mar 2021
Try this:
x = [1 2 3 4 5];
y1 = [2 4 6 8 10];
y2 = [4.2 5 5.8 6.1 7.2];
x_int = interp1(y1-y2, x, 0); % X-Intersection Coordinate
y_int = interp1(x, y1, x_int); % Y-Intersection Coordinate
figure
plot(x, y1)
hold on
plot(x, y2)
plot(x_int, y_int, 'sr')
hold off
grid
The coordinates themselves are (x_int,y_int).
  2 Comments
Mayowa Milburn
Mayowa Milburn on 28 Mar 2021
Thanks man, really helpful. It makes sense that its an interpolation rather than using polyfit & polyval.
Star Strider
Star Strider on 28 Mar 2021
As always, my pleasure!
Interpolation is the best option in most instances, however if there are more than one intersection, they need to be calculated separately. That is relatively straightforward to do, the only additional step is that the interpolations require a loop to calculate them separately.

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!