3
$\begingroup$

In the following example Nearest finds the nearest values between list1 and list2 and resorts the list2 according to the order in list1.

list1 = {1, 2, 4, 8, 16, 32};
list2 = {2.1, 1.1, 4.1, 16.1, 8.1, 32.1};

result=Nearest[list2, list1]

{{1.1}, {2.1}, {4.1}, {8.1}, {16.1}, {32.1}}

How can I find the indices on how list2 was resorted to obtain result.

I would like to get the following as output:

{2, 1, 3, 5, 4, 6}
$\endgroup$
0
5
$\begingroup$

So you really want to find nearest from list1 not list2, with labels, right?

 Nearest[Thread[# -> Range@Length@#] &@list1, list2]
{{2}, {1}, {3}, {5}, {4}, {6}}
$\endgroup$
1
  • $\begingroup$ Yes, in my problem list1 corresponds to starting coordinates of a constant number of particles in an image. list2 would be the coordinates got from ComponentMeasurements in the next image (here the order can be different then in list1). I follow the particles and track them by using Nearest from image to image. The indices I need to resort also corresponding further properties like (MeanIntensity, BoundingBoxArea, etc.). $\endgroup$ – mrz Jun 17 '16 at 10:39
8
$\begingroup$

This is the same approach as Kuba's, only a bit shorter

Nearest[list1 -> Automatic][list2]

(* {{2}, {1}, {3}, {5}, {4}, {6}} *)

Mathematica 10.0.2 or higher is required to take advantage of this listability.

$\endgroup$
5
$\begingroup$

I would go with Kuba's method but this also works I believe:

list1 = {4, 16, 8, 1, 32, 2};
list2 = {2.1, 1.1, 4.1, 16.1, 8.1, 32.1};

Ordering[list1][[ Ordering @ Nearest[list1, list2] ]]
{6, 4, 1, 2, 3, 5}

I scrambled the elements of list1 so as not to make the problem too easy; if they are always in order this becomes simply Ordering @ Nearest[list1, list2].

$\endgroup$
1
  • $\begingroup$ Yes this is generally the case, list1 is not ordered. $\endgroup$ – mrz Jun 17 '16 at 10:56

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