0
0
Signal Processingdata~5 mins

IIR filter implementation in Signal Processing

Choose your learning style9 modes available
Introduction

An IIR filter helps to remove unwanted parts of a signal, like noise, by using past inputs and outputs.

You want to clean audio recordings by reducing background noise.
You need to smooth sensor data in a wearable device.
You want to extract a specific frequency range from a signal.
You want to reduce sudden spikes in temperature readings.
You want to process real-time signals efficiently with less memory.
Syntax
Signal Processing
y[n] = (b0 * x[n]) + (b1 * x[n-1]) + ... - (a1 * y[n-1]) - (a2 * y[n-2]) - ...

x[n] is the current input sample.

y[n] is the current output sample.

Coefficients b are for input, a for output feedback.

Examples
This example uses one past input and one past output to calculate the current output.
Signal Processing
y[n] = 0.5 * x[n] + 0.5 * x[n-1] - 0.3 * y[n-1]
This uses two past inputs and two past outputs for a smoother filter effect.
Signal Processing
y[n] = 0.2 * x[n] + 0.2 * x[n-1] + 0.2 * x[n-2] - 0.4 * y[n-1] - 0.1 * y[n-2]
Sample Program

This code creates a noisy sine wave and applies a simple IIR low-pass filter to reduce noise. The plot shows the original noisy signal and the smoother filtered signal.

Signal Processing
import numpy as np
import matplotlib.pyplot as plt

# Sample input signal: noisy sine wave
fs = 100  # Sampling frequency
f = 5     # Signal frequency
t = np.arange(0, 1, 1/fs)
x = np.sin(2 * np.pi * f * t) + 0.5 * np.random.randn(len(t))

# IIR filter coefficients (simple low-pass)
b = [0.2929, 0.2929]  # feedforward coefficients
a = [-0.4142]         # feedback coefficients

# Initialize output array
y = np.zeros_like(x)

# Apply IIR filter
for n in range(len(x)):
    x_n = x[n]
    x_n_1 = x[n-1] if n-1 >= 0 else 0
    y_n_1 = y[n-1] if n-1 >= 0 else 0
    y[n] = b[0]*x_n + b[1]*x_n_1 - a[0]*y_n_1

# Plot input and filtered output
plt.plot(t, x, label='Noisy Input')
plt.plot(t, y, label='Filtered Output')
plt.legend()
plt.xlabel('Time (seconds)')
plt.title('IIR Filter Example')
plt.show()
OutputSuccess
Important Notes

IIR filters use feedback, so past outputs affect current output.

Be careful with coefficients to keep the filter stable.

Initial past values are often set to zero at the start.

Summary

IIR filters use past inputs and outputs to process signals.

They are good for real-time filtering with less memory.

Choosing correct coefficients is important for good results.