Points lying within line
74 次查看(过去 30 天)
显示 更早的评论
How I can find quickly wether a point lies on a line in the 2d-space, where the coordinates of the line are x1,x2,y1,y2.
thanks in advance
0 个评论
回答(3 个)
Jan
2017-8-4
编辑:Jan
2017-8-4
Are the two points meant as end points of a line segement, or just two points on a line, which has infinite length?
function R = isPointOnLine(P1, P2, Q, EndPoints)
% Is point Q=[x3,y3] on line through P1=[x1,y1] and P2=[x2,y2]
% Normal along the line:
P12 = P2 - P1;
L12 = sqrt(P12 * P12');
N = P12 / L12;
% Line from P1 to Q:
PQ = Q - P1;
% Norm of distance vector: LPQ = N x PQ
Dist = abs(N(1) * PQ(2) - N(2) * PQ(1));
% Consider rounding errors:
Limit = 10 * eps(max(abs(cat(1, P1(:), P2(:), Q(:)))));
R = (Dist < Limit);
% Consider end points if any 4th input is used:
if R && nargin == 4
% Projection of the vector from P1 to Q on the line:
L = PQ * N.'; % DOT product
R = (L > 0.0 && L < L12);
end
This considers line in all directions, rounding errors and if the 4th input is used, Q must be element of the line between P1 and P2.
0 个评论
Image Analyst
2017-8-4
On a related note, if you didn't know the line formula and needed to figure it out, you mgiht take a look at RANSAC https://en.wikipedia.org/wiki/Random_sample_consensus
0 个评论
Alessandro La Chioma
2017-8-4
You can have a little function like the following:
function IsPointWithinLine(x1, y1, x2, y2, x3, y3)
% Line equation: y = m*x + b;
m = (y2-y1)/(x2-x1);
b = y1 - m*x1;
yy3 = m*x3 + b;
if y3 == yy3
disp('The point lies on the line')
else
disp('The point does NOT lie on the line')
end
3 个评论
Jan
2017-8-4
A combination:
function R = IsPointWithinLine(x1, y1, x2, y2, x3, y3)
% Line equation: y = m*x + b;
Limit = 100 * eps(max(abs([x1,y1,x2,y2,x3,y3])));
if x1 ~= x2
m = (y2-y1) / (x2-x1);
yy3 = m*x3 + y1 - m*x1;
R = (abs(y3 - yy3) < 100 * Limit);
else
R = (x3 < Limit);
end
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!