I'm trying to use Nearest
as a function to minimize over: a toy example is
f[z_] := FindMinimum[First@Nearest[Range@9 -> "Distance", x], {x,z}]
An expected result is f[5.6]=6
. I'm aware there are simpler ways to write such a function; the goal is to minimze with Nearest
.
I tried with Unevaluated
and Inactive
in various spots, but no matter what I get the error
The default distance function does not give a real numeric distance when applied to the point pair x and 1.
Then FindMinimum
complains about a nonnumeric function value. It's worth noting that any symbolic call to Nearest
gives the same error; the problem is that FindMinimum
can't inject the parameter.
Question
How can I properly delay the evaluation of Nearest
such that it may be evaluated by FindMinimum
?
Inadvertent solution:
f[x_] := First@Nearest[Range@9 -> "Distance", x]
FindMinimum[Hold@f@X, {X, 5.6}]
This doesn't seem to generalize when I do multidimensional minimizations.
x
should be arbitrary. For some reason extracting to a delayed function makes it work albeit with errors $\endgroup$f[x_?NumericQ] := First@Nearest[Range@9 -> "Distance", x]
? $\endgroup$