find algorithm for a contour
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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
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!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!