4
$\begingroup$

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.

$\endgroup$
1
  • 1
    $\begingroup$ 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. :) $\endgroup$
    – Michael E2
    Commented Feb 23, 2014 at 13:18

1 Answer 1

8
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – Whelp
    Commented Feb 23, 2014 at 13:20
  • $\begingroup$ @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. $\endgroup$
    – Michael E2
    Commented Feb 23, 2014 at 13:45

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.