본문 바로가기

Enginius/Matlab

Closest Distance from Point to Line

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);