In this assignment you will write a custom filtering function in Matlab and use it to process signals through filters (linear, time-invariant, causal, stable systems). You will implement both finite and infinite impulse response filters (both FIR and IIR). The
From a numerical point of view, the terms convolution and filtering both refer to processing a signal through a linear, time-invariant (LTI) system. The key difference between the operations of convolution and filtering is the time when the samples of the input signal are available. In convolution, all samples of the input signal are assumed known and available at the time the convolution is computed and convolution produces all the samples of the output signal. Convolution is a array-in/array-output computational process. Filtering processes the input signal samples one at a time and produces the output samples one at a time. Thus filtering is appropriate for real-time deployments of LTI systems. Filtering is a sample-in/sample-out computational process.
Implement FIR filter function and use it to apply filters to signals. Design various types of filters.
Implement IIR filter function and use it to apply filters to signals. Design various types of filters.
Difference equations provide a general description of the input-output relationship for LTI systems in the time-domain. If the input and output are given by
where
Before moving on, observe that the left and right-hand sides of
Thus, the most general form of an LTI systems equates the convolution of input and output with two other fixed sequences.
"Solving" the difference equation is how the output is computed. To illustrate the process, let us consider the special case where
We generally assume
Now solve for
We see that the output
These same steps can be followed for the general case and we may solve
where we assume zero initial conditions
The first summation in
We see that the
Your job is to write a Matlab function that implements an FIR filter. There are two inputs: (1) an array
The function must manage a buffer of internal memory to hold the current and past samples of the input signal in order to compute the current sample
The table above illustrates the movement of data over time through the internal memory of the FIR filter. The top row of the filter contains the impulse response sequence
A Matlab function that performs filtering must implement the movement of data through a memory buffer as described above. In Matlab, the "persistent" keyword may be used inside a function to create a local variable that persists across subsequent calls to the function. An example appears below.
function y = myFIRfilter(b,x)
persistent z; % Persistent internal filter memory
if isempty(z)
z = zeros(size(b)); % Initialize to zero
end
% Inputs
% b = [b[0], b[ 1], b[ 2], b[ 3]]
% x = x[n] = the current input sample
% Internal memory before this function call
% z = [x[n-1], x[n-2], x[n-3], x[n-4]]
% Internal memory after this function call
% z = [x[n ], x[n-1], x[n-2], x[n-3]]
% Shift data in buffer and write in the new input sample
... % Right shift buffer
... % Put new input sample into the buffer
% Compute the filter output
y = ... % Point-by-point multiply and accumulate
Your assignment is to finish writing the myFIRfilter
function. Do not use built-in functions or vector operations.Use for
loops where needed.
IIF filters implement the difference equation in
As in the FIR case, an IIR filter allocates internal memory which is partitioned into two parts: one to hold the input data history
When a new input sample
The Matlab code below illustrates how to allocate and initialize a pair of buffers: one for input history and one for output history.
function y = myIIRfilter(b,a,x)
persistent zx zy; % Persistent internal filter memory
if isempty(zx)
zx = zeros(size(b)); % Initialize input buffer to zero
zy = zeros(size(a)); % Initialize output buffer zero
end
% Inputs
% b = [b[0], b[1], ..., b[M-1]] array of feed forward coefficients
% a = [a[0], a[1], ..., a[N-1]] array of feedback coefficients
% x = x[n] = the current input sample
% Outputs
% y = y[n] = the current output sample
% Shift data in buffer and write in the new input sample
... % Right shift buffers
... % Put new input sample into the input buffer
% Compute the filter output
y = ... % Point-by-point multiply and accumulate
... % Put new output sample into the output buffer
Your assignment is to finish writing the myIIRfilter
function. Do not use built-in functions or vector operations.Use for
loops where needed.
FIR and IIR filter design are extensive topics in their own right. In this assignment, we will use a simple recipe to design FIR filters.
The following procedure designs the impulse response for a low-pass filter operating at a sample rate of
% Filter Specification
Fs = 8000; % samples/second
% Cut off frequencies
Fpass = 1000; % Hz
Fstop = 1500; % Hz
% Filter order
N = 101; % Length of filter impulse response (odd integer)
% FIR Filter Design Procedure
fpass = Fpass/Fs;
fstop = Fstop/Fs;
f1 = (fstop + fpass)/2;
f2 = (fstop - fpass)/2;
L = (N-1)/2;
n = [-L:L];
h = (sin(2*pi*f1*n) .* sin(2*pi*f2*n)) ./ ((pi*n) .* (2*pi*f2*n));
h(L+1) = 2*f1;
% Plot magnitude response
[H,F] = freqz(h,1,2^14,Fs); % Compute frequency response
subplot(211);
plot(F,abs(H),'LineWidth',2); % Plot magnitude response [linear]
xlabel('Frequency [Hertz]');
ylabel('Magnitude [linear]');
xlim([0 Fs/2]);
grid on;
subplot(212);
plot(F,20*log10(abs(H)),'LineWidth',2); % Plot magnitude response [dB]
xlabel('Frequency [Hertz]');
ylabel('Magnitude [dB]');
ylim([-80 5]); xlim([0 Fs/2]);
grid on; shg;
This script uses the freqz
Matlab function to compute the frequency response of the FIR filter. This filter has a trapazoidal-shaped magnitude response as can be seen in the linear magnitude response plots below. It is flat in the pass band
The impluse response (shown below) has a sinc-like shape.
You can modify this filter design script by changing the pass and stop band edge frequencies and by changing the filter order
Consider two low pass filters designed to have the trapazoidal response above. Suppose the two filters have the frequencies characteristics shown in the table below.
LPF 1 (narrow) | LPF 2 (wide) |
---|---|
Let
The magnitude responses of
The filter with impulse response
The output is equal to the input. This filter passes everything!
We can combine an all pass filter
To make this work, the delta function has to "line up" with the sinc function main lobe in the low pass filter. We'll see why this is the case later on in the course. For now, consider the Matlab code below to make this work.
L = 50; N = 2*L+1; % Odd integer
n = [-L:L];
% Design LPF
f1 = 0.125; f2 = 0.025;
hlpf = (sin(2*pi*f1*n) .* sin(2*pi*f2*n)) ./ ((pi*n) .* (2*pi*f2*n));
hlpf(L+1) = 2*f1;
% Design all pass filter
hall = zeros(size(hlpf));
hall(L+1) = 1; % This is the "delta"
% Design HPF
hhpf = hall - hlpf;
% Compute frequency response
[Hhpf,F] = freqz(hhpf,1,2^14,1);
% Visualization
figure();
subplot(211);
stem(n+L,hlpf,'LineWidth',2);
xlabel('Index');
ylabel('Amplitude');
title('LPF Impulse Response')
grid on;
subplot(212);
stem(n+L,hall,'LineWidth',2);
xlabel('Index');
ylabel('Amplitude');
title('All Pass Impulse Response (delta function)')
grid on;
figure();
plot(F,abs(Hhpf),'LineWidth',2);
xlabel('Frequency');
ylabel('Magnitude [linear]');
title('Magnitude Response of High Pass Filter');
grid on;
shg;
Here is a plot of the impulse responses of the low pass and all pass filters. Can you see that the delta in the all pass filter "lines up" with the main lobe of the low pass filter impulse response?
Here is a plot of the high pass filter magnitude response. Can you see that it stops low frequencies and passes high frequencies? Hence the name high-pass filter.
Given the principles described here, how would you design a band-stop filter?
Matlab has several built-in IIR filter design procedures. We will learn about these later in the course. In this lab assignment, several IIR filter designs will be given.
The web page Shelving Filter gives the difference equation for a low-shelf shelving filter with
A notch filter may be designed as follows for processing data sampled at rate
b = [1, -2*cos(omega_n), 1]; a = [1, -2*q*cos(omega_n), q^2];
The notch filter has the magnitude response shown below. It was designed to have a notch at 800 Hz and a sample rate of 8000 Hz. The reason for calling this a notch filter is clear from the magnitude response. It has unity gain across all frequencies except for those frequencies near the notch frequency where it has a gain of zero. If this filter was applied to a song with a note at 800 Hz, this filter would remove those notes completely.
IIR filters have a wide variety of applications. IIR filters can be designed to exhibit excellent frequency response characteristics. Designing other types IIR filters will be considered later in the course.
FIR Filtering
Complete the FIR filtering function and turn in a printout of your code. Do not use built-in functions or vector operations. Use for
loops where needed. Write the filtering function using a single for loop.
Let the impulse response be
Let the impulse response be
a. Compute the filter output
b. Using the freqz
function, plot the magnitude response assuming the sample rate is
c. Using the magnitude response, explain why the steady state output is zero.
Design a band-stop filter by combining all-pass and low-pass filters.
a. Show how to compute the impulse response.
b. Make a plot of the filter magnitude response.
IIR Filtering
Complete the IIR filtering function and turn in a printout of your code. Do not use built-in functions or vector operations. Use for
loops where needed. Write the filtering function using a single for loop for the feed forward section and a single for loop for the feedback section.
Use the filter coefficients for the shelving filter and process the signal on the shelving filter web page. Use the original audio as the input signal rather than the whole song.
a. Make spectrogram plots of the input and output to illustrate that the shelving filter performs as expected.
b. Using the freqz
function, plot the filter magnitude response using the sample rate in the audio file.
c. What audible effect does the shelving filter impart to the signal? How does the magnitude response of the shelving filter predict this result?
Design a notch filter to cut out the note Bb4=A#4 which has a frequency of 466.16 Hz (https://pages.mtu.edu/~suits/notefreqs.html). This note occurs multiple times in the introduction to the song "Fireflies" by Owl City. Here is an audio clip. To design the notch filter, you will need the audio sample rate and that can be obtained from the audio file using the Matlab command shown below. Process the audio clip using your IIR filtering code and make spectrogram plots of the input signal
[x,Fs]=audioread('fireflyintro.wav'); % Fs = 44,100 samples/second