Finding the closest point on a line to another point

67 ビュー (過去 30 日間)
Rae Taylor-Burns
Rae Taylor-Burns 2020 年 1 月 29 日
コメント済み: James Tursa 2020 年 1 月 29 日
Hello all,
I am looking find the closest point on the line in the below image to each of the points shown by a circle.
I have 2 tables, one I will call line, and one I will call point:
line.x = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
line.y = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
point.x = [4.5, 2.1, 3.6]
point.y = [3.9, 2.7, 3.1]
scatter(point.x, point.y)
hold on
plot(line.x, line.y)
I want to find the closest defined point on the line (it has to be one of the points listed above, it can't be a point on the line between the defined points) that is closest to each of the circles.
Any tips on how to do this? I have found several similar threads but nothing that gets at what I'm after. Thanks all!!
  2 件のコメント
Turlough Hughes
Turlough Hughes 2020 年 1 月 29 日
Are you treating the line as continuous or as the discrete points provided?
Rae Taylor-Burns
Rae Taylor-Burns 2020 年 1 月 29 日
As the discrete points provided. Thanks!

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

採用された回答

Turlough Hughes
Turlough Hughes 2020 年 1 月 29 日
編集済み: Turlough Hughes 2020 年 1 月 29 日
Solving for the discrete points is actually a lot easier. Using your data as follows:
line.x = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5];
line.y = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5];
point.x = [4.5, 2.1, 3.6];
point.y = [3.9, 2.7, 3.1];
h = figure(); plot(line.x,line.y,'ok','MarkerFaceColor','k');
hold on, plot(point.x,point.y,'or')
h.Position(3) = h.Position(4); % sets the figure aspect ratio to 1.
I just find the distance to each point in your line. The first row of dist is the distance of every point in line to the [point.x(1) point.y(1)], row two is all the distances to the second point and so on:
dist = sqrt((line.y - point.y.').^2 + (line.x - point.x.').^2)
[~,idx] = min(dist,[],2); % index for the closest points, i.e. those with min distance.
Plot resulting points on the line that are closest.
hold on; plot(line.x(idx),line.y(idx),'.cyan','MarkerSize',18)
  3 件のコメント
Turlough Hughes
Turlough Hughes 2020 年 1 月 29 日
Have you tried clearing your workspace and then entering the code exactly as provided above?
James Tursa
James Tursa 2020 年 1 月 29 日
You can drop the sqrt( ) since it won't affect the resulting min( ) answer.

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

その他の回答 (1 件)

Rae Taylor-Burns
Rae Taylor-Burns 2020 年 1 月 29 日
Ah yes - thank you!! Very helpful and fast!

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by