Find intersection point between a vertical line and another line.

18 vues (au cours des 30 derniers jours)
David Rojas
David Rojas le 19 Fév 2021
Commenté : Alan Stevens le 19 Fév 2021
Hi everyone,
I have a simple question which I cannot solve. I have to find the intersection point between 2 straight lines but one of them is vertical (slope==Inf) so my function is not working as desired. I have use the code here below and it works perfectly but not if one of the lines is vertical. Any ideas?
AlineX=[0 0];
AlineY=[0 400];
BLineX=[1180 570];
BLineY=[-289.5 250];
p1 = polyfit(AlineX,AlineY,1);
p2 = polyfit(BLineX,BLineY,1);
%Calculating intersection
X=fzero(@(x) polyval(p1-p2,x),3);
Y=polyval(p1,X);
As you can see, there is a A line whose starting coordinate is (0,0) and endind at (0,400) and a B line that starts at (1180,-289.5) and ends at (570,250).
One of the things I tried (since the vertical line is starting at (0,0), is doing 2 opposiute diagonals, like this:
AlineX=[-1180 -570];
AlineY=[-289.5 250];
BLineX=[1180 570];
BLineY=[-289.5 250];
p1 = polyfit(AlineX,AlineY,1);
p2 = polyfit(BLineX,BLineY,1);
%Calculating intersection
X=fzero(@(x) polyval(p1-p2,x),3);
Y=polyval(p1,X);
This gives a solution but the result X is not at 0 so I don't really understand why. Any ideas?
Many thanks in advance

Réponse acceptée

Alan Stevens
Alan Stevens le 19 Fév 2021
You could insert a conditional:
AlineX=[0 0];
AlineY=[0 400];
BLineX=[1180 570];
BLineY=[-289.5 250];
p1 = polyfit(AlineX,AlineY,1);
p2 = polyfit(BLineX,BLineY,1);
%Calculating intersection
if AlineX(1) == AlineX(2)
X = AlineX(1);
Y = polyval(p2,X);
else
X=fzero(@(x) polyval(p1-p2,x),3);
Y=polyval(p1,X);
end
  2 commentaires
David Rojas
David Rojas le 19 Fév 2021
Wow, it worked! Although it shows a warning:
Warning: Polynomial is badly conditioned. Add points with distinct X values, reduce the degree of the polynomial, or try centering and
scaling as described in HELP POLYFIT.
> In polyfit (line 72)
In intersectFunction (line 37)
Thank you Alan!!
Alan Stevens
Alan Stevens le 19 Fév 2021
This will eliminate the warning (which refers to p1 when you have a vertical line)
AlineX=[0 0];
AlineY=[0 400];
BLineX=[1180 570];
BLineY=[-289.5 250];
p2 = polyfit(BLineX,BLineY,1);
%Calculating intersection
if AlineX(1) == AlineX(2)
X = AlineX(1);
Y = polyval(p2,X);
else
p1 = polyfit(AlineX,AlineY,1);
X=fzero(@(x) polyval(p1-p2,x),3);
Y=polyval(p1,X);
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by