tags:

views:

213

answers:

1

I have an array of 2D Cartesian points in MATLAB and I'd like to sort them so that putting them into plot would create a polygon with no line overlaps.

(NB. I'm not actually going to plot in MATLAB, I just need to sort them in that manner)

I'm thinking of writing a loop that would find the polar coordinate system's 'theta' for a vector going from a new point I know to be inside the polygon to each of the polygon's points, then sorting according to that value, but it seems very hacky and inefficient!

Any tips?

+4  A: 

I think that your idea is just ok.

That will make simple and elegant solution

For finding point in center you can use "avarege"

len=length(points(:,1));
p(1)=sum(points(:,1))/len;
p(2)=sum(points(:,2))/len;

angle=atan2(points(:,2)-p(2),points(:,1)-p(1));

[angle_sorted,perm]=sort(angle);
p_sorted=points
p_sotred(:,1)=points(perm,1);
p_sotred(:,2)=points(perm,2);

Did not check, but it should be ok.

Complexity is n*log(n) becuase of sort.

ralu
There are a couple of spelling slips there - but the advice is excellent! It works a treat - thanks!
JP