title: Finding first samples greater than a threshold value efficiently in Python (and MATLAB comparison)
body: <p>Instead of finding all the samples / data points within a list or an array which are greater than a particular <code>threshold</code>, I would like to find only the first samples where a <code>signal</code> becomes greater than a <code>threshold</code>. The signal might cross the threshold several times. For example if I have an example signal:</p>
  
  <pre><code>signal = [1, 2, 3, 4, 4, 3, 2, 1, 0, 3, 2, 1, 0, 0, 1, 1, 4, 8, 7, 6, 5, 0]
  </code></pre>
  
  <p>and a <code>threshold = 2</code>, then </p>
  
  <pre><code>signal = numpy.array(signal)
  is_bigger_than_threshold = signal &gt; threshold
  </code></pre>
  
  <p>would give me all values in <code>signal</code>which are greater than <code>threshold</code>. 
  However, I would like to get only the first samples whenever signal becomes greater than threshold. Therefore, I am going through the whole list and make boolean comparisons like</p>
  
  <pre><code>first_bigger_than_threshold = list()
  first_bigger_than_threshold.append(False)
  for i in xrange(1, len(is_bigger_than_threshold)):
      if(is_bigger_than_threshold[i] == False):
          val = False
      elif(is_bigger_than_threshold[i]):
          if(is_bigger_than_threshold[i - 1] == False):
              val = True
          elif(is_bigger_than_threshold[i - 1] == True):
              val = False
      first_bigger_than_threshold.append(val)
  </code></pre>
  
  <p>This gives me the result I was looking for, namely</p>
  
  <pre><code>[False, False, True, False, False, False, False, False, False, True, False, False, False,   
  False, False, False, True, False, False, False, False, False]
  </code></pre>
  
  <p>In MATLAB I would do similarily</p>
  
  <pre><code>for i = 2 : numel(is_bigger_than_threshold)
      if(is_bigger_than_threshold(i) == 0)
          val = 0;
      elseif(is_bigger_than_threshold(i))
          if(is_bigger_than_threshold(i - 1) == 0)
              val = 1;
          elseif(is_bigger_than_threshold(i - 1) == 1)
              val = 0;
          end
      end
      first_bigger_than_threshold(i) = val;
  end % for
  </code></pre>
  
  <p>Is there a more efficient (faster) way to perform this calculation? </p>
  
  <p>If I generate data in Python, e.g.</p>
  
  <pre><code>signal = [round(random.random() * 10) for i in xrange(0, 1000000)]
  </code></pre>
  
  <p>and time it, calculating these values took <code>4.45</code> seconds. If I generate data in MATLAB</p>
  
  <pre><code>signal = round(rand(1, 1000000) * 10);
  </code></pre>
  
  <p>and execute the program it takes only <code>0.92</code> seconds. </p>
  
  <p>Why is MATLAB almost 5 times quicker than Python performing this task?</p>
  
  <p>Thanks in advance for your comments! </p>