Closest Distance from Point to Line

Posted 2017.07.14 20:43

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' 카테고리의 다른 글

Closest Distance from Point to Line  (0) 2017.07.14
KNN-regression  (0) 2017.03.01
Plot transparent png images at arbitrary locations  (0) 2016.11.21
Highway Simulator  (0) 2016.02.23
Using MATLAB in script (OS X)  (0) 2016.01.15
Nonparametric Regression and Gaussian Random Paths  (0) 2015.12.23
« PREV : 1 : ··· : 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : ··· : 581 : NEXT »