[SciPy-user] Sample and hold

Robert Kern robert.kern at gmail.com
Sat Jun 3 14:40:44 CDT 2006

Martin Spacek wrote:
> Martin Spacek wrote:
>>I've got an array of irregularly spaced data points, like this:
>>               *                             *
>>                   *
>>           *                                      *
>>*                      *
>>                                         *
> To be more accurate, I've actually got two arrays of the same length. 
> One to hold the values, the other to hold the timepoints.

Okay, let's suppose that these arrays are y and x respectively and that x is
already sorted.

# Untested!

import numpy as np

def sample_and_hold(x, y, newx):
    idx = np.searchsorted(x, newx) - 1

    # Handle the cases where newx is smaller than the first point.
    idx = np.where(idx < 0, 0, idx)

    return y[idx]

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the SciPy-user mailing list