File Exchange

image thumbnail

point to line distance

version 1.3.2 (4.2 KB) by Rik
calculate the distance between a 2D or 3D line and one or more points

31 Downloads

Updated 05 Jul 2020

View Version History

GitHub view license on GitHub

You can input either a 2D or a 3D line and 2D or 3D points. This function is an extended version of the line below, with some input checking:
distance=norm(cross(v1-v2,pt-v2))/norm(v1-v2)

Licence: CC by-nc-sa 4.0

Cite As

Rik (2021). point to line distance (https://github.com/thrynae/point_to_line_distance/releases/tag/1.3.2), GitHub. Retrieved .

Comments and Ratings (11)

Francesco Sturla

Anthony Dave

Turlough Hughes

Martin Krøjmand

Songqiu

Thank you very much for your effort in the file.
Could you please improve the code a little more to add two optional outputs: (1) the coordinates of the projection points for all points on the line and (2) a flag if the projection point is inside or outside of the line segment for each point?

Rik

@Nicola, thanks for pointing out this issue. I now uploaded a version where this should be fixed. The function now properly accepts 2D inputs.

Nicola Piccinelli

The input point "pt" shouldn't be checked against the case in which it's of size 2?

Rik

@Kaleesh, I'll try to help you your question thread https://www.mathworks.com/matlabcentral/answers/425347

Kaleesh Bala

lemme put this way

curvexy1 = [ 0 20 ];
curvexy2 =[20 50];

curvexy = (curvexy1 & curvexy2 );

plot (curvexy,'-')
hold on

[x,y] = ginput(1);
h1 = text(x,y,'o', ...
'HorizontalAlignment','center', ...
'Color', [1 0 0], ...
'FontSize',8);

%% let curvexy1 ,curvexy2 be v1,v2 and ginput(1) be pt - I tried using your code to identify the perpendicular distance but ??

Rik

You can find the solution here: https://gamedev.stackexchange.com/questions/72528/how-can-i-project-a-3d-point-onto-a-3d-line

A non-vectorized solution in the terms of the input to this function:

ap = pt-v1;ab = v2-v1;
result = v1 + dot(ap,ab)/dot(ab,ab) * ab;

Rafael Cordero

Hi! Thanks, works great. I was wondering: how do I find the POINT of intersection between the original line and the projection of the point to this line? Thank you!

MATLAB Release Compatibility
Created with R2020a
Compatible with R13SP1 and later releases
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!