6
$\begingroup$

What is the best method to constrain multiple locator points to a set of data? A while back, I needed a program that could perform a linear fit for a specified range of data points. In an effort to create more work for myself, I decided to utilize LocatorPane to define end points for the fit range. The key to this program was constraining both locator points and making them snap-to points along the data set. I was able to cobble together code in Mathematica 10 that did just that (see example):

my example

Recently, I switched to a new version of Mathematica (11.0.1). Now, when I use this code, I get Part errors. Since my code is a bit ridiculous, I think the best option is a rewrite. What is the best method to constrain multiple locator points to a set of data?

I can attach my code if you'd like to take a look, but it's pretty messy.

$\endgroup$
10
$\begingroup$

Use Nearest[]:

pts = {{1.0, 12.}, {1.9, 10.}, {2.6, 8.2}, {3.4, 6.9}, {5.0, 5.9}};
nf = Nearest[pts];

DynamicModule[{loc = pts[[{1, -1}]]}, 
              LocatorPane[Dynamic[loc, (loc = Flatten[nf[#], 1];) &], 
                          ListPlot[pts, Frame -> True]], SaveDefinitions -> True]

locators constrained to a point set

$\endgroup$
  • $\begingroup$ Excellent answer! I used Nearest in my old code, but I was completely unaware that you could use it on its own to generate a "Nearest" function. A few edits here and there and everything is working great. Thanks for the help! $\endgroup$ – msb91880 Oct 5 '16 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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