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.

 採用された回答

Star Strider
Star Strider 2021 年 3 月 28 日

1 投票

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 件のコメント

Mayowa Milburn
Mayowa Milburn 2021 年 3 月 28 日
Thanks man, really helpful. It makes sense that its an interpolation rather than using polyfit & polyval.
Star Strider
Star Strider 2021 年 3 月 28 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLine Plots についてさらに検索

製品

リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by