File Exchange

image thumbnail

Fast Line Segment Intersection

version (3.5 KB) by U. Murat Erdem
Finds the pairwise intersection points between line segments in 2D Cartesian space.


Updated 10 Apr 2010

View Version History

View License

OUT = LINESEGMENTINTERSECT(XY1,XY2) generates intersection analysis between the line segment sets given in XY1 and XY2. Code can handle coincident and parallel lines.

The main emphasis is on speed. The code is fully vectorized and it runs pretty fast (orders of magnitude) compared to some of the previous postings.

Cite As

U. Murat Erdem (2020). Fast Line Segment Intersection (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (18)

Gaurav Bahl

liang huo


vvf gao

what is the mathematics behind the ocde ?? thank you

Yusheng Zhou

John Solum

Liwei Dai

Just checked your code, it seems that the entries in out.intMatrixX, out.intMatrixY are not correct. Many of the entries are filled with zeros which should be NaN if there is no intersection between two line segments, right?
Another thing is the link to the algorithm behind this just doesn't work anymore, could you please give me another link? I felt it's pretty awesome to learn this. :)

M. F.

Sam Murthy

Please consider changing the parallelism check to abs(denominator) < some small number. This will catch lines that are parallel to within some threshold.

Matthew Bays


Francesco Montorsi

I've found your function very useful, thanks! However I recently wanted to squeeze out some additional performance and ended up rewriting the thing in MEX C code, which can be compiled and run from MATLAB... I posted my code at .


piet fue



Quick and effective. However, I believe there is a typo in the documentation:

'intNormalizedDistance2To1' : N1xN2 matrix where the (i,j) entry is the normalized distance from the start point of line segment XY1(j,:) to the intersection point with XY2(i,:).

This description is the same as intNormalizedDistance1To2 except that i and j are swapped in the description, and that doesn't really make any sense. I believe XY1 and XY2 should also be swapped.


Fabio Pinna

It worked fine and fast for me! Good work!
Good vectorization.
The complex output prevent further vectorization but it is already fast enough

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!