Home > Enterprise >  Examining the impulse response of a given system ( Python )
Examining the impulse response of a given system ( Python )

Time:09-22

I have written a code which takes a vector as input ( the impulse ) and should return another vector ( the 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?

CodePudding user response:

You simply need to indent your gas 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

CodePudding user response:

I have managed to fix this code by:

  • Making sure the indentation is consistent and sensible
  • Defining g inside the response function before the for-loop (otherwise you will re-initialise g during every iteration of the loop)
  • After the end of the function definition, define 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.]
  • Related