Intersection points of multiple straight line segments
13 views (last 30 days)
Show older comments
This feels as though it should be easy, but other than creating loops which for large data sets run for ever I can't see how to do this
I have mulitple line segments with end points in the form [x11 y11 x12 y12; x21 y21 x22 y22;...] [x13 y13 x14 y14; x23 y23 x24 y24;...]
I am trying to find intersection points between any pair of line segments in the two lists
I know how to find where any specific two intersect, using xy = [x1*y2-x2*y1,x3*y4-x4*y3]/[y2-y1,y4-y3;-(x2-x1),-(x4-x3)]; and looping through each list in turn
but can't see an efficient way of testing all possible pairs
Any help gratefully received
3 Comments
Answers (2)
Image Analyst
on 5 May 2025
How about just do a brute force loop
numSegments = size(lineSegments, 1); % Num rows in the matrix.
numIntersections = numSegments * (numSegments - 1);
xyIntersections = nan(numIntersections, 2); % x,y of all intersections.
row = 1;
for k1 = 1 : numIntersections
line1 = lineSegments(k1, :); % [x1, y1, x2, y2]
for k2 = 1 : numIntersections
if k1 == k2
% Same line compared with itself so skip it.
continue;
end
line2 = lineSegments(k2, :);
% Get x1, x2, etc.
x1 = line1(1);
x2 = line1(3);
x3 = line2(1);
x4 = line2(3);
% Get y1, y2, etc.
y1 = line1(2);
y2 = line1(4);
y3 = line2(2);
y4 = line2(4);
% Compute this intersection using your formula.
% Haven't checked your formula but I assume it produces
% a 1x2 row vector containing the (x,y) intersection coordinates.
xyIntersections(row) = [x1*y2-x2*y1,x3*y4-x4*y3] / [y2-y1,y4-y3;-(x2-x1),-(x4-x3)];
row = row + 1;
end
end
2 Comments
Image Analyst
on 6 May 2025
I don't know how much a loop would speed it up. I doubt it's the looping itself that's using up the time. It's the computations inside and that same computation would need to be done with a vectorized method.
How many line segments do you have? A hundred thousand? I did a double nested for loop with each one iterating a hundred thousand times, so that's 10 billion loop iterations. That double for loop took only 3.4 seconds on my laptop. That's really fast for 10 billion iterations, I think.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!