How to find the closest point to a line

32 ビュー (過去 30 日間)
Blue
Blue 2022 年 11 月 2 日
コメント済み: 012786534 2022 年 11 月 3 日
Hello,
I am having a bit of a hard time finding which point (i.e centroid) is closest to a line formed by the start and end coordinates. The lines are always in a straight line.
points = array2table([1,48,-55,48.1,-55.1; 2, 50,-55,50.1,-55.1], 'VariableNames', {'name', 'start_lat','start_long','end_lat','end_long'})
centroids = cell2table({'A', 47, -56; 'B', 51,-54}, 'VariableNames', {'name', 'centroid_lat','centroid_long'})
desired_output = cell2table({1,48,-55,48.1,-55.1, 'A'; 2, 50,-55,50.1,-55.1, 'B'}, 'VariableNames', {'name', 'start_lat','start_long','end_lat','end_long', 'closet_centroid'})
Thank you,
  3 件のコメント
Blue
Blue 2022 年 11 月 2 日
I have edited the question to change the centroids positions. I simply want to associate each centroid to the closest line formed by the start and end positions of each point
Davide Masiello
Davide Masiello 2022 年 11 月 2 日
How do you determine the distance between a line and a point?
Is the distance between the point and the line centroid ok?

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2022 年 11 月 2 日
  3 件のコメント
Rik
Rik 2022 年 11 月 3 日
Since you know you only put in 2 points, why not create the vector including the 0? That way you also get to skip the test with length (which I wouldn't use anymore.
I also removed the repmat call, as you only provide a single point.
points = array2table([1,48,-55,48.1,-55.1; 2, 50,-55,50.1,-55.1],...
'VariableNames', {'name', 'start_lat','start_long','end_lat','end_long'});
centroids = cell2table({'A', 47, -56; 'B', 51,-54},...
'VariableNames', {'name', 'centroid_lat','centroid_long'});
for i = 1:height(points)
v1 = [points.start_lat(i), points.start_long(i), 0];
v2 = [points.end_lat(i) , points.end_long(i) , 0];
for j = 1:height(centroids)
pt = [centroids.centroid_lat(j), centroids.centroid_long(j), 0];
a = v1 - v2;
b = pt - v2;
distance(j) = sqrt(sum(cross(a,b,2).^2,2)) ./ sqrt(sum(a.^2,2));
end
[~, idx] = min(distance);
points.associated_centroid(i) = centroids.name(idx);
end
points
points = 2×6 table
name start_lat start_long end_lat end_long associated_centroid ____ _________ __________ _______ ________ ___________________ 1 48 -55 48.1 -55.1 {'A'} 2 50 -55 50.1 -55.1 {'B'}
012786534
012786534 2022 年 11 月 3 日
I agree !

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 11 月 3 日
Does my attached function help any?

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by