Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a large table of triplets whose structure is:

list=Table[{a,b, RandomReal[]}, {a,1,100}, {b,1,100}]

I would like to search through the list by looking for the closest entry labeled by {a,b} to a given input {x,y} and return the associated third item in the triplet. To give an example, if I have

{x, y} = {10.2, 5.1}

I would like to return the triplet

{10, 5, c}

Where c is the associated random real in the table. I have tried using Nearest, but the structure of the table does not seem compatible with search.

share|improve this question
Hi, I tried to improve the formatting: To format code blocks, you have to surround them with blank lines, in addition to indenting. Inline code is enclosed in backticks. You can look at the edits to see. :) – Michael E2 Feb 23 '14 at 13:18
up vote 7 down vote accepted

Here's a way to use Nearest:

SeedRandom[1]; (* for reproducibility; omit in application *)

list = Table[N@{a, b, RandomReal[]}, {a, 1, 100}, {b, 1, 100}];
flat = Flatten[list, 1];

nf = Nearest[flat[[All, 1 ;; 2]] -> flat]
   NearestFunction[{10000, 2}, <>]

nf[{10.2, 5.1}]
   {{10., 5., 0.588169}}

Note: I converted the OP's integer coordinates to Real with N, so that list and flat would be packed arrays for efficiency, in case the table gets much bigger. It doesn't really make a difference on the OP's example. Omit the N if desired.

share|improve this answer
Could you clarify how function nf works? I see what you are doing with Flatten but I don't understand how nf processes its argument. – Whelp Feb 23 '14 at 13:20
@Whelp It's the third synopsis on the documentation page. Think of the rule (->) as mapping the LHS -> RHS (element by element). Nearest will find the nearest element in the LHS and return the corresponding element of the RHS. – Michael E2 Feb 23 '14 at 13:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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