find algorithm for a contour
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
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).
Respuestas (1)
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!
0 comentarios
Ver también
Categorías
Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!