1
$\begingroup$

How to use Nearest inside Minimize?

The following returns errors but if # - {a, b} is replaced with # - {1, 2} it works correctly so I guess the errors are due to Nearest not returning numeric outputs.

x = RandomInteger[{-10, 10}, {10, 2}]
y = RandomInteger[{-10, 10}, {10, 2}]
Minimize[(# - Nearest[y, #][[1]] & /@ (# - {a, b} & /@ x))^2 // 
   Flatten // Total, {a, b}]
Clear[x, y]
$\endgroup$
1
  • $\begingroup$ I recommend using nf = Nearest[...data...] outside the Minimize first, then using the nf inside the minimize for performance reasons, to avoid repeatedly calculating the acceleration structure while doing the minimization. $\endgroup$
    – flinty
    Commented Oct 16, 2023 at 11:03

1 Answer 1

4
$\begingroup$
  • Use the ?NumericQ skill.
SeedRandom[1];
x = RandomInteger[{-10, 10}, {10, 2}];
y = RandomInteger[{-10, 10}, {10, 2}]; 
f[a_?NumericQ, 
  b_?NumericQ] := (# - Nearest[y, #][[1]] & /@ (# - {a, b} & /@ 
        x))^2 // Flatten // Total;
 NMinimize[f[a, b], {a, b}]

{83.7, {a -> 0.3, b -> -0.8}}

$\endgroup$

Your Answer

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

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