1
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ No, x should be arbitrary. For some reason extracting to a delayed function makes it work albeit with errors $\endgroup$
    – Adam
    Sep 22 at 5:20
  • $\begingroup$ Perhaps f[x_?NumericQ] := First@Nearest[Range@9 -> "Distance", x]? $\endgroup$
    – Greg Hurst
    Sep 22 at 14:52

1 Answer 1

3
$\begingroup$
$Version

(* "13.3.1 for Mac OS X ARM (64-bit) (July 24, 2023)" *)

Clear["Global`*"]

Nearest is already doing a minimization, FindMinimum is not needed.

First@Nearest[Range[9], 5.6]

(* 6 *)

To do a minimization with distance,

ArgMin[{EuclideanDistance[{x}, {5.6}], 1 <= x <= 9}, x, Integers]

(* 6 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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