# Points lying within line

107 views (last 30 days)
Graz Mand on 4 Aug 2017
Commented: Jan on 4 Aug 2017
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.

Jan on 4 Aug 2017
Edited: Jan on 4 Aug 2017
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 on 4 Aug 2017
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 on 4 Aug 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
Jan on 4 Aug 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