Points lying within line
Afficher commentaires plus anciens
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
Réponses (3)
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.
Image Analyst
le 4 Août 2017
1 vote
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

Alessandro La Chioma
le 4 Août 2017
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 commentaires
Image Analyst
le 4 Août 2017
You'd need to use ismembertol() instead of ==.
Jan
le 4 Août 2017
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
Catégories
En savoir plus sur Geometric Transformation and Image Registration dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!