3
$\begingroup$

I would like to know if a list has repeated consecutive values above a threshold. Lets say for this example the threshold is 5.

list={0, 0, 1, 2, 3, 3, 4, 2, 1, 2, 0, 2, 6, 7, 6, 5, 4, 3, 3, 4, 6, 2, 7, 6, 5, 3, 5, 4, 5, 2, 2, 1, 2, 4, 3, 1, 1, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 4, 3, 0, 1, 2}

because of the run 6, 7, 6, and 7, 6,the function should return True or 1 or some indication that consecutive values in the list are above the threshold.

If the threshold is 6 the function would yield False or 0 as there are no consecutive values above 6.

This code fails

Select[Split[list], First[#] > 5 && Length[#] > 1 &, Infinity]

The Split only works for consecutive values of the same value where I need it to split for consecutive values above a threshold.

I tried SplitBy but my pattern is incorrect.

SplitBy[list, Repeated[#] > 5 &]

I understand that neither of these functions above will give True or 1 but once the pattern is correct, taking it to the True or 1 is easy.

$\endgroup$
6
$\begingroup$

Fundamental operation:

t = 5;        
us = UnitStep[list - (t+1)];

(* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, \
 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)

Then look for sequential ones by any method:

us*list // Differences // FreeQ[1] // Not

MatchQ[us, {___, 1, 1, ___}]

Max @ ListConvolve[{1, 1}, us] > 1
$\endgroup$
  • $\begingroup$ Thank you. I'm so grateful. I would have never approached the problem in this way. I was killing myself on finding the correct pattern. $\endgroup$ – Ray Troy Jan 20 '17 at 20:50
  • $\begingroup$ you could directly use MatchQ on the list as MatchQ[list, {___, x_Integer /; x > #, y_Integer /; y > #, ___}] &@5 (I guess the above performs better though) $\endgroup$ – george2079 Jan 20 '17 at 21:45
  • $\begingroup$ I think Clip[list, {t+1, t}, {0, 1}] is slightly faster than UnitStep[list - (t+1)]. $\endgroup$ – Carl Woll Jan 20 '17 at 22:08
  • $\begingroup$ @CarlWoll I don't believe that I was aware that in the second parameter of Clip min could be larger than max. However on my system UnitStep is several times faster than your Clip expression. $\endgroup$ – Mr.Wizard Jan 20 '17 at 23:02

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.