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]
nf = Nearest[...data...]
outside theMinimize
first, then using thenf
inside the minimize for performance reasons, to avoid repeatedly calculating the acceleration structure while doing the minimization. $\endgroup$