Clear Filters
Clear Filters

find algorithm for a contour

1 view (last 30 days)
Desmond Anthony
Desmond Anthony on 25 Nov 2021
Answered: Sanju on 21 Feb 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 Comment
Adam Danz
Adam Danz on 26 Nov 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).

Sign in to comment.

Answers (1)

Sanju
Sanju on 21 Feb 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!

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!