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?
Asked
Active
Viewed 1,085 times
1
-
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. – bbgodfrey Feb 21 '15 at 16:33
3 Answers
1
pts = RandomReal[{0, 1}, {20, 2}];
ordered2 = pts[[Ordering[-Norm /@ (# - orig & /@ pts)]]]
ordered2 == ordered (* `ordered` from belisarius's answer *)
(* True *)
kglr
- 394,356
- 18
- 477
- 896
0
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}]]

Dr. belisarius
- 115,881
- 13
- 203
- 453
0
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.9112240.011001
It is shorter to write too. :-) Ordering is slightly faster still but not as convenient to use.