find algorithm for a contour

1 次查看(过去 30 天)
Desmond Anthony
Desmond Anthony 2021-11-25
回答: Sanju 2024-2-21
Hey guys,
i have n points given in a plane and my task is it to find an algorithm that can determine n points in the right order and then connect together. the algorithm have to find the next point that is closest to the last point and then so on.but i have no idea how this goes.
i hope you guys can help me by this.
  1 个评论
Adam Danz
Adam Danz 2021-11-26
Sounds like you should compute euclidean distance between the 3D points (or 2D points if the plane in parallel to the XY, XZ, or YZ planes).

请先登录,再进行评论。

回答(1 个)

Sanju
Sanju 2024-2-21
You're discussing the "nearest neighbour" problem. In MATLAB, this can be tackled by utilizing the “pdist2” function to calculate pairwise distances between points. Subsequently, you can iteratively identify the closest neighbour for each point.
Here's an example implementation you can refer to,
% Generate random points
n = 10;
points = rand(n, 2);
% Initialize variables
order = zeros(n, 1);
visited = false(n, 1);
% Find the starting point (closest to the origin)
distances = pdist2(points, [0, 0]);
[~, start] = min(distances);
order(1) = start;
visited(start) = true;
% Find the nearest neighbour for each point
for i = 2:n
distances = pdist2(points, points(order(i-1), :));
distances(visited) = inf; % Ignore already visited points
[~, next] = min(distances);
order(i) = next;
visited(next) = true;
end
% Connect the points in the order found
x = points(order, 1);
y = points(order, 2);
plot(x, y, 'o-');
The above code generates ‘n’ random points in a plane, finds the starting point (closest to the origin), and then iteratively finds the nearest neighbour for each point. Finally, it plots the points in the order found, connecting them with lines.
You can also refer to the below documentation on “pdist2” function if required,
Hope this Helps!

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by