3
$\begingroup$

I have a large list of real numbers, that vary between a maximum and a minimum. For the sake of an example: megalist=RandomReal[{-5, 5}, 10^4]. Now, I have a much smaller list such as minilist={0.3,1,-0.5} and I would like to see whether minilist is contained inside megalist, within a certain tolerance on each component of the list, let us say +-0.1. In other words: whether megalist contains a sublist such as: {0.3+-0.1,1+-0.1,-0.5+-0.1}. And, if it exists, I would like to get its position. Any help is appreciated.

$\endgroup$

1 Answer 1

3
$\begingroup$

You can create a list of subsequences of length 3 using Partition and use Nearest with distance function ChessboardDistance (thanks: @CarlWoll ):

nF = Nearest[Partition[megalist, 3, 1] -> {"Element", "Index"}, 
  DistanceFunction -> (Norm[# - #2, Infinity] &)]

enter image description here

The function nF[x] returns the subsequences of megalist and their positions nearest x.

There are no subsequences within distance .1 of minilist:

nF[minilist, {All, .1}]
{}

There are 2 within distance .25:

nF[minilist, {All, .2}]
{{{0.473371, 1.18655, -0.703937}, 4590}, 
{{0.473238, 1.2483, -0.690072}, 6032}}
$\endgroup$
2
  • 2
    $\begingroup$ I think you can use ChessboardDistance instead. $\endgroup$
    – Carl Woll
    Commented Mar 31, 2021 at 19:02
  • $\begingroup$ Of course! Thank you @Carl. Updated. $\endgroup$
    – kglr
    Commented Mar 31, 2021 at 19:11

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.