Impulse response with initial conditions on python using filter/filtic

Viewed 383

I am trying to get impulse response using filter/filtic at rest and initial conditions.


import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

n = np.arange(0,8,1)

h = np.array([1,0,0,0,0,0,0,0]) #unit impulse signal

a = np.array([1,1/2,1/4])
b = np.array([1,2,1/4])   #a & b are filter coeficients

plt.figure(1)

y1 = signal.lfilter(b,a,h) 
plt.stem(n,y1)
plt.grid()
plt.xlabel("n")
plt.ylabel("Impulse response")
plt.title("Impulse response with initial rest")

## With initial condition

x1 = np.array([-1,0])
x2 = np.array([-1/2,1])

z1 = signal.lfiltic(b,a,x1,x2)
y11 = signal.lfiltic(b,a,h,z1)

plt.figure(2)
plt.stem(n,y11)

While I got impulse response at rest, but i am getting an error while using initial conditions. This is the error I am getting

Traceback (most recent call last):

File "C:\Users\Hp.spyder-py3\untitled1.py", line 32, in plt.stem(n,y11)

File "C:\Users\Hp\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 3134, in stem return gca().stem(

File "C:\Users\Hp\anaconda3\lib\site-packages\matplotlib_init_.py", line 1361, in inner return func(ax, *map(sanitize_sequence, args), **kwargs)

File "C:\Users\Hp\anaconda3\lib\site-packages\matplotlib\axes_axes.py", line 2873, in stem stemlines = xlines(

File "C:\Users\Hp\anaconda3\lib\site-packages\matplotlib_init_.py", line 1361, in inner return func(ax, *map(sanitize_sequence, args), **kwargs)

File "C:\Users\Hp\anaconda3\lib\site-packages\matplotlib\axes_axes.py", line 1115, in vlines masked_verts[:, 1, 1] = ymax

File "C:\Users\Hp\anaconda3\lib\site-packages\numpy\ma\core.py", line 3375, in setitem _data[indx] = dval

ValueError: could not broadcast input array from shape (2,) into shape (8,)

Can someone please help me.

1 Answers

When trying to obtain the filter response with initial condition you're using lfiltic two times in a row. You need to use the response from the first lfiltic (z1) in the lfilter command, similarly with what you've done in the first block, but now passing z1 to the zi function parameter.

...
z1 = signal.lfiltic(b,a,x1,x2)
y11 = signal.lfilter(b,a,h,zi=z1)

plt.figure(2)
plt.title("Impulse response with initial condition")
plt.stem(n,y11[0])

filter_with_initial_conditions

Related