0

I'm trying to set up a filter in Python, and I am stuck in a basic stuff.

This is the function that I have to implement:

y[n] = (1 − λ) · x[n] + λ · y[n − 1]

I'm reading an m file and applying the filter.

Here's the code:

import sys
import numpy as np
import matplotlib.pyplot as plt

y = np.loadtxt('acs712_192us.m')
size = len(y)

x = np.arange(0, size)

out = []

lamb = 0.9 

for i in range(0, len(y)):
    out.append(((1-lamb) * y[i]) + (lamb * out[i - 1]))

plt.plot(x, y)
plt.plot(x, out)
plt.show()

When I run this program, get the following error:

File "main_LI.py", line 15, in out.append(((1-lamb) * y[i]) + (lamb * out[i - 1])) IndexError: list index out of range

I know i can't access out[-1] position (in the first loop), maybe is this the problem?

Anyone have any tips?

Thank you guys!

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
Matheus Bernardi
  • 151
  • 1
  • 3
  • 16

2 Answers2

1

First, you can use negative indexes in Python. The problem is that you are providing an index that does not exist.

out initially is an empty list, so the problem is that you are trying to access an index that does not exist in the first iteration:

import sys
import numpy as np
import matplotlib.pyplot as plt

y = np.loadtxt('acs712_192us.m')
size = len(y)

x = np.arange(0, size)

out = []

lamb = 0.9 

for i in range(len(y)):
    if i == 0:
       out.append(value) # value is what you want out[0] to be
    else:
        out.append(((1-lamb) * y[i]) + (lamb * out[i - 1]))

plt.plot(x, y)
plt.plot(x, out)
plt.show()
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
0

You can use list comprehension to do this pretty easily.

l = 0.9
x = np.arange(0, 10)
filtered = [x[i] if i == 0 else (1-l)*x[i] + l*x[i-1] for i in range(0,len(x))]

>>> print(filtered)
[0, 0.09999999999999998, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1000000000000005, 7.1, 8.1]

is this the output you expect?

Grant Williams
  • 1,469
  • 1
  • 12
  • 24