How it works,
main
A = [4 1];
B = [2 9];
axis_val = [-10 15 -10 15];
figure(1);
while 1
clf; hold on;
plot([A(1) B(1)], [A(2) B(2)], 'bo-', 'LineWidth', 2, 'MarkerSize', 15);
text(A(1), A(2), ' A', 'FontSize', 15);
text(B(1), B(2), ' B', 'FontSize', 15);
axis equal; axis(axis_val);
grid on;
pos = ginput(1);
[dist, minpnt] = get_dist_point2line(pos, A, B);
plot(pos(1), pos(2), 'kx', 'LineWidth', 2, 'MarkerSize', 15);
plot(minpnt(1), minpnt(2), 'ro', 'LineWidth', 2, 'MarkerSize', 15);
plot([pos(1) minpnt(1)], [pos(2) minpnt(2)], 'r-', 'LineWidth', 2);
axis equal; axis(axis_val);
grid on;
title(sprintf('Dist: %.1f', dist), 'FontSize', 15);
drawnow;
pause();
end
function
function [mindist, minpnt] ...
= get_dist_point2line(x, a, b)
% IF LINE_A == LINE_B
len_ab = norm(a - b);
if len_ab == 0
mindist = norm(a - x);
minpnt = a;
return;
end
% OTHERWISE
a2b = b - a;
b2a = a - b;
a2x = x - a;
b2x = x - b;
if dot(a2x, a2b) < 0
minpnt = a;
elseif dot(b2x, b2a) < 0
minpnt = b;
else
minpnt = a + dot(a2x, a2b)*a2b/len(a2b)/len(a2b);
end
mindist = dist(minpnt, x);
function res = dot(x, y)
res = x*y';
function res = dist(x, y)
res = len(x-y);
function res = len(x)
res = sqrt(x(1)^2+x(2)^2);
'Enginius > Matlab' 카테고리의 다른 글
Convert k-ary tree to Left Child Right Sibling (LCRS) Tree (2) | 2018.08.26 |
---|---|
Handling 'bvh' format from OptiTrack in MATLAB (0) | 2018.06.30 |
KNN-regression (0) | 2017.03.01 |
Plot transparent png images at arbitrary locations (0) | 2016.11.21 |
Highway Simulator (0) | 2016.02.23 |