Plot a point of intersection between 2 lines or curves

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.

 Akzeptierte Antwort

Star Strider
Star Strider am 28 Mär. 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 Kommentare

Thanks man, really helpful. It makes sense that its an interpolation rather than using polyfit & polyval.
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Line Plots finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by