Kalpesh Krishna Kalpesh Krishna - 29 days ago 8
Python Question

Best way to vectorize operation having input and output history dependence?

My goal is to vectorize the following operation in numpy,

y[n] = c1*x[n] + c2*x[n-1] + c3*y[n-1]


If
n
is time, I essentially need the outputs depending on previous inputs as well as previous outputs. I'm given the values of
x[-1]
and
y[-1]
. Also, this is a generalized version of my actual problem where
c1 = 1.001
,
c2 = -1
and
c3 = 1
.

I could figure out the procedure to add the first two operands, simply by adding
c1*x
and
c2*np.concatenate([x[-1], x[0:-1])
, but I can't seem to figure out the best way to deal with
y[n-1]
.

Answer

One may use an IIR filter to do this. scipy.signal.filter is the correct choice in this case.

For my specific constants, the following code snippet would do -

  from scipy import signal
  inital = signal.lfiltic([1.0001,-1], [1, -1], [y_0], [x_0])
  output, _ = signal.lfilter([1.0001,-1], [1, -1], input, zi=inital)

Here, signal.lfiltic is used to to specify the initial conditions.

Comments