4
$\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
    $\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$ – Daniel Lichtblau Apr 28 '16 at 22:34
  • $\begingroup$ @DanielLichtblau: Nearest[testdat2[[All, 1]]->Automatic]; $\endgroup$ – ciao Apr 29 '16 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$ – Daniel Lichtblau Apr 29 '16 at 15:43
5
$\begingroup$

Using Ordering:

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

$\ $ 6

$\endgroup$
  • $\begingroup$ Looks great, thanks! $\endgroup$ – YungHummmma Apr 29 '16 at 17:52

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.