# Better way to use Nearest

I'm trying to write a snippet of code that, given an input value (value), checks a list of arbitrary length (data) for the closest value, and then outputs the index of that value in the list. I'm using the output as an argument, so it can't be in brackets -- it has to be just the value. I can use Nearest and Position to get what I want, but it ends up being in a bunch of brackets each time and I need to use First or Flatten to get it out! It looks ugly.

Right now I have:

First[Flatten[Position[data, First[Nearest[data, value, 1]]]]]


The output is a value of position, not in brackets.

Without that First modifying Nearest the output is {{}}
Without that First and Flatten modifying Position the output is {{position}}. I need the output to simply be position.

Hopefully, I have explained my needs well - does anyone know of a more elegant way to accomplish this?

• You can get rid of the Flatten and one of the Firsts: First@Nearest[data -> Range[Length[data]], 5, 1] – bill s Jul 15 '16 at 21:25
• First + (118679) – Kuba Jul 15 '16 at 21:48
• @bill s. Where in that function should the value you are matching go? The solution also has to work for a list of arbitrary length, which I should have mentioned - I will make the edit. – Nate Jul 15 '16 at 21:53
• Duplicate?: (25273) – Mr.Wizard Jul 16 '16 at 2:48
• data is any list and I just used 5 as the value to match in the data vector – bill s Jul 16 '16 at 13:53

## 1 Answer

I recommend not using Position, but rather giving Nearest a list of rules associating each item in your data list with its position.

data = {3, 4, 5, 6, 7};
rules = Thread[Rule[data, Range[Length[data]]]];
where[val_] := Nearest[rules, val, 1][[1]]

where /@ data


{1, 2, 3, 4, 5}

• ...or just use Nearest[data -> Automatic, val, 1][[1]]. – J. M.'s ennui Jul 15 '16 at 23:28
• @J.M. Yes, that's more concise. Didn't know about that variant, but I guess I should have reviewed the docs before posting. Since the OP's case is very common, it makes a lot of sense it should have special support – m_goldberg Jul 16 '16 at 1:19