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.

 Respuesta aceptada

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 comentarios

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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Line Plots en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Etiquetas

Preguntada:

el 27 de Mzo. de 2021

Comentada:

el 28 de Mzo. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by