2 correct code to use Module; add nf to localization edited Jun 19 '15 at 9:04 Mr.Wizard♦ 235k3030 gold badges488488 silver badges10901090 bronze badges You can speed it up by only invoking the NearestFunction once: KPosition3[x_, y_] := Block[Module[{step0, step1, nf}, step0 = Thread[x -> Range[1, Length@x, 1]]; nf = Nearest[step0]; step1 = nf[#, y] & /@ x];  Running your three timing tests gives: {0.003057, 0.004344, 0.051009}  You can speed it up by only invoking the NearestFunction once: KPosition3[x_, y_] := Block[{step0, step1}, step0 = Thread[x -> Range[1, Length@x, 1]]; nf = Nearest[step0]; step1 = nf[#, y] & /@ x];  Running your three timing tests gives: {0.003057, 0.004344, 0.051009}  You can speed it up by only invoking the NearestFunction once: KPosition3[x_, y_] := Module[{step0, step1, nf}, step0 = Thread[x -> Range[1, Length@x, 1]]; nf = Nearest[step0]; step1 = nf[#, y] & /@ x];  Running your three timing tests gives: {0.003057, 0.004344, 0.051009}  1 answered Jun 18 '15 at 15:18 bill s 56.4k33 gold badges8080 silver badges161161 bronze badges You can speed it up by only invoking the NearestFunction once: KPosition3[x_, y_] := Block[{step0, step1}, step0 = Thread[x -> Range[1, Length@x, 1]]; nf = Nearest[step0]; step1 = nf[#, y] & /@ x];  Running your three timing tests gives: {0.003057, 0.004344, 0.051009}