# Extracting values from a list

Consider these lists :

soln = Table[i, {i, -17, 17}];
coordinates = Catenate[Table[{x, y}, {y, -2, 2}, {x, -3, 3}]];
solnlist = MapThread[{#1[[1]], #1[[2]], #2} &, {coordinates, Chop[soln]}];


solnlist, in my case, is a list of solution placed against coordinates. I want to extract the values given the coordinates. For this purpose, I made a function:

u[x_, y_] := Catch[
Do[
sol = solnlist[[o]]; If[sol[[1]] == x && sol[[2]] == y, Break[]],
{o,Length[solnlist]}
];
Throw[sol[[3]]]
];


This function does the work, that is, it gives me the value at a point $$(x,y)$$ from the solnlist. However, when the length of solnlist is large, it is a bit slow process. I have a bigger code where I am using such a function inside a loop. The loop takes a lot of time to execute. Is there any faster way to perform such an extraction process?

• Cases[solnlist, {-1, 2, f_} :> f] but you could also do ClearAll[solnlist]; MapThread[(solnlist[#1[[1]], #1[[2]]] = #2) &, {coordinates, Chop[soln]}]; solnlist[-1, 2]
– Kuba
Sep 26, 2018 at 13:38
• Could use Nearest[]: nf = Nearest[Thread[coordinates -> soln]]; u[x_, y_] := First[nf[{x, y}]]. Interpolation[] is also a possibility. Sep 26, 2018 at 13:49
• Thank you all. These functions work much faster than mine. Sep 27, 2018 at 8:06

This seems like a perfect job for Association:

assoc = AssociationThread[coordinates, soln];


Then, to find the value associated with a single coordinate:

assoc[{1, 2}]


15

To find the values associated with multiple coordinates:

Lookup[assoc, {{1,2}, {-1,2}}]


{15, 13}