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!
NearestFunction
withNearest[testdat2[[All, 1]]->Range[Length[testdat2]]]
. You should now be able to avoid thePosition
machinations. For one-off purposes, the method in a response that usesOrdering
is quite fine. $\endgroup$Nearest[testdat2[[All, 1]]->Automatic];
$\endgroup$Automatic
setting would do just what was wanted. $\endgroup$