I have 2 vectors that are x and y coordinates of the 8 vertexes of a polygon
x=[5 5 7 7 9 9 5 7]
y=[8 6 6 8 6 8 10 10]
I wanna sort them (clockwise) to obtain the right vectors (to draw the polygon correctly)
x=[5 7 9 9 7 7 5 5]
y=[6 6 6 8 8 10 10 8]
I tried the solutions by @ben-voight and @mclafee, but I think they are sorting the wrong way.
When using atan2 the angles are stated in the following way:
Matlab Atan2
Wikipedia Atan2
This means that using ascending sort() of Numpy or Matlab will progress counterclockwise.
This can be verified using the Shoelace equation
Wikipedia Shoelace
Python Shoelace
So, adjusting the answers mentioned above to use descending sorting the correct solution in Matlab is
The solution in numpy is
Output:
Please notice the
[::-1]
used to invert arrays / lists.Python version (numpy) for Ben Voigt's algorithm:
Example:
Step 1: Find the unweighted mean of the vertices:
Step 2: Find the angles:
Step 3: Find the correct sorted order:
Step 4: Reorder the coordinates:
This algorithm does not apply to non-convex polygons. Instead, consider using MATLAB's poly2cw()