MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Using Nearest on a group of points

  • To: mathgroup at
  • Subject: [mg117623] Re: Using Nearest on a group of points
  • From: Peter Pein <petsie at>
  • Date: Thu, 24 Mar 2011 06:32:42 -0500 (EST)
  • References: <im9sk8$g5j$>

Am 22.03.2011 11:11, schrieb Martin VavpotiÄ?:
> 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.

I've got two possible solutions; one is ugly and the other is probably slow:

get some "separated" random data:
In[1]:= pts = RandomSample[Union[RandomReal[{0, 1},
      {5, 2}], RandomReal[{5, 6}, {5, 2}]], 10]

have a look at the mess:
In[2]:= ListPlot[pts, Joined -> True]
(* output deleted *)

use a brain twister using anonymous functions and a temporary variable:
(starting at the origin; could be any point in the plane)
In[3]:= sorted = Rest[First[NestWhile[
      Block[{tmp}, {Join[#1[[1]],
          tmp = Nearest[#1[[2]], #1[[1,-1]]]],
         DeleteCases[#1[[2]], tmp[[1]]]}] & ,
      {{{0, 0}}, pts}, #1[[2]] =!= {} & , 1]]]

and look at the result:
In[4]:= ListPlot[sorted, Joined -> True]

or apply a rule repeatedly:

In[5]:= sort2=Rest[First[{{{0.,0.}},pts}//. 

and the results are the same:
In[6]:= sorted === sort2
Out[6]= True


  • Prev by Date: Writing images from manipulate
  • Next by Date: Re: Chop in Mathematica 8.0.1
  • Previous by thread: Re: Using Nearest on a group of points
  • Next by thread: Re: Using Nearest on a group of points