# Find intersection point between a vertical line and another line.

27 views (last 30 days)
David Rojas on 19 Feb 2021
Commented: Alan Stevens on 19 Feb 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?

Alan Stevens on 19 Feb 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 CommentsShowHide 1 older comment
Alan Stevens on 19 Feb 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

R2020a

### Community Treasure Hunt

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

Start Hunting!