MATLAB: Find intersection point between a vertical line and another line.

intersection linesMATLABpolyfitvertical line

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

Best Answer

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
Related Question