Intersection of lines with endpoints

The lines are represented by their endpoints in a matrix. Each row in a matrix gives coordinates for a line like: (x1, y1, x2, y2).The problem is that Matlab makes a line from the endpoints and not a section of a line and still displays intersection although it's not there. (See the attached picture below)
lines = [
1.9988 3.3693 5.3629 6.9431
2.7362 6.3124 4.5334 3.6730
4.8329 5.9387 4.3260 4.4204
];
a = lines;
b = a;
for line = 1:size(a,1)
lineone = a(line, :);
b(1,:) = [];
for anotherline = 1:size(b,1)
linetwo = b(anotherline, :);
%line1
%x1 =[from x1 value , to x2 value]
%y1 =[from y1 value , to y2 value]
x1 = [lineone(1) lineone(3)];
y1 = [lineone(2) lineone(4)];
%line2
x2 = [linetwo(1) linetwo(3)];
y2 = [linetwo(2) linetwo(4)];
%fit linear polynomial
p1 = polyfit(x1,y1,1);
p2 = polyfit(x2,y2,1);
%calculate intersection
x_intersect = fzero(@(x) polyval(p1-p2,x),3);
y_intersect = polyval(p1,x_intersect);
intersectionpoint =[x_intersect , y_intersect]
hold on
plot(x1,y1)
plot(x2,y2)
plot(x_intersect,y_intersect,"*")
end

2 Comments

Why you just don't check if x value of found intersection is within range where (and only where) could possibly be the intersection between two lines?
if x_intersect >= max(min(x1),min(x2)) && ...
x_intersect <= min(max(x1),max(x2))
intersectionpoint =[x_intersect , y_intersect]
plot(x_intersect,y_intersect,"*")
end
polyfit and fzero is an overkill for the occurring easy systems of equations. If you express the line in the form of a start point and a direction vector, it gets much easier to obtain the result and as a side effect it is trivial to limit the intersections to the line segment only. On demand I will post some code in the evening.

Sign in to comment.

Categories

Products

Asked:

on 12 Dec 2017

Answered:

on 13 Dec 2017

Community Treasure Hunt

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

Start Hunting!