[SciPy-user] Sample and hold
John Hunter
jdhunter at ace.bsd.uchicago.edu
Sat Jun 3 14:35:38 CDT 2006
>>>>> "Martin" == Martin Spacek <scipy at mspacek.mm.st> writes:
Martin> Martin Spacek wrote:
>> Hi,
>>
>> I've got an array of irregularly spaced data points, like this:
>>
>> * * * * * * * *
Martin> To be more accurate, I've actually got two arrays of the
Martin> same length. One to hold the values, the other to hold
Martin> the timepoints.
I learned from my matlab days that cumsum is a useful workhorse when
trying to code things up w/o loops. This example takes the first diff
of the sample data and inserts into the resampled vector at the right
points, assuming your time data is sorted. When you do a cumsum, the
zeros of the target vector contribute nothing and the diff is summed
up to recover the original signal between sample points.
import numpy as n
# some random sample data
N = 20
t = n.cumsum(n.rand(N))
x = n.rand(N)
dx = n.zeros(x.shape[0], n.Float)
# create a first diff vector so that our cumsum trick can
# be used below
dx[0] = x[0]
dx[1:] = n.diff(x)
# resampled vectors
dt = 0.01
ts = n.arange(0, max(t)+dt, dt)
xs = n.zeros( ts.shape, n.Float)
# find out where to insert our (diffed) sample points
# into the target vector using search sorted
ind = n.searchsorted(ts,t)
xs[ind] = dx
xs = n.cumsum(xs)
from pylab import figure, show
fig = figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, x, 'o')
ax1.plot(ts, xs, '-')
show()
More information about the SciPy-user
mailing list