0
$\begingroup$

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?

$\endgroup$
3
  • $\begingroup$ 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] $\endgroup$
    – Kuba
    Sep 26, 2018 at 13:38
  • $\begingroup$ Could use Nearest[]: nf = Nearest[Thread[coordinates -> soln]]; u[x_, y_] := First[nf[{x, y}]]. Interpolation[] is also a possibility. $\endgroup$ Sep 26, 2018 at 13:49
  • $\begingroup$ Thank you all. These functions work much faster than mine. $\endgroup$ Sep 27, 2018 at 8:06

1 Answer 1

4
$\begingroup$

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}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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