Re: Using Nearest on a group of points
- To: mathgroup at smc.vnet.net
- Subject: [mg117579] Re: Using Nearest on a group of points
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Wed, 23 Mar 2011 02:55:09 -0500 (EST)
On Mar 22, 2011, at 6:10 AM, Martin Vavpoti=C4=8D wrote: > Hello. I need some help with the function Nearest. > > I have a groups of points, each with two coordinates (x,y), describing > a connected shape (the last point is a neighbor to the first one). The > initial order of these points is completely scrambled but I need them > to follow one another so their sequence describes a combined shape. I > thought of using the Nearest function but there is a problem. > Somewhere in the middle of my shape is a large gap where no points > reside. I fear that if I use Nearest, the function will find the wrong > point. > > What I need is for function Nearest to ignore points already sorted > and search only for points that have not been used yet. If your list isn't too long you can do it recursively: sortPoints[{x_}] := {x} sortPoints[points_] := With[{index = First[Nearest[Rest[points] -> Automatic, First[points]]]}, {First[points], Sequence @@ sortPoints[Prepend[Drop[Rest[points], {index}], points[[index + 1]]]]}] (Debug) In[63]:= sortPoints[RandomInteger[{1, 10}, {10, 2}]] (Debug) Out[63]= {{10, 1}, {8, 3}, {9, 5}, {8, 8}, {8, 9}, {10, 10}, {4, 9}, {2, 10}, {4, 4}, {2, 2}} Regards, Ssezi