I have a problem, where I generate two lists of points, and I want to see which points are the closest. If I just want to find which ones are exactly the same, I can use Intersection[list1,list2]
. I even know that I can use SameTest
to define the test. As an example, I could use
testlist1 = Table[k, {k, 0, 25, 0.25}];
testlist2 = Table[k, {k, 0, 49, 0.49}];
Intersection[testlist1, testlist2]
and I get the result
{0., 12.25, 24.5}
I can use SameTest
to define a closeness function that will test if the two elements are very close:
testlist1 = Table[k, {k, 0, 25, 0.25}];
testlist2 = Table[k, {k, 0, 49, 0.49}];
Intersection[testlist1, testlist2,
SameTest -> (Abs[#1 - #2] <= 0.01 &)]
and now I get the elements
{0., 0.5, 11.75, 12.25, 12.75, 24., 24.5}
For my problem, I have two lists that will always contain at least one pair of corresponding points between the list, although they may not always be equal, and the difference will not always be the same; and there may also be more than one set of corresponding points. I've generated the following code, which (mostly) works, but is slow, and depends on a new function introduced in 10.3 which is labeled as [[EXPERIMENTAL]]
, specifically, the function DistanceMatrix
testlist1 = Table[k, {k, 0, 25, 0.25}];
testlist2 = Table[k+.0057, {k, 0, 49, 0.49}];
Intersection[testlist1, testlist2,
SameTest -> (Abs[#1 - #2] <= Min[DistanceMatrix[testlist1,testlist2]] &)]
which returns
{0.5}
Which is (mostly) correct. See bullet 3 for why I'm unsatisfied with the answer.
Now my problems are these:
- This seems inefficient, and runs quite slowly
- This depends on an experimental function, which is only available in the latest version of Mathematica (10.3)
- This returns the element in the first list called in
Intersection
corresponding to theSameTest
returning true. Rather, I'd like it to return the matching elements from both lists. A dirty solution would be to callIntersection
twice, with the lists swapped in the slots, but for a solution that already seems inefficient, I'd rather not call it multiple times.
So: is there a better way to do this? Even returning the current result would be ok, if not ideal. Ideally, a list of pairs would be returned, with each pair corresponding to the matching set.
Pick
method solves both intersection and complement $\endgroup$