One solution is to use the equations derived in this tutorial for finding the intersection point of two lines in 2-D (update: this is an internet archive link since the site no longer exists). You can first create two matrices: one to hold the x coordinates of the line endpoints and one to hold the y coordinates.
x = [0 0; 6 6]; %# Starting points in first row, ending points in second row y = [0 6; 6 0];
The equations from the above source can then be coded up as follows:
dx = diff(x); %# Take the differences down each column dy = diff(y); den = dx(1)*dy(2)-dy(1)*dx(2); %# Precompute the denominator ua = (dx(2)*(y(1)-y(3))-dy(2)*(x(1)-x(3)))/den; ub = (dx(1)*(y(1)-y(3))-dy(1)*(x(1)-x(3)))/den;
And you can now compute the intersection point of the two lines:
xi = x(1)+ua*dx(1); yi = y(1)+ua*dy(1);
For the example in the question, the above code gives
xi = 3 and
yi = 3, as expected. If you want to check that the intersection point lies between the endpoints of the lines (i.e. they are finite line segments), you just have to check that the values
ub both lie between 0 and 1:
isInSegment = all(([ua ub] >= 0) & ([ua ub] <= 1));
A couple more points from the tutorial I linked to above:
- If the denominator
denis 0 then the two lines are parallel.
- If the denominator and numerator for the equations for
ubare 0 then the two lines are coincident.