MATLAB: Rearranging an array of vertices of a geometry to compute the perimeter

perimeter of geometryrearrangement

Please, find the attached picture. I have the following x and y coordinates of a geometry which are the vertices of a geometry but they are not orderly arranged (1). I need the vertices to be arranged following a counterclockwise direction in order to be able to estimate the perimeter correctly (2). Please, how can I achieve this with matlab code? Thank you so much.
(1) unordered vertices
x y
0 1
0.5 0
0 0.5
0.5 0.8
0.5 0.5
0.3 1
0.5 0.2
0.5 1
0 0
0.4 0
0.1 1
0.1 0
0 0.8
0 0
(2) ordered vertices in counterclockwise direction
x y
0 0
0.1 0
0.4 0
0.5 0
0.5 0.2
0.5 0.5
0.5 0.8
0.5 1
0.3 1
0.1 1
0 1
0 0.8
0 0.5
0 0

Best Answer

Use mean() to get the middle of the set of points. Then use atan2d() to get the angle from the center to each of the points. Then use sort(). It's really super easy. Try it and write back if you can't figure it out. Here's a start:
xCenter = mean(x);
yCenter = mean(y);
angles = atan2d(y - yCenter, x - xCenter);
[sortedAngles, sortOrder] = sort(angles);
x = x(sortOrder);
y = y(sortOrder);