k.munn
k.munn

Reputation: 3

How to apply a difference equation to a numpy array inside for loop

I'm trying to apply a simple difference equation to a numpy array as part of a filtering algorithm. The problem is that python reassigns the numpy variables inside the for loop and thus returns a list of zeros. How to I restructure this code to pass the numpy arrays by reference to the for loop?

def resonant_ladder_filter(vector_in, fc, res):

    fs = 44100 
    fs2 = 2*fs 



    in2 = signal.decimate(vector_in, 2)

    h = signal.firwin(10, 0.5)

    in2 = signal.lfilter(h,1,in2)

    g = 2*np.pi*fc/fs2 

    Gres = res; 

    h0 = g/1.3; h1 = g*0.3/1.3; 

    w = np.array([0, 0, 0, 0, 0])

    wold = np.array([0, 0, 0, 0, 0])

    Gcomp = 0.5; 

    out = np.zeros(len(vector_in))

    out2 = np.zeros(len(in2))

    for n in range(0,len(in2)):
        u = in2[n] - 4*Gres*(wold[4] - Gcomp*in2[n])

        w[0] = np.tanh(u) 


        w[1] = h0*w[0] + h1*wold[0] + (1-g)*wold[1]
        w[2] = h0*w[1] + h1*wold[1] + (1-g)*wold[2]
        w[3] = h0*w[2] + h1*wold[2] + (1-g)*wold[3]
        w[4] = h0*w[3] + h1*wold[3] + (1-g)*wold[4]

        out2[n] = w[4]

        wold = w

    out2 = signal.lfilter(h,1,out2)

    out = signal.decimate(out2, 2)

    return out

This code is essentially written in a matlab style, and doesn't plug and play nicely with python as is. There must be a better, pythonic way to write this, I just can't work that out.

Upvotes: 0

Views: 253

Answers (1)

Joe Ernst
Joe Ernst

Reputation: 179

-- Hi k.munn,

I believe your issue has to do with variable assignment vs. copying.

This line is your problem:

wold = w

Change it to:

wold = w.copy()

It will create a copy of your numpy.array which should resolve your issue.

See the general documentation here: Python docs - copy, or here Numpy docs - copy

Hope this helps!


EDIT:

Running the code surfaced an element assignment issue within the numpy arrays as they are initialised as integer zeros:

w = np.array([0,0,0,0,0])

Changing this to (for wold respectively):

w = np.zeros(5, dtype=np.float64)

Should allow

w[0] = np.tanh(u)

to insert the values correctly.

Upvotes: 1

Related Questions