1
$\begingroup$

I need to take a list of random points and then sort them from least to greatest based on their Euclidean distance from a certain point. How would I do this?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$ – bbgodfrey Feb 21 '15 at 16:33
0
$\begingroup$
orig = {1, 1};
pts = RandomReal[{0, 1}, {20, 2}];
ordered = Sort[pts, Norm[#1 - orig] > Norm[#2 - orig] &]
Graphics[{PointSize[#[[1]] .01], Point@#[[2]]} & /@  Transpose[{Range@Length@pts, ordered}]]

Mathematica graphics

$\endgroup$
  • 2
    $\begingroup$ Or SortBy[..., Norm[#-orig]&] $\endgroup$ – Szabolcs Feb 21 '15 at 16:22
1
$\begingroup$
pts = RandomReal[{0, 1}, {20, 2}];
ordered2 = pts[[Ordering[-Norm /@ (# - orig & /@ pts)]]]

ordered2 == ordered (* `ordered` from belisarius's answer *)
(* True *)
$\endgroup$
0
$\begingroup$

Using Sort with a custom ordering function forces quadratic complexity due to pairwise comparison(1)(2)(3)(4)(5) and should be avoided whenever possible. Use SortBy instead, as Szabolcs comments.

orig = {1, 1};

pts = RandomReal[1, {50000, 2}];

Sort[pts, Norm[#1 - orig] > Norm[#2 - orig] &] // AbsoluteTiming // First

SortBy[pts, Norm[# - orig] &]                  // AbsoluteTiming // First
3.911224

0.011001

It is shorter to write too. :-) Ordering is slightly faster still but not as convenient to use.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.