I have written a code which takes a vector as input (impulse) and should return another vector (impulse response).
import numpy as np
from scipy import signal
y = signal.unit_impulse(8)
def response(y):
for i in range(8):
g = np.zeros(len(y))
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g
print(g)
The signal.unit_impulse(8)
creates a vector with 8 digits, where the first one is 1 and the rest are zero. When I run this, I get NameError: name 'g' is not defined.
Within the function logic I receive a notification Local variable 'g' might be referenced before assignment
. I think these two statements are related somehow. How can I fix this?
You simply need to indent your g
as it is currently not returned by your function.
def response(y):
g = np.zeros(len(y))
for i in range(8):
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g
I have managed to fix this code by:
g
inside the response
function before the for
-loop (otherwise you will re-initialise g
during every iteration of the loop)g
as the output from the response
function when called with y
as the input (if g
is only defined in the scope of your function, then code outside the scope of your function won't have access to it) import numpy as np
from scipy import signal
y = signal.unit_impulse(8)
def response(y):
g = np.zeros(len(y))
for i in range(8):
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g
g = response(y)
print(g)
This code provides the following output:
[ 3. -2. 2. 0. 0. 0. 0. 0.]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.