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?

  • 1
    $\begingroup$ You can get rid of the Flatten and one of the Firsts: First@Nearest[data -> Range[Length[data]], 5, 1] $\endgroup$
    – bill s
    Jul 15, 2016 at 21:25
  • $\begingroup$ First + (118679) $\endgroup$
    – Kuba
    Jul 15, 2016 at 21:48
  • $\begingroup$ @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. $\endgroup$
    – Nate
    Jul 15, 2016 at 21:53
  • $\begingroup$ Duplicate?: (25273) $\endgroup$
    – Mr.Wizard
    Jul 16, 2016 at 2:48
  • $\begingroup$ data is any list and I just used 5 as the value to match in the data vector $\endgroup$
    – bill s
    Jul 16, 2016 at 13:53

1 Answer 1


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}

  • 4
    $\begingroup$ ...or just use Nearest[data -> Automatic, val, 1][[1]]. $\endgroup$ Jul 15, 2016 at 23:28
  • $\begingroup$ @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 $\endgroup$
    – m_goldberg
    Jul 16, 2016 at 1:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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