Code covered by the BSD License

### Highlights from Find intersection of two lines

3.5

3.5 | 4 ratings Rate this file 21 Downloads (last 30 days) File Size: 2.47 KB File ID: #30502

# Find intersection of two lines

This function accepts two lines and returns the point that the lines have in common.

File Information
Description

Also included is a function that allows the user to try the function in a interactive way.

The function only accepts lines with two dimensions (x,y)

MATLAB release MATLAB 7.7 (R2008b)
11 Jul 2013

Cannot handle situation when lines intersect in an extended point.

09 Jul 2012
10 Jul 2011

Does not give accurate intersections. Specifically, at the endpoints of lines. Perhaps due to the high precision of the points chosen since "Warning: Matrix is singular to working precision" is shown. The line intersect function by Douglas Schwartz (file ID #11837) computes the intersection accurately.

An example script showing this:

%This script tests the function "lineintersect.m" by Paulo Silva. Note
%that when line1=1 and line2=2, lineintersect.m finds the correct
%intersection BUT line1=2 ad line2=1 does not.

clear all; close all;

%4 equidistant points on perimeter of circle of radius 100. Placed at 45,
%135, 225, 315 degrees and converted to XY crds using pol2cart function. Row #1 is X-crds, Row #2 is Y-crds
ptsXY=[70.7106781186548,-70.7106781186547,-70.7106781186548;70.7106781186547,70.7106781186548,-70.7106781186547];

%plots points as red stars
hold on;
plot(ptsXY(1,:),ptsXY(2,:),'*','color','red');

%"Lines" describes how the points are connected. Here, pt 1 and pt 3 are connected. And pt 2 and pt 3 are connected.
Lines=[1,2;3,3];

%plot lines and label lines with line IDs
for ii=1:size(Lines,2)
plot(ptsXY(1,Lines(:,ii)),ptsXY(2,Lines(:,ii)));
text(linspace(ptsXY(1,Lines(1,ii)),ptsXY(1,Lines(2,ii)),10),linspace(ptsXY(2,Lines(1,ii)),ptsXY(2,Lines(2,ii)),10),int2str(ii),'Color','black','FontWeight','normal');
end

%choose two lines to test. Note that line1=1 and line2=2 finds the correct
%intersection BUT line1=2 ad line2=1 does not.
line1=2;
line2=1;

%extract XY crds
l1_XY=[ptsXY(:,Lines(1,line1)) ptsXY(:,Lines(2,line1))]; %-each line is defined by 4 coordinates: 2 X- and 2 Y-crds
l2_XY=[ptsXY(:,Lines(1,line2)) ptsXY(:,Lines(2,line2))]; %/

%look for intersection and plot intersection
[intxX,intxY]=lineintersect([l1_XY(:,1)' l1_XY(:,2)'],[l2_XY(:,1)' l2_XY(:,2)']);
plot(intxX,intxY,'ro','MarkerFaceColor','g','LineWidth',2) %this will mark the intersection point with red 'o'

07 Apr 2011