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]
.
One may use an IIR filter to do this.
scipy.signal.lfilter
is the correct choice in this case.For my specific constants, the following code snippet would do -
Here,
signal.lfiltic
is used to to specify the initial conditions.Just by playing around with
cumsum
:First a little function to produce your expression iteratively:
Make a small test array (I first worked with
np.arange(10)
)and with a different
C
:I first tried:
and then realized that the
x[:-2]
term wasn't needed:If I was back in school I probably would have discovered this sort of pattern with algebra, rather than a numpy trial-n-error. It may not be general enough, but hopefully it's a start.