6
$\begingroup$

I frequently end up in this situation. I have a solution, but I suspect it's the dumbest way of doing it. Frequently, I'll have a list of pairs, for example:

testdat2 = Table[{i, i^2}, {i, 0, 2, .1}] {{0., 0.}, {0.1, 0.01}, {0.2, 0.04}, {0.3, 0.09}, {0.4, 0.16}, {0.5, 0.25}, {0.6, 0.36}, {0.7, 0.49}, {0.8, 0.64}, {0.9, 0.81}, {1., 1.}, {1.1, 1.21}, {1.2, 1.44}, {1.3, 1.69}, {1.4, 1.96}, {1.5, 2.25}, {1.6, 2.56}, {1.7, 2.89}, {1.8, 3.24}, {1.9, 3.61}, {2., 4.}} 

And I'll want to find the index of the pair with its first element closest to a given number. For example, if I want to find the pair whose first element is closest to 0.52, that would be the pair {0.5, 0.25}.

My way of doing this now is to look at only the first element of each pair by using [[All,1]], then using Nearest to get the nearest element, then using Position to find the position of it... but it's very ugly and there's gotta be a better way:

First@First@ Position[testdat2[[All, 1]], First@Nearest[testdat2[[All, 1]], .52]] 

What's the more elegant way? thanks!

$\endgroup$
3
  • 3
    $\begingroup$ If you are going to do this often, with the same list, then create a NearestFunction with Nearest[testdat2[[All, 1]]->Range[Length[testdat2]]]. You should now be able to avoid the Position machinations. For one-off purposes, the method in a response that uses Ordering is quite fine. $\endgroup$ Commented Apr 28, 2016 at 22:34
  • $\begingroup$ @DanielLichtblau: Nearest[testdat2[[All, 1]]->Automatic]; $\endgroup$ Commented Apr 29, 2016 at 0:45
  • $\begingroup$ @ciao Having worked on that code a bit, I of course had no idea the Automatic setting would do just what was wanted. $\endgroup$ Commented Apr 29, 2016 at 15:43

3 Answers 3

5
$\begingroup$

Using Ordering:

First @ Ordering[Abs[testdat2[[All, 1]] - 0.52], 1] 

$\ $ 6

$\endgroup$
1
  • $\begingroup$ Looks great, thanks! $\endgroup$ Commented Apr 29, 2016 at 17:52
3
$\begingroup$
list = {{0., 0.}, {0.1, 0.01}, {0.2, 0.04}, {0.3, 0.09}, {0.4, 0.16}, {0.5,0.25}, {0.6, 0.36}, {0.7, 0.49}, {0.8, 0.64}, {0.9, 0.81}, {1., 1.}, {1.1, 1.21}, {1.2, 1.44}, {1.3, 1.69}, {1.4, 1.96}, {1.5, 2.25}, {1.6, 2.56}, {1.7, 2.89}, {1.8, 3.24}, {1.9, 3.61}, {2., 4.}}; 

Using PositionSmallest (new in 13.2)

PositionSmallest[Abs[list[[All, 1]] - 0.52]] 

{6}

$\endgroup$
1
$\begingroup$
list = {{0., 0.}, {0.1, 0.01}, {0.2, 0.04}, {0.3, 0.09}, {0.4, 0.16}, {0.5,0.25}, {0.6, 0.36}, {0.7, 0.49}, {0.8, 0.64}, {0.9, 0.81}, {1., 1.}, {1.1, 1.21}, {1.2, 1.44}, {1.3, 1.69}, {1.4, 1.96}, {1.5, 2.25}, {1.6, 2.56}, {1.7, 2.89}, {1.8, 3.24}, {1.9, 3.61}, {2., 4.}}; 

Using NearestTo:

Flatten@Position[#, NearestTo[0.52][#][[1]]] &@list[[All, 1]] (*{6}*) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.