This is a vectorized Matlab function for finding pairwise projections of m
points onto n
line segments. Here xp
and yp
are m by 1
vectors holding coordinates of m
different points, and x1
, y1
, x2
and y2
are n by 1
vectors holding coordinates of start and end points of n
different line segments.
It returns m by n
matrices, x
and y
, where x(i, j)
and y(i, j)
are coordinates of projection of i
-th point onto j
-th line.
The actual work is done in first few lines and the rest of the function runs a self-test demo, just in case where it is called with no parameters. It s relatively fast, I managed to find projections of 2k points onto 2k line segments in less than 0.05s.
function [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2)
if nargin > 0
xd = (x2-x1) ;
yd = (y2-y1) ;
dAB = xd.*xd + yd.*yd;
u = bsxfun(@rdivide, bsxfun(@times, bsxfun(@minus, xp, x1 ), xd) + ...
bsxfun(@times, bsxfun(@minus, yp, y1 ), yd), dAB);
x = bsxfun(@plus, x1 , bsxfun(@times, u, xd));
y = bsxfun(@plus, y1 , bsxfun(@times, u, yd));
else
nLine = 3;
nPoint = 2;
xp = rand(nPoint, 1) * 2 -1;
yp = rand(nPoint, 1) * 2 -1;
x1 = rand(nLine, 1) * 2 -1;
y1 = rand(nLine, 1) * 2 -1;
x2 = rand(nLine, 1) * 2 -1;
y2 = rand(nLine, 1) * 2 -1;
tic;
[x, y] = projectPointLine(xp, yp, x1, y1, x2, y2);
toc
close all;
plot([x1 ; x2 ], [y1 ; y2 ], .- , linewidth , 2, markersize , 20);
axis equal;
hold on
C = lines(nPoint + nLine);
for i=1:nPoint
scatter(x(i, :), y(i, :), 100, C(i+nLine, :), x , linewidth , 2);
scatter(xp(i), yp(i), 100, C(i+nLine, :), x , linewidth , 2);
end
for i=1:nLine
scatter(x(:, i) , y(:, i) , 100, C(i, :), o , linewidth , 2);
end
end
end