find algorithm for a contour

3 visualizaciones (últimos 30 días)
Desmond Anthony
Desmond Anthony el 25 de Nov. de 2021
Respondida: Sanju el 21 de Feb. de 2024
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 comentario
Adam Danz
Adam Danz el 26 de Nov. de 2021
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).

Iniciar sesión para comentar.

Respuestas (1)

Sanju
Sanju el 21 de Feb. de 2024
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!

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by