DIGITAL DIGITAL DIGITAL DIGITAL SIGNAL PROCESSINGSIGNAL PROCESSINGSIGNAL PROCESSINGSIGNAL PROCESSING
COMPUTER SIMULATION LAB
DEPARTMENT OF ELECTRICAL ENGINEERING
Prepared By:
Engr. Faisal Baig
Lecturer (Lab) Electrical,
FUUAST-Islamabad
Name: ____________________________________________
Registration No: ____________________________________
Roll No: ___________________________________________
Semester: _________________________________________
Batch: ____________________________________________
SECTION NO. 1 (Software)
EXPERIMENT NO. 1:
Signals in Matlab (Continuous time & Discrete time)
EXPERIMENT NO. 2:
Discrete Time Systems and its Properties
1) Linearity
2) Time invariant
EXPERIMENT NO. 3:
Impulse Response of a system
1) IIR
2) FIR
EXPERIMENT NO. 4:
DTFT and Properties
EXPERIMENT NO. 5:
Sampling, A/D Conversion and D/A Conversion
EXPERIMENT NO. 6:
System Frequency Transform
Introduction to Digital Filter
EXPERIMENT NO. 7:
Simple Digital Filter
1) IIR
2) FIR
EXPERIMENT NO. 8:
Digital Filter Design
1) FIR
2) Introduction to Widows method
EXPERIMENT NO. 9:
FIR Filter Design using Rectangular Windows method
1) LPF
2) HPF
3) BPF
4) BSF
EXPERIMENT NO. 10:
DIGITAL FILTER STRUCTURE
EXPERIMENT NO. 11:
Design of FIR filters using Matlab commands. EXPERIMENT NO. 12:
Design of IIR filters using Matlab commands
EXPERIMENT NO. 13:
DFT
EXPERIMENT NO. 14:
Interpolation & Decimation
EXPERIMENT NO. 15:
Filter designing by Matlab tools
EXPERIMENT NO. 16:
Design an IIR filter to suppress frequencies of 5 Hz and 30 Hz from given signal
EXPERIMENT NO. 1
SIGNALS IN MATLAB (CONTINUOUS TIME & DISCRETE TIME)
Signals are broadly classified into two classifications:
a. Continuous Time Signals
b. Discrete Time Signals
A continuous time signal will be denoted by x(t), in which the variable t can represent any physical
quantity.
A discrete time signal will be denoted x[n], in which the variable n is integer value. In this lab we will
learn to represent and operate on signals in MATLAB.
1. Continuous Time Signals
For the following: Run the following lines and explain why the plots are different.
Provide the snapshots of the plots for each step given below.
close all, clear all t = 0:2*pi; plot(t,sin(t)) figure t = 0:0.2:2*pi; plot(t,sin(t)) figuret = 0:0.02:2*pi; plot(t,sin(t))
For the last graph, add a title and axis labels with: title('Continuous time signal plot') xlabel('t (Seconds)') ylabel('y(t)')
Change the axis with:
axis([0 2*pi -1.2 1.2])
Put two plots on the same axis t = 0:0.2:2*pi; plot(t,sin(t),t,sin(2*t))
Produce a plot without connecting the points
t = 0:0.2:2*pi; plot(t,sin(t),'.')
Try the following command
t = 0:0.2:2*pi;
plot(t,sin(t),t,sin(t),'g.')
Question 1: What does ‘g’ do?
2. Discrete Time Signals
Use stem to plot the discrete time signals. Provide the snapshots of the step below.
close all clear all n = -10: 10; f = n >= 0; stem(n,f)
3. Elementary sequences in digital signal processing
For each part below, provide an example using any input and also provide the plots of input and
output sequences using subplot.
a. Unit sample sequence
− = , = , ≠
% Generate a vector from -10 to 20 n = -10:20; n0=0; % Generate the unit sample sequence u =n-n0==0; % Plot the unit sample sequence stem(n,u); xlabel( 'Time index n' ); ylabel( 'Amplitude' ); title( 'Unit Sample Sequence' ); axis([-10 20 0 2]);
b. Unit step sequence
− = , ≥ , <
n=-10:30 n0=0; y=n-n0>=0; figure stem(n,y); title('UNIT STEP FUNCTION');
c. Real Valued Exponential sequence
= , ∈
n = 0:35; a = 1.2; K = 0.2; x = K*a.^+n; stem(n,x); xlabel('Time index n'); ylabel('Amplitude'); d. Complex valued exponential sequence
=
c = -(1/12)+(pi/6)*i; K = 2; n = 0:40; x = K*exp(c*n); subplot(2,1,1); stem(n,real(x)); xlabel('Time index n'); ylabel('Amplitude'); title('Real part'); subplot(2,1,2); stem(n,imag(x)); xlabel('Time index n'); ylabel('Amplitude'); title('Imaginary part');
e. Sinusoidal sequence
n = 0:40; f = 0.1; phase = 0; A = 1.5; arg = 2*pi*f*n - phase; x = A*cos(arg); stem(n,x); % Plot the generated sequence axis([0 40 -2 2]); grid; title('Sinusoidal Sequence'); xlabel('Time index n'); ylabel('Amplitude'); axis;
f. Operations on sequence:
• Shifting
In this operation each sample of x(n) is shifted by an amount k to obtain a shifted
sequence y(n)
yn = xn − k
If we let m = n-k, then n = m+k the above operation is given by
ym + k = xm
For this we can use the following code
s=1:100; subplot(2,1,1) stem(s) title('Sequence'); axis([0 100 0 100]); s_new=[zeros(1,10) s]; subplot(2,1,2) stem(s_new); axis([0 100 0 100]); title('Delayed sequence');
• Folding
In this operation each sample of x(n) is flipped around its axis to obtain a folded sequence
y(n)
!" = #−"
For this the following code is shown.
Exercise:
Generate and plot each of the following sequences over the indicated interval. Provide the
scripts used to generate the plots.
Ex.1:
a. $" = 2&" + 2 − &" − 4,−5 ≤ & ≤ 5
b. #" = "[+" − +" − 10] + 10/^−0.3" − 10[+" − 10 − +" − 20], 0 ≤ " ≤ 20
Ex.2:
Let x(n) = 1,2,3,4,5,6,7,6,5,4,3,2,1, Determine and plot the following sequences.
a. #3" = 2#" − 5 − 3#" + 4 b. #4" = #3 − " + #"#" − 2
EXPERIMENT NO. 2
(Discrete Time Systems)
DSP LAB # 3: Discrete Time Systems
To provide an overview of discrete time signals and systems on MATLAB, to analyze various properties
of discrete time systems and verify them on MATLAB.
Introduction:
Mathematically, a discrete-time system is described as an operator T[.] that takes a sequencex(n) called
excitation and transforms it into another sequence y(n) (called response). Discretetime systems can be
classified into two categories i) LTI systems ii) NON-LTI systems. Adiscrete system T[.] is a linear operator
L[.] if and only if L[.] satisfies the principle ofsuperposition, namely
5[ + 66] = 5[] +5[6]
A discrete system is time-invariant if shifting the input only causes the same shift in the output.
A system is said to be bounded-input bounded-output (BIBO) stable if every bounded input produces a
bounded output.
|| < ∞ → |:| < ∞,∀#, !
An LTI system is BIBO stable if and only if its impulse response is absolutely sum able.
<=<>?@ABCB@: ↔ E|F| < ∞
A system is said to be causal if the output at any instant depends only on the present & past values only.
An LTI system is causal if and only if the impulse response is
F = , < 0
1. Linearity and Non-Linearity: We now investigate the linearity property of a causal system of described by the following
equation.
:[] − . G:[ − ] + . HI:[ − 6] = 6. 6[] + 6. J[ − ] + 6. G[ − 6]
Following program simulates the above mentioned equation.
Question 1: Run above program and compare y[n] obtained with weighted input with y[n] obtained by
combining the two outputs y1[n] and y2[n] with the same weights. Are these two sequences equal? Is
this system linear?
Exercise 1: Consider another system described by :*. − :* − 6. + . HI:* − G. = 6. 6*. + 6. J* − J. + 6. G* − I.
:*. − :* − 6. + :* − G. = *. + * − J. + * − G.
:*. − :* − 6. + . HI:* − G. + J:* − I. = *. + . J* − . + 6. G* − J.
Modify given program to compute the output sequences y1[n], y2[n], and y[n] of the above system.
Compare y[n] with y[n]. Are these two sequences equal? Is this system linear?
2. Time-Invariant and Time-Varying Systems:
We next investigate the time-invariance property. Following program simulates following
difference equation
:*. − . G:* − . + . HI:* − 6. = 6. 6*. + 6. J* − . + 6. G* − 6.
Two input sequence x[n] and x[n-D], are generated and corresponding output sequences
y1[n],y2[n] are plotted.
clear all, close all n = 0:40; a = 2; b = -3; x1 = cos(2*pi*0.1*n); x2 = cos(2*pi*0.4*n); x = a*x1 + b*x2; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; ic = [0 0]; % Set zero initial conditions y1 = filter(num,den,x1,ic); % Compute the output y1 [n] y2 = filter(num,den,x2,ic); % Compute the output y2 [n] y = filter(num,den,x,ic); % Compute the output y[n] yt = a*y1 + b*y2; d = y - yt; % Compute the difference output d[n] % Plot the outputs and the difference signal subplot (3,1,1) stem(n ,y); ylabel('Amplitude'); title('Output Due to Weighted Input'); subplot(3,1,2) stem(n,yt); ylabel('Amplitude'); title('Weighted Output'); subplot(3,1,3) stem(n,d); xlabel('Time index n'); ylabel('Amplitude'); title('Difference Signal');
Exercise 2: Consider another system described by:
:*. − :* − . + :* − 6. + . :* − G. = [] + 6. J[ − ] + 6. G[ − I] :[] − :[ − 6]+= [] + . 6[ − 6] + [ − G]
:[] = [] + 6. J[ − J] + 6. G[ − I]
Modify program to simulate the above system and determine whether this system is time-
invariant or not.
3. Linearity and Time-Invariant: (LOOPS)
Using loops to solve the given equation
:[] = [] + [ − ]
close all, clear all n = 0:40; D = 10;a = 3.0;b = -2; x = a*cos(2*pi*0.1*n) + b*cos(2*pi*0.4*n); xd = [zeros(1,D) x]; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; ic = [0 0];% Set initial conditions % Compute the output y[n] y = filter(num,den,x,ic); % Compute the output yd[n] yd = filter(num,den,xd,ic); % Compute the difference output d[n] d = y - yd(1+D:41+D); % Plot the outputs subplot(3,1,1) stem(n,y); ylabel('mplitude'); title('Output y[n]');grid; subplot(3,1,2) stem(n,yd(1:41)); ylabel('Amplitude'); title(['Output Due to Delayed Input x[n , num2str(D ),]']);grid; subplot(3,1,3) stem(n,d); xlabel('Time index n'); ylabel('Amplitude'); title('Difference Signal');grid;
x1=[1 1 2]; x2=[2 2 0]; %for y1 for i=1:3 if(i==1) y1(i)=x1(i); else if(i>1) y1(i)=x1(i)+x1(i-1); end end end %for y2 for i=1:3 if(i==1) y2(i)=x2(i); else if(i>1) y2(i)=x2(i)+x2(i-1); end end end x3=x1+x2; %for y3 for i=1:3 if(i==1) y3(i)=x3(i); else if(i>1) y3(i)= x3(i)+x3(i-1);
end
end
end
y3
y1+y2
if(y3==(y1+y2))
display('System is linear')
end
x1=[1 1 2]; %for y1 for i=1:3 if(i==1) y1(i)=x1(i); else if(i>1) y1(i)=x1(i)+x1(i-1); end end end y1 x2=[0 0 x1] %for y2 for i=1:5 if(i==1) y3(i)=x2(i); else if(i>1) y3(i)=x2(i)+x2(i-1); end end end y3 if(y3(3:5)==y1) display('System is Time invariant') end
Exercise 1: Consider another system described by:
:*. + :* − . = [] + [ − J] :[] = [] + [ − ]
Modify program to simulate the above system and determine whether this system is time-
invariant or not.
EXPERIMENT NO. 3
Impulse Response of System
Impulse Response Computation:
Response of a system to an impulse is called impulse response, two types
• FIR( Finite impulse response)
• IIR (infinite impulse response)
FIR:
In signal processing, a finite impulse response (FIR) filter is a filter whose impulse response (or
response to any finite length input) is of finite duration, because it settles to zero in finite time.
For a discrete-time FIR filter, the output is a weighted sum of the current and a finite number of
previous values of the input. The operation is described by the following equation, which defines
the output sequence y[n] in terms of its input sequence x[n]:
y[n]=b0x(n)+ b1x(n-1)+ b2x(n-2) ……….+ bNx(n-N)
y [n]=∑bi x(n-i)
where:
• is the input signal,
• is the output signal,
• are the filter coefficients, also known as tap weights, that make up the impulse
response,
is the filter order; an th-order filter has terms on the right-hand side. The in
these terms are commonly referred to as taps, based on the structure of a tapped delay line that in
many implementations or block diagrams provides the delayed inputs to the multiplication
operations. One may speak of a 5th order/6-tap filter, for instance.
Properties: An FIR filter has a number of useful properties which sometimes make it preferable to an infinite
impulse response (IIR) filter. FIR filters:
• Require no feedback. This means that any rounding errors are not compounded by summed
iterations. The same relative error occurs in each calculation. This also makes implementation
simpler.
• Are inherently stable. This is due to the fact that, because there is no required feedback, all the
poles are located at the origin and thus are located within the unit circle (the required condition
for stability in a Z transformed system).
• They can easily be designed to be linear phase by making the coefficient sequence symmetric;
linear phase, or phase change proportional to frequency, corresponds to equal delay at all
frequencies. This property is sometimes desired for phase-sensitive applications, for example
data communications, crossover filters, and mastering.
Impulse response:
The impulse response can be calculated if we set in the above relation, where
is impulse. The impulse response for an FIR filter then becomes the set of coefficients , as follows
for to .
FIR filters are clearly bounded-input bounded-output (BIBO) stable, since the output is a sum of a
finite number of finite multiples of the input values, so can be no greater than times the
largest value appearing in the input.
:*. = 6. 6*. * . * 6.
Exercise 1: Compute Impulse Response
:*. 6. 6*. * . * 6. . * K.
IIR:
% Compute the impulse response y
close all, clear all
N = 40;
num = [2.2 1 1];
den = [1];
y = impz(num,den,N);
% Plot the impulse response
stem(y);
xlabel('Time index n'); ylabel('Amplitude');
title('Impulse Response'); grid;
IIR systems have an impulse response function that is non-zero over an infinite length of time. This
is in contrast to finite impulse response (FIR) filters, which have fixed-duration impulse responses.
The simplest analog IIR filter is an RC filter made up of a single resistor (R) feeding into a node
shared with a single capacitor (C).
Digital filters are often described and implemented in terms of the difference equation that defines
how the output signal is related to the input signal:
where:
Is the feed forward filter order
are the feed forward filter coefficients
is the feedback filter order
are the feedback filter coefficients
Is the input signal
Is the output signal.
A more condensed form of the difference equation is:
which, when rearranged, becomes:
To find the transfer function of the filter, we first take the Z-transform of each side of the above
equation, where we use the time-shift property to obtain:
We define the transfer function to be:
Considering that in most IIR filter designs coefficient is 1, the IIR filter transfer function takes the
more traditional form:
Properties:
The main advantage IIR filters have over FIR filters is that through recursion they use fewer taps.
Therefore in digital signal processing applications IIR filters use fewer computing resources than an
equivalent FIR filter. A disadvantage of IIR filters is they can be unstable and subject to limit cycle
behavior.
:*. − 6:* − . = 6. 6*. * . * 6.
Know For N=100
% Compute the impulse response y
close all, clear all
N = 40;
num = [2.2 1 1];
den = [1 2];
y = impz(num,den,N);
% Plot the impulse response
stem(y);
xlabel('Time index n'); ylabel('Amplitude');
title('Impulse Response'); grid;
Following equation computes impulse response of following difference equation
:*. − . G:* . . HI:* 6. 6. 6*. 6. J* . 6. G* 6. Exercise 3: Write MATLAB program to generate and plot the step response of a causal LTI
system.
Exercise 2:
:*. . G:* . . HI:* 6. 6. 6*. 6. J* . 6. G* 6. Using this program compute and plot the first 40 samples of the step response above
mentioned LTI system.
% Compute the impulse response y close all, clear all N = 40; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; y = impz(num,den,N); % Plot the impulse response stem(y); xlabel('Time index n'); ylabel('Amplitude'); title('Impulse Response'); grid;
EXPERIMENT NO. 4
Z-Transform
Study of Z-Transform in MATLAB:
THEORY: Z-Transform technique is an important tool in the analysis of characterization of discrete time
signals and LTI systems; Z-Transform gives the response of various signals by its pole zero locations.
Z-Transform is an important tool in DSP that gives the solution of difference equation in one go.
The Z-Transform of a discrete time system x (n) is defined as power series;
And the inverse Z-Transform is denoted by;
Since, Z-Transform is the infinite power series; it exists only for the region for which this series
converges (region of convergence). Inverse Z-Transform is the method for inverting the Z-
Transform of a signal so as to obtain the time domain representation of signal. The features of Z-
Transform which are explained are as fellows;
Z-Transform of a Discrete time function
EXAMPLE:
MATLAB CODE:
% Z transform close all, clear all
b=[1 -1.6 180 1];
a=[1 -1.5 161 0.878];
A=roots(a)
B=roots(b)
zplane(b,a)
A =
0.7527 +12.6666i
0.7527 -12.6666i
-0.0055
B =
0.8028 +13.3927i
0.8028 -13.3927i
-0.0056
Z-TRRANSFORM OF A DISCRETE TIME FUNCTION:
Z-transform is defined as
X(z)
Or
X(z)=Z(x(n))
Let the function equation be
*. = /G^
*. = MB ∗
% Z-transform close all, clear all syms z n u =1/(4^n); U=ztrans(u) U= 4*z/(4*z-1)
% Z-transform close all, clear all syms z n a x=sin(a*n) X=ztrans(x) X= z*sin(a)/(z^2-2*z*cos(a)+1)
Exercise 1:
Consider that the equation is
*. = ^G
Find Z-transform
INVERSE Z-TRANSFORM: The inverse Z-Transform is denoted by,
Let the Z-domain is:
% Z-transform close all, clear all syms z n X=2*z/(2*z-1) x=iztrans(X) x= (1/2)^n
EXPERIMENT NO. 5
Fourier Transform and Properties
Discrete-Time Fourier Transform: The discrete-time Fourier transform (DTFT) X(ejω ) of a sequence x[n] is a continuous function of ω.
Since the data in MATLAB is in vector form, X(ejω ) can only be evaluated at a prescribed set of
discrete frequencies. Moreover, only a class of the DTFT that is expressed as a rational function in
e−jω in the form
OP/QRS = TU + T3/VQR + T4/VQR4 + ⋯ + TX/VQRXYU + Y3/VQR + Y4/VQR4 + ⋯ + YZ/VQRZ
(5.1)
can be evaluated. In the following two projects you will learn how to evaluate and plot the DTFT
and study certain properties of the DTFT using MATLAB.
DTFT Computation
The DTFT X(ejω ) of a sequence x[n] of the form of Eq. (5.1) can be computed easily at a prescribed
set of L discrete frequency points ω = ω₃ using the MATLAB function freqz. Since X(ejω ) is a
continuous function of ω, it is necessary to make L as large as possible so that the plot generated
using the command plot provides a reasonable replica of the actual plot of the DTFT. In MATLAB,
freqz computes the L-point DFT of the sequences p0 p1 . . . PM and d0 d1 . . . dM , and then
forms their ratio to arrive at X(ejωl ), l = 1, 2, . . . , L. For faster computation, L should be chosen as a
power of 2, such as 256 or 512.
Program P5_1 can be used to evaluate and plot the DTFT of the form of Eq. (5.1).
% Program P5_1 % Evaluation of the DTFT clear all; close all; clc % Compute the frequency samples of the DTFT w = -4*pi:8*pi/511:4*pi; num = [2 1];den = [1 -0.6]; h = freqz(num, den, w); % Plot the DTFT subplot(2,1,1) plot(w/pi,real(h));grid title('Real part of H(e^j\omega)') xlabel('\omega /\pi'); ylabel('Amplitude'); subplot(2,1,2) % plot the imaginary part in the same way your self and give it title pause subplot(2,1,1) % In this subplot plot magnitude of FFT your self subplot(2,1,2) % In this subplot plot magnitude of FFT your self
DTFT Properties
Most of the properties of the DTFT can be verified using MATLAB. Since all data in MATLAB have to
be finite-length vectors, the sequences being used to verify the properties are thus restricted to be
of finite length.
Program P5_2 can be used to verify the time-shifting property of the DTFT.
-1 -0.5 0 0.5 10
20
40
60Magnitude Spectrum of Original Sequence
-1 -0.5 0 0.5 10
20
40
60Magnitude Spectrum of Time-Shifted Sequence
-1 -0.5 0 0.5 1-4
-2
0
2
4Phase Spectrum of Original Sequence
-1 -0.5 0 0.5 1-4
-2
0
2
4Phase Spectrum of Time-Shifted Sequence
% Program P5_2 % Time-Shifting Properties of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; wo = 0.4*pi;D=10; num=[1 2 3 4 5 6 7 8 9]; h1 = freqz(num, 1, w); h2 = freqz([zeros(1,D) num], 1, w); subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h2));grid title('Magnitude Spectrum of Time-Shifted Sequence' ) subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h2));grid title('Phase Spectrum of Time-Shifted Sequence')
Program P5_3 can be used to verify the frequency-shifting property of the DTFT.
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 11.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579x 10
10 Magnitude Spectrum of Original Sequence
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 11.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579
1.3579x 10
10 Magnitude Spectrum of Frequency-Shifted Sequence
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1.5
-1
-0.5
0
0.5
1
1.5x 10
-9 Phase Spectrum of Original Sequence
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1.5
-1
-0.5
0
0.5
1
1.5x 10
-9 Phase Spectrum of Frequency-Shifted Sequence
% Program P5_3 % Frequency-Shifting Properties of DTFT clear all; close all; clc w = -pi:2*pi/255:pi; wo = 0.4*pi; num1=[13579111315 17];
L = lengt h(num1); h1 = freqz(num1, 1, w); n = 0:L-1; num2 = exp(wo*i*n).*num1; h2 = freqz(num2, 1, w); subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h2));grid title('Magnitude Spectrum of Frequency-Shifted Sequ ence') subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h2));grid title('Phase Spectrum of Frequency-Shifted Sequence ')
Program P5_4 can be used to verify the convolution property of the DTFT.
Program P5_5 can be used to verify the modulation property of the DTFT.
% Program P5_4
% Convolution Property of DTFT
close all; clear all; clc
w = -pi:2*pi/255:pi;
x1=[1 3 5 7 9 11 13 15 17];
x2=[1 -23 -21];
% convolve x1 and x2 yourself
h1 = freqz(x1, 1, w);
% compute freqz of x2 at w points and save it in h2 yourself
hp = h1.*h2;
h3 = freqz(y,1,w);
subplot(2,2,1)
plot(w/pi,abs(hp));grid
title('Product of Magnitude Spectra')
subplot(2,2,2)
plot(w/pi,abs(h3));grid
title('Magnitude Spectrum of Convolved Sequence')
subplot(2,2,3)
% Program P5_5
% Modulation Property of DTFT
close all; clear all; clc
w = -pi:2*pi/255:pi;
x1=[1 3 5 7 9 11 13 15 17];
x2=[1 -1 1 -1 1 -1 1 -1 1];
y = x1.*x2;
h1 = freqz(x1, 1, w);
h2 = freqz(x2, 1, w);
% similarly compute freqz of y and save it in h3 yourself
subplot(3,1,1)
plot(w/pi,abs(h1));grid
title('Magnitude Spectrum of First Sequence')
subplot(3,1,2)
plot(w/pi,abs(h2));grid
Program P5_6 can be used to verify the time-reversal property of the DTFT.
-1 -0.5 0 0.5 12
4
6
8
10Magnitude Spectrum of Original Sequence
-1 -0.5 0 0.5 12
4
6
8
10Magnitude Spectrum of Time-Reversed Sequence
-1 -0.5 0 0.5 1-4
-2
0
2
4Phase Spectrum of Original Sequence
-1 -0.5 0 0.5 1-4
-2
0
2
4Phase Spectrum of Time-Reversed Sequence
% Program P5_6 % Time-Reversal Property of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; num=[1 2 3 4]; L = length(num)-1; h1 = freqz(num, 1, w); h2 = freqz(fliplr(num), 1, w); h3 = exp(w*L*1i).*h2; subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h3));grid title('Magnitude Spectrum of Time-Reversed Sequence ') subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h3));grid title('Phase Spectrum of Time-Reversed Sequence')
EXPERIMENT NO. 6
Sampling, A/D Conversion and D/A
Conversion
The Sampling Process in the Time Domain:
The purpose of this section is to study the relation in the time domain between a continuous-time
signal xa (t) and the discrete-time signal x[1] generated by a periodic sampling of xa (t).
1. Sampling of a Sinusoidal Signal
In this project you will investigate the sampling of a continuous-time sinusoidal signal xa (t) at
various sampling rates. Since MATLAB cannot strictly generate a continuous-time signal, you will
generate a sequence xa (nTH ) from xa (t) by sampling it at a very high rate, 1/TH , such that the
samples are very close to each other. A plot of xa (nTH ) using the plot command will then look like
a continuous-time signal.
2. Aliasing Effect in the Time Domain
In this project you will generate a continuous-time equivalent ya (t) of the discrete-time signal x[1]
generated in Program P4_1 to investigate the relation between the frequency of the sinusoidal
signal xa (t) and the sampling period. To generate the reconstructed signal ya (t) from x[1], we pass
x[1] through an ideal low pass filter that in turn can be implemented according to Eq. (4.1). If Eq.
(4.1) is computed at closely spaced values of t, a plot of ya (t) will resemble a continuous-time
signal. In order to implement this equation on MATLAB, the summation in Eq. (4.1) needs to be
replaced with a finite sum, and hence we can generate only an approximation to the desired
reconstructed continuous-time signal ya (t).
% Program 6_1 % Illustration of the Sampling Process % in the Time Domain clear all; close all; clc; t = 0:0.0005:1; f = 13; xa = cos(2*pi*f*t); subplot(2,1,1) plot(t,xa,'LineWidth',1.5); xlabel('Time, msec');ylabel('Amplitude'); title('Continuous-time signal x_a(t)'); axis([0 1 -1.2 1.2]) subplot(2,1,2); T = 0.1; n = 0:T:1; xs = cos(2*pi*f*n); k = 0:length(n)-1; stem(k,xs,'r'); xlabel('Time index n');ylabel('Amplitude'); title('Discrete-time signal x[n]'); axis([0 (length(n)-1) -1.2 1.2])
h\t = 12π _ H\jΩedefdt
h
Vh
= T2π_ edefdΩ = sinΩltΩmt/2
enVen
,− ∞ ≤ t ≤ ∞
(4.1)
3. Effect of Sampling in the Frequency Domain
Aliasing Effect in the Frequency Domain
% Program P6_2 % Illustration of Aliasing Effect in the Time Domai n clear all; close all; clc; T = 0.1; f = 13; n = (0:T:1)'; xs = cos(2*pi*f*n); t = linspace(-0.5,1.5,500)'; ya = sinc((1/T)*t(:,ones(size(n))) - (1/T)*n(:,ones (size(t)))')*xs; plot(n,xs,'bo',t,ya, 'r','Linewidth',1.5);grid; xlabel('Time, msec');ylabel('Amplitude'); title('Reconstructed continuous-time signal y_a(t )'); axis([0 1 -1.2 1.2]);
% Program P6_3 % Illustration of the Aliasing Effect % in the Frequency Domain clear all; close all; clc; t = 0:0.005:10; xa = 2*t.*exp(-t); subplot(2,2,1) plot(t,xa);grid xlabel('Time, msec');ylabel('Amplitude'); title('Continuous-time signal x_a(t)'); subplot(2,2,2) wa = 0:10/511:10; ha = freqs(2,[1 2 1],wa); plot(wa/(2*pi),abs(ha));grid; xlabel('Frequency, kHz');ylabel('Amplitude'); title('|X_a(j\Omega)|'); axis([0 5/pi 0 2]); subplot(2,2,3) T=1 ; n = 0:T:10; xs = 2*n.*exp(-n); k = 0:length(n)-1; stem(k,xs);grid; xlabel('Time index n');ylabel('Amplitude'); title('Discrete-time signal x[n]'); subplot(2,2,4) wd = 0:pi/255:pi; hd = freqz(xs,1,wd); plot(wd/(T*pi), T*abs(hd));grid; xlabel('Frequency, kHz');ylabel('Amplitude'); title('|X(e^j\omega)|'); axis([0 1/T 0 2])
4. Analog Low pass Filters
Analog low pass filters are employed as anti-aliasing filters and as anti-imaging filters in the digital
processing of continuous-time signals.
Design of Analog Low pass Filters
The first step in the design of any of these filters is the determination of the filter order N and the
appropriate cutoff frequency ΩC. These parameters can be determined using the MATLAB
commands buttord for the Butterworth filter, cheb1ord for the Type 1 Chebyshev filter, cheb2ord
for the Type 2 Chebyshev filter, and ellipord for the elliptic filter. ΩC is the 3-dB cutoff frequency
for the Butterworth filter, the passband edge for the Type 1 Chebyshev filter, the stopband edge
for the Type 2 Chebyshev filter, and the pass band edge for the elliptic filter. For the design of
filters MATLAB commands are butter for the Butterworth filter, cheby1 for the Type 1 Chebyshev
filter, cheby2 for the Type 2 Chebyshev filter, and ellip for the elliptic filter.
Program P4 4 can be used for the design of the Butterworth lowpass filter.
% Program P6_4 % Design of Analog Lowpass Filter clear all; close all; clc; Fp = 3500;Fs = 4500; Wp = 2*pi*Fp; Ws = 2*pi*Fs; [N, Wn] = buttord(Wp, Ws, 0.5, 30,'s'); [b,a] = butter(N, Wn, 's'); wa = 0:(3*Ws)/511:3*Ws; h = freqs(b,a,wa); plot(wa/(2*pi), 20*log10(abs(h)),'r', 'LineWidth',1 .5);grid xlabel('Frequency, Hz');ylabel('Gain, dB'); title('Gain response'); axis([0 3*Fs -60 5]);
0 2000 4000 6000 8000 10000 12000-60
-50
-40
-30
-20
-10
0
Frequency, Hz
Gai
n, d
BGain response
EXPERIMENT NO. 7:
System Frequency Transform
Introduction to Digital Filter
Frequency Transform:
Is to represent mathematical function of time in frequency domain.
:*. − 6:* − . = 6. 6*. 6* . 6. 6* 6.
% Program P7_1
% Illustration of Aliasing Effect in the Time Domain
clear all; close all; clc;
num=[1 2 2.2];
den=[1 2];
freqz(num,den)
% Program P7_2
% Illustration of Aliasing Effect in the Time Domain
clear all; close all; clc;
num=[1 2 2.2];
den=[1 2];
Y=freqz(num,den)
Plot(abs(Y))
Can also view the frequency response of the system by defining “w”
% Program P7_3
% Illustration of Aliasing Effect in the Time Domain
clear all; close all; clc;
w=-pi:pi/100:pi
num=[1 2 2.2];
den=[1 2];
freqz(num,den)
Another way to do this is by computing the frequency response of the system then define w and
compute the response
% Program P7_4
% Illustration of Aliasing Effect in the Time Domain
clear all; close all; clc;
w=-pi:pi/100:pi
Y=(1+2*exp(-j*w)+2.2*exp(-2*j*w))./(1-2*exp(-j*w))
plot(w,abs(Y))
Exercise 1:
:*. − 6:* − 6. = 6. 6[] + 6[ − ] + 6. 6[ − 6]
:[] − . :[ − ] + :[ − J] = [] + . I[ − ] + [ − 6]
:[] − . :[ − ] + :[ − J] + :[ − I] = [] + [ − G] Plot the magnitude and phase response of the given difference equation.
Filter:
Filters are usually used to discriminate a frequency or a band of frequency from a given signal
which is normally a mixture of both desired and undesired signals. The undesired portion of the
signal commonly comes from noise sources such as power line hum etc. Or other signals which are
not required for the current application. Analog filters were being used successfully for decades to
serve this purpose. Although analog filters are excellent in some aspects, especially in cost, they do
have some serious demerits. One of the drawbacks of analog filters is there non-linear phase
characteristics. This is not a serious problem in many of the applications, but it become serious in
applications like telecommunication, voice processing etc... Another drawback is the less sharp cut-
off frequency. It is possible to increase roll-off rate by cascading filter stages, but this would
increase system cost and complexity. On the other hand, it is possible to achieve all these
characteristics fairly by using a digital filter
Two types of Filter
• FIR (Finite impulse Response)
• IIR (Infinite impulse Response)
Filters can be designed by using different techniques but the most simple type of filters are simple
digital filters. In case of simple digital filters these can be implemented simply by the difference
equation,
Like FIR filters are
Low Pass:
:[] = 6[] +6[ − ]
High Pass:
:[] = 6[] −6[ − ]
Band Pass:
:[] = 6[] −6[ − 6]
Band Stop:
:[] = 6[] +6[ − 6]
EXPERIMENT NO. 8:
Simple Digital Filter
1) FIR
2) IIR
Low Pass:
:*. = 6 *. +
6 * − . Find the frequency transform of the given difference equation
High Pass:
:*. = 6 *. −
6 * − . Find the frequency transform of the given difference equation
% Program
% Low pass FIR filter
clear all; close all; clc;
w=-pi:pi/100:pi;
num=[1/2 1/2];
den=[1];
H=freqz(num,den,w);
plot(w,abs(H))
xlabel('w frequency')
ylabel('abs(H)')
Band Pass:
:*. = 6 *. −
6 * − 6. Find the frequency transform of the given difference equation
% Program
% Low pass FIR filter
clear all; close all; clc;
w=-pi:pi/100:pi;
num=[1/2 -1/2];
den=[1];
H=freqz(num,den,w);
plot(w,abs(H))
xlabel('w frequency')
ylabel('abs(H)')
% Program
% Low pass FIR filter
clear all; close all; clc;
w=-pi:pi/100:pi;
num=[1/2 0 -1/2];
den=[1];
H=freqz(num,den,w);
plot(w,abs(H))
xlabel('w frequency')
ylabel('abs(H)')
Band Stop:
:*. = 6 *. +
6 * − 6. Find the frequency transform of the given difference equation
% Program
% Low pass FIR filter
clear all; close all; clc;
w=-pi:pi/100:pi;
num=[1/2 0 1/2];
den=[1];
H=freqz(num,den,w);
plot(w,abs(H))
xlabel('w frequency')
ylabel('abs(H)')
EXPERIMENT NO.9
Design of FIR filters using
Rectangular window
Low Pass Filter:
Compute the impulse response of the Low pass filter. After computing impulse response computes
the frequency response of the response to visualize the frequency response.
Pass the signal of any frequency from the filter and observe the output
% Program
% Low pass FIR filter (Rectangular Window)
clc
clear all
w=-pi:pi/200:pi;
n=0:40;
%Impulse Responce
h=(1/pi)*sinc((1*(n-20))/pi);
subplot(2,3,1)
plot(n,h)
xlabel('Impulse Responce for n=0:40')
%Frequency Responce
y=freqz(h,1,w);
subplot(2,3,2)
plot(w,abs(y))
xlabel('freqz Responce for n=0:40')
n1=0:50;
x=cos(1.5*n1);
subplot(2,3,3)
plot(n1,x)
xlabel('Input Signal')
subplot(2,3,4)
y=conv(x,h);
plot(y)
axis([0 90 -1 1])
xlabel('Output Signal')
subplot(2,3,5)
X=freqz(x,1,w);
plot(w,abs(X))
xlabel('X(e^j^w)')
High Pass Filter:
Compute the impulse response of the Low pass filter. After computing impulse response computes
the frequency response of the response to visualize the frequency response.
Pass the signal of any frequency from the filter and observe the output
% Program
% High pass FIR filter (Rectangular Window)
clc
clear all
w=-pi:pi/200:pi;
n=0:40;
%Impulse Responce
h=sinc((n-20))-(1.5/pi*sinc(1.5*(n-20)/pi))
subplot(2,3,1)
plot(n,h)
xlabel('Impulse Responce for n=0:40')
%Frequency Responce
y=freqz(h,1,w);
subplot(2,3,2)
plot(w,abs(y))
xlabel('freqz Responce for n=0:40')
n1=0:50;
x=cos(2*n1)+cos(0.5*n1);
subplot(2,3,3)
plot(n1,x)
xlabel('Input Signal')
subplot(2,3,4)
y=conv(x,h);
plot(y)
axis([0 90 -1 1])
xlabel('Output Signal')
subplot(2,3,5)
X=freqz(x,1,w);
plot(w,abs(X))
xlabel('X(e^j^w)')
Band Pass Filter:
Compute the impulse response of the Low pass filter. After computing impulse response computes
the frequency response of the response to visualize the frequency response.
Pass the signal of any frequency from the filter and observe the output
% Program
% Band pass FIR filter (Rectangular Window)
clc
clear all
w=-pi:pi/200:pi;
wL=1.5;wP=2.3;
n=0:40;
%Impulse Responce
h=(wL/pi*sinc(wL*(n-20)/pi))-(wP/pi*sinc(wP*(n-20)/pi))
subplot(2,3,1)
plot(n,h)
xlabel('Impulse Responce for n=0:40')
%Frequency Responce
y=freqz(h,1,w);
subplot(2,3,2)
plot(w,abs(y))
xlabel('freqz Responce for n=0:40')
n1=0:50;
x=cos(2*n1)+cos(0.7*n1);
subplot(2,3,3)
plot(n1,x)
xlabel('Input Signal')
subplot(2,3,4)
y=conv(x,h);
plot(y)
axis([0 90 -1 1])
xlabel('Output Signal')
subplot(2,3,5)
X=freqz(x,1,w);
plot(w,abs(X))
xlabel('X(e^j^w)')
subplot(2,3,6)
Y=freqz(y,1,w);
plot(w,abs(Y))
xlabel('Y(e^j^w)')
Band Pass Filter:
Compute the impulse response of the Band stop filter. After computing impulse response
computes the frequency response of the response to visualize the frequency response.
Pass the signal of any frequency from the filter and observe the output
% Program
% Band Stop FIR filter (Rectangular Window)
clc
clear all
w=-pi:pi/200:pi;
wL=0.5;wP=2.3;
n=0:100;
%Impulse Responce
h=(wL/pi*sinc(wL*(n-50)/pi))-(wP/pi*sinc(wP*(n-50)/pi))+sinc(n-50)
subplot(2,3,1)
plot(n,h)
xlabel('Impulse Responce for n=0:40')
%Frequency Responce
y=freqz(h,1,w);
subplot(2,3,2)
plot(w,abs(y))
xlabel('freqz Responce for n=0:100')
n1=0:50;
x=cos(1*n1)+cos(1.5*n1);
subplot(2,3,3)
plot(n1,x)
xlabel('Input Signal')
subplot(2,3,4)
y=conv(x,h);
plot(y)
axis([0 90 -1 1])
xlabel('Output Signal')
subplot(2,3,5)
X=freqz(x,1,w);
plot(w,abs(X))
xlabel('X(e^j^w)')
subplot(2,3,6)
Y=freqz(y,1,w);
plot(w,abs(Y))
xlabel('Y(e^j^w)')
EXPERIMENT NO. 10
DIGITAL FILTER STRUCTURE
FIR Filter Design:
Conceptually the simplest approach to FIR filter design is to simply truncate to a finite number of
terms the doubly infinite-length impulse response coefficients obtained by computing the inverse
discrete-time Fourier transform of the desired ideal frequency response. However, a simple
truncation results in an oscillatory behavior in the respective magnitude response of the FIR filter,
which is more commonly referred to as the Gibbs phenomenon.
The Gibbs phenomenon can be reduced by windowing the doubly infinite-length impulse response
coefficients by an appropriate finite-length window function. The functions fir1 and fir2 can be
employed to design windowed FIR digital filters in MATLAB. Both functions yield a linear-phase
design.
The function fir1 can be used to design conventional lowpass, highpass, bandpass, and bandstop
linear-phase FIR filters. The command
b = fir1(N,Wn)
returns in vector b the impulse response coefficients, arranged in ascending powers of z—1 , of a
lowpass or a bandpass filter of order N for an assumed sampling frequency of 2 Hz. For lowpass
design, the normalized cutoff frequency is specified by a scalar Wn, a number between 0 and 1. For
bandpass design, Wn is a two-element vector [Wn1, Wn2] containing the specified passband edges
where 0 < Wn1 < Wn2 < 1. The command
b = fir1(N,Wn,’high’)
with N an even integer, is used for designing a highpass filter. The command
b = fir1(N,Wn,’stop’)
with Wn a two-element vector, is employed for designing a bandstop FIR filter. If none is specified,
the Hamming window is employed as a default. The command
b = fir1(N, Wn, taper)
makes use of the specified window coefficients of length N+1 in the vector taper. However, the
window coefficients must be generated a priori using an appropriate MATLAB function such as
blackman, hamming, hanning, chebwin, or kaiser. The commands to use are of the following
forms:
taper = blackman(N) taper = hamming(N) taper = hanning(N) taper = chebwin(N) taper = kaiser(N, beta)
The function fir2 can be used to design linear-phase FIR filters with arbitrarily shaped magnitude
responses. In its basic form, the command is
b = fir2(N, fpts, mval)
which returns in the vector b of length N+1 the impulse response coefficients, arranged in
ascending powers of z—1 . fpts is the vector of specified frequency points, arranged in an
increasing order, in the range 0 to 1 with the first frequency point being 0 and the last frequency
point being 1. As before, the sampling frequency is assumed to be 2 Hz. mval is a vector of specified
magnitude values at the specified frequency points and therefore must also be of the same length
as fpts. The Hamming window is used as a default. To make use of other windows, the command
to use is
b = fir2(N, fpts, mval,taper)
where the vector taper contains the specified window coefficients.
A more widely used linear-phase FIR filter design is based on the Parks–McClellan algorithm, which
results in an optimal FIR filter with an equiripple weighted error ε (w) defined in Eq.
ℰω = qrstuP/QRSt − vrw
It makes use of the Remez optimization algorithm and is available in MATLAB as the function firpm.
This function can be used to design any type of single-band or multiband filter, the differentiator,
and the Hilbert transformer. In its basic form, the command
b = firpm(N,fpts,mval)
returns a vector b of length N+1 containing the impulse response coefficients of the desired FIR filter
in ascending powers of z—1 . fpts is the vector of specified frequency points, arranged in
increasing order, in the range 0 to 1 with the first frequency point being 0 and the last frequency
point being 1. As before, the sampling frequency is assumed to be 2 Hz. The desired magnitudes
of the FIR filter frequency response at the specified band edges are given by the vector mval, with
the elements given in equal-valued pairs. The desired magnitudes between two specified
consecutive frequency points f(k) and f(k+1) are determined according to the following rules. For
k odd, the magnitude is a line segment joining the points mval(k), fpts(k) and mval(k+1),
fpts(k+1), whereas, for k even, it is unspecified with the frequency range [fpts(k), fpts(k+1)]
being a transition or “don’t care” region. The vectors fpts and mval must be of the same length
with the length being even. Figure 7.4 illustrates the relationship between the vectors fpts and
mval given by
fpts = [ 0 0.2 0.4 0.7 0.8 1.0] mval = [0.5 0.5 1.0 1.0 0.3 0.3]
FIGURE 9.1: ILLUSTRATION OF RELATIONSHIP BETWEEN VECTORS FPTS AND MVAL
The desired magnitude responses in the passband(s) and the stopband(s) can be weighted by an
additional vector wgts included as the argument of the function firpm. The function can be used to
design equiripple Types 1, 2, 3, and 4 linear-phase FIR filters. Types 1 and
2 are the default designs for order N even and odd, respectively. Types 3 (N even) and 4 (N odd) are
used for specialized filter designs, the Hilbert transformer and the differentiator. To design these
two types of FIR filters the fiags hilbert and differentiator are used for ftype in the last two
versions of firpm. The command
b = firpm(N,fpts,mval,wgts)
is used to design an FIR filter weighted in each band by the elements of the weight vector wgts
whose length is thus half that of fpts. The elements of the vector wgts can be determined
from the specified passband and stopband ripples by dividing the maximum ripple value by the
ripple values. To design a Hilbert transformer or a differentiator, use the forms
firpm(N,fpts,mval,ftype) firpm(N,fpts,mval,wgts,ftype)
where ftype is the string hilbert or differentiator. In the case of a Hilbert transformer
design, the smallest element in fpts should not be a 0.
The order N of the FIR filter to meet the given specifications can be estimated using either Kaiser’s
formula of Eq. (9.2).
x ≅ −20 log3UP&~&S 1314.6r/2
(9.2)
The MATLAB function kaiord given below implements Kaiser’s formula:
function N = kaiord(Fp, Fs, dp, ds, FT) % Computation of the length of a linear-phase % FIR multiband filter using Kaiser’s formula % dp is the passband ripple % ds is the stopband ripple % Fp is the passband edge in Hz % Fs is the stopband edge in Hz % FT is the sampling frequency in Hz. % If none specified default value is 2 % N is the estimated FIR filter order if nargin == 4, F T=2 ; end if length(Fp) > 1, TBW = min(abs(Fp(1) - Fs(1)), abs(Fp(2) - Fs(2))); else TBW = abs(Fp - Fs); end num = -20*log10(sqrt(dp*ds)) - 13; den = 14.6*TBW/FT; N = ceil(num/den);
The function kaiserord in the Signal Processing Toolbox can also be used for estimating the filter
order using Kaiser’s formula. It can be used in one of the following forms:
[N, Wn, beta, ftype] = kaiserord(fedge, aval, dev) [N, Wn, beta, ftype] = kaiserord(fedge, aval, dev, FT) c = kaiserord(fedge, aval, dev, FT, ’cell’)
where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified; fedge is a
vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a vector
specifying the desired values of the magnitude response at the specified bandedges given by fedge.
The length of fedge is 2 less than twice the length of aval and therefore must be even. dev is a
vector of maximum deviations or ripples in dB allowable for each band. If the deviations specified
are unequal, the smallest one is used for all bands.
The output data are in the desired format for use in fir1, with normalized bandedges Wn and the
parameter beta used for computing the window coefficients as given in Eq. (7.36). The string ftype
specifies the filter type for fir1. It is high for highpass filter design, and stop for bandstop filter
design. The last form of kaiserord specifies a cell array whose elements are parameters to fir1.
The MATLAB function firpmord implements the formula of Eq. (7.8). It can be used in one of the
following forms:
[N,fts,mval,wgts] = firpmord(fedge,aval,dev) [N,fts,mval,wgts] = firpmord(fedge,aval,dev,FT)
where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified, fedge is a
vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a vector
specifying the desired values of the magnitude response at the specified bandedges given by fedge.
The length of fedge is 2 less than twice the length of aval and therefore must be even. dev is a
vector of maximum deviations or ripples in dB allowable for each band. A third form of firpmord is
given by
c = firpmord(fedge,aval,dev,FT, ’cell’)
and specifies a cell array whose elements are the parameters to firpm.
In some cases, the order N determined using either method may not result in an FIR filter meeting
the original specifications. If it does not, the order should either be increased or decreased by 1
gradually until the specifications are met. Moreover, the order estimates may be highly inaccurate
for very narrowband or very wideband FIR filters.
Lab task
1.1..1 Using MATLAB determine the lowest order of a digital IIR lowpass filter of all four types.
The specifications are as follows: sampling rate of 40 kHz, passband edge frequency of 4
kHz, stopband edge frequency of 8 kHz, passband ripple of 0.5 dB, and a minimum
stopband attenuation of 40 dB. Comment on your results.
1.1..2 Using MATLAB determine the lowest order of a digital IIR highpass filter of all four
types. The specifications are as follows: sampling rate of 3,500 Hz, passband edge
frequency of 1,050 Hz, stopband edge frequency of 600 Hz, passband ripple of 1 dB,
and a minimum stopband attenuation of 50 dB. Comment on your results.
1.1..3 Using MATLAB determine the lowest order of a digital IIR bandpass filter of all four types.
The specifications are as follows: sampling rate of 7 kHz, passband edge frequencies at
1.4 kHz and 2.1 kHz, stopband edge frequencies at 1.05 kHz and 2.45 kHz, passband
ripple of 0.4 dB, and a minimum stopband attenuation of 50 dB. Comment on your
results.
1.1..4 Using MATLAB determine the lowest order of a digital IIR bandstop filter of all four
types. The specifications are as follows: sampling rate of 12 kHz, passband edge
frequencies at 2.1 kHz and 4.5 kHz, stopband edge frequencies at 2.7 kHz and 3.9
kHz, passband ripple of 0.6 dB, and a minimum stopband attenuation of 45 dB.
Comment on your results.
1.1..5 Design the Butterworth bandstop filter by running Program P9_1. Write down the
exact expression for the transfer function generated. What are the filter
specifications? Does your design meet the specifications? Using MATLAB, compute
and plot the filter’s unwrapped phase response and the group delay response.
1.1..6 Modify Program P10_1 to design a Type 1 Chebyshev lowpass filter meeting the given
specifications of Question Q 1. Write down the exact expression for the transfer
function generated. Does your design meet the specifications? Using MATLAB,
compute and plot the filter’s unwrapped phase response and the group delay
response.
1.1..7 Modify Program P10_1 to design a Type 2 Chebyshev highpass filter meeting the
specifications given in Question Q 2. Write down the exact expression for the
transfer function generated. Does your design meet the specifications? Using MATLAB,
compute and plot the filter’s unwrapped phase response and the group delay
response.
1.1..8 Modify Program P10_1 to design an elliptic bandpass filter meeting the specifications
given in Question Q 3. Write down the exact expression for the transfer function
generated. Does your design meet the specifications? Using MATLAB, compute and
plot the filter’s unwrapped phase response and the group delay response.
1.1..9 Repeat the above question for the following cases: (a) sampling rate of 20 kHz, (b) δp
= 0.002 and δS = 0.002, and (c) stopband edge = 2.3 kHz. Compare the filter length
obtained in each case with that obtained in the above question. Comment on the
effect of the sampling rate, ripples, and the transition bandwidth on the filter order.
EXPERIMENT NO.11
Design of FIR filters using Matlab
commands.
Description:
Digital filters refers to the hard ware and software implementation of the mathematical Algorithm
which accepts a digital signal as input and produces another digital signal as output whose wave
shape, amplitude and phase response has been modified in a specified manner.
Digital filter play very important role in DSP. Compare with analog filters they are preferred in
number of application due to following advantages.
• Truly linear phase response
• Better frequency response
• Filtered and unfiltered data remains saved for further use.
There are two types of digital filters.
• FIR (finite impulse response) filter
• IIR (infinite impulse response) filter
Description of the Commands Used In FIR Filter Design:
FIR1:
FIR filters design using the window method. B = FIR1(N,Wn) designs an N'th order low
pass FIR digital filter and returns the filter coefficients in length N+1 vector B. The cutoff
frequency Wn must be between 0 < Wn < 1.0, with 1.0 corresponding to half the
sample rate. The filter B is real and has linear phase. The normalized gain of the filter
at Wn is -6 dB.
B = FIR1(N,Wn,'high') designs an N'th order high pass filter. You can also use B =
FIR1 (N,Wn,'low') to design a low pass filter. If Wn is a two-element vector, Wn = [W1
W2], FIR1 returns an order N band pass filter with pass band W1 < W < W2.
B = FIR1 (N,Wn,'stop') is a band stop filter if Wn = [W1 W2]. You can also specify If Wn
is a multi-element vector, Wn = [W1 W2 W3 W4 W5 ... WN], FIR1 returns an order N
Multiband filter with bands 0 < W < W1, W1 < W < W2, ..., WN < W < 1.
B = FIR1 (N,Wn,'DC-1') makes the first band a pass band.
B = FIR1(N,Wn,'DC-0') makes the first band a stop band.
By default FIR1 uses a Hamming window. Other available windows, including Boxcar,
Hann, Bartlett, Blackman, Kaiser and Chebwin can be specified with an optional trailing
argument. For example, B = FIR1(N,Wn,kaiser(N+1,4)) uses a Kaiser window with
beta=4. B = FIR1(N,Wn,'high',chebwin(N+1,R)) uses a Chebyshev window.
For filters with a gain other than zero at Fs/2, e.g., high pass and band stop filters, N must
be even. Otherwise, N will be incremented by one. In this case the window length
should be specified as N+2.
By default, the filter is scaled so the center of the first pass band has magnitude exactly
one after windowing. Use a trailing 'noscale' argument to prevent this scaling, e.g.
B = FIR1(N,Wn,'noscale')
B = FIR1(N,Wn,'high','noscale')
B = FIR1(N,Wn,wind,'noscale').
You can also specify the scaling explicitly, e.g. FIR1(N,Wn,'scale'), etc.
FREQZ Digital Filter Frequency Response.
[H,W] = FREQZ(B,A,N) returns the N-point complex frequency response vector H and
the N-point frequency vector W in radians/sample of the filter: given numerator and
denominator coefficients in vectors B and A. The frequency response is evaluated at N
points equally spaced around the upper half of the unit circle. If N isn't specified, it
defaults to 512.
[H,W] = FREQZ(B,A,N,'whole') uses N points around the whole unit circle.
H = FREQZ(B,A,W) returns the frequency response at frequencies designated in vector
W, in radians/sample (normally between 0 and pi).
[H,F] = FREQZ(B,A,N,Fs) and [H,F] = FREQZ(B,A,N,'whole',Fs) return frequency
vector F (in Hz), where Fs is the sampling frequency (in Hz).
H = FREQZ(B,A,F,Fs) returns the complex frequency response at the frequencies
designated in vector F (in Hz), where Fs is the sampling frequency (in Hz).
[H,W,S] = FREQZ(...) or [H,F,S] = FREQZ(...) returns plotting information to be used
with FREQZPLOT. S is a structure whose fields can be altered to obtain different
frequency response plots. For more information see the help for FREQZPLOT.
FREQZ(B,A,...) with no output arguments plots the magnitude and unwrapped phase of
the filter in the current figure window.
Designing A Low Pass Filter:
Suppose out target is to pass all frequencies below 1200 Hz
fs=8000; % sampling frequency
n=50; % order of the filter
w=1200/ (fs/2);
b=fir1(n,w,'low'); % Zeros of the filter
freqz(b,1,128,8000); % Magnitude and Phase Plot of the filter
figure(2)
[h,w]=freqz(b,1,128,8000);
plot(w,abs(h)); % Normalized Magnitude Plot
grid
figure(3)
zplane(b,1);
Designing High Pass Filter:
Now our target is to pass all frequencies above 1200 Hz
Designing High Pass Filter:
Designing Band Pass Filter:
fs=8000;
n=50;
w=1200/ (fs/2); b=fir1(n,w,'high');
freqz(b,1,128,8000);
figure(2)
[h,w]=freqz(b,1,128,8000);
plot(w,abs(h)); % Normalized Magnitude Plot
grid
figure(3)
zplane(b,1);
fs=8000;
n=50;
w=1200/ (fs/2);
b=fir1(n,w,'high');
freqz(b,1,128,8000);
figure(2)
[h,w]=freqz(b,1,128,8000);
plot(w,abs(h)); % Normalized Magnitude Plot
grid
figure(3)
zplane(b,1);
fs=8000;
n=40;
b=fir1(n,[1200/4000 1800/4000],’bandpass’);
freqz(b,1,128,8000)
figure(2)
[h,w]=freqz(b,1,128,8000);
plot(w,abs(h)); % Normalized Magnitude Plot
grid
figure(3)
zplane(b,1);
Designing Multi Band Filter
Problems:
Design a band pass filter and band stop filter with the help of LPF and HPF
The filter has following specifications.
Band pass = 1200 – 2800 Hz
Band stop =1200-2800 Hz
n=50;
w=[0.2 0.4 0.6];
b=fir1(n,w);
freqz(b,1,128,8000)
figure(2)
[h,w]=freqz(b,1,128,8000);
plot(w,abs(h)); % Normalized Magnitude Plot
grid
figure(3)
zplane(b,1);
Design a Multi band filter using HPF and LPF
The filter has following specifications
Pass band=1200 Hz – 1800 Hz
Stop band = 1900 Hz – 2200 Hz
Pass band = 2300 Hz – 2700 Hz
EXPERIMENT NO.12
Design of IIR filters using Matlab
commands.
Description:
Matlab contains various routines for design and analyzing digital filter IIR. Most of these are part of
the signal processing tool box. A selection of these filters is listed below.
• Buttord ( for calculating the order of filter)
• Butter ( creates an IIR filter)
• Ellipord ( for calculating the order of filter)
• Ellip (creates an IIR filter)
• Cheb1ord (for calculating the order of filter)
• Cheyb1 (creates an IIR filter)
Explanation Of The Commands For Filter Design:
Buttord:
Butterworth filter order selection.
[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Butterworth
filter that loses no more than Rp dB in the pass band and has at least Rs dB of attenuation in the
stop band. Wp and Ws are the pass band and stop band edge frequencies, normalized from 0 to 1
(where 1 corresponds to pi radians/sample). For example
Low pass: Wp = .1, Ws = .2
High pass: Wp = .2, Ws = .1
Band pass: Wp = [.2 .7], Ws = [.1 .8]
Band stop: Wp = [.1 .8], Ws = [.2 .7]
BUTTORD also returns Wn, the Butterworth natural frequency (or, the "3 dB frequency") to use
with BUTTER to achieve the specifications. [N, Wn] = BUTTORD(Wp, Ws, Rp, Rs, 's') does the
computation for an analog filter, in which case Wp and Ws are in radians/second. When Rp is
chosen as 3 dB, the Wn in BUTTER is equal to Wp in BUTTORD.
Ellipord:
Elliptic filter order selection.
[N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital elliptic filter
that loses no more than Rp dB in the pass band and has at least Rs dB of attenuation in the stop
band Wp and Ws are the pass band and stop band edge frequencies, normalized from 0 to 1
(where 1 corresponds to pi radians/sample). For example,
Low pass: Wp = .1, Ws = .2
High pass: Wp = .2, Ws = .1
Band pass: Wp = [.2 .7], Ws = [.1 .8]
Band stop: Wp = [.1 .8], Ws = [.2 .7]
ELLIPORD also returns Wn, the elliptic natural frequency to use with ELLIP to achieve the
specifications. [N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in
which case Wp and Ws are in radians/second. NOTE: If Rs is much greater than Rp, or Wp and Ws
are very close, the estimated order can be infinite due to limitations of numerical precision.
Cheb1ord:
Chebyshev Type I filter order selection.
[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev
Type I filter that loses no more than Rp dB in the pass band and has at least Rs dB of attenuation in
the stop band. Wp and Ws are the pass band and stop band edge frequencies, normalized from 0
to 1 (where 1 corresponds to pi radians/sample). For example,
Low pass: Wp = .1, Ws = .2
High pass: Wp = .2, Ws = .1
Band pass: Wp = [.2 .7], Ws = [.1 .8]
Band stop: Wp = [.1 .8], Ws = [.2 .7]
CHEB1ORD also returns Wn, the Chebyshev natural frequency to use with CHEBY1 to achieve the
specifications. [N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter,
in which case Wp and Ws are in radians/second.
Butter:
Butterworth digital and analog filter design.
[B,A] = BUTTER(N,Wn) designs an Nth order lowpass digital Butterworth filter and returns the filter
coefficients in length N+1 vectors B (numerator) and A (denominator). The coefficients are listed in
descending powers of z. The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0 corresponding
to half the sample rate. If Wn is a two-element vector, Wn = [W1 W2], BUTTER returns an order 2N
bandpass filter with passband W1 < W < W2.
[B,A] = BUTTER(N,Wn,'high') designs a highpass filter. [B,A] = BUTTER(N,Wn,'stop') is a bandstop
filter if Wn = [W1 W2]. When used with three left-hand arguments, as in [Z,P,K] = BUTTER(...), the
zeros and poles are returned in length N column vectors Z and P, and the gain in scalar K. When
used with four left-hand arguments, as in [A,B,C,D] = BUTTER(...), state-space matrices are
returned. BUTTER(N,Wn,'s'), BUTTER(N,Wn,'high','s') and BUTTER(N,Wn,'stop','s') design analog
Butterworth filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.
Ellip:
Elliptic or Cauer digital and analog filter design.
[B,A] = ELLIP(N,Rp,Rs,Wn) designs an Nth order low pass digital elliptic filter with Rp decibels of
peak-to-peak ripple and a minimum stop band attenuation of Rs decibels. ELLIP returns the filter
coefficients in length N+1 vectors B (numerator) and A (denominator).The cutoff frequency Wn
must be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. Use Rp = 0.5 and Rs = 20 as
starting points, if you are unsure about choosing them.
If Wn is a two-element vector, Wn = [W1 W2], ELLIP returns an order 2N band pass filter with pass
band W1 < W < W2. [B,A] = ELLIP(N,Rp,Rs,Wn,'high') designs a high pass filter. [B,A] =
ELLIP(N,Rp,Rs,Wn,'stop') is a band stop filter if Wn = [W1 W2]. When used with three left-hand
arguments, as in [Z,P,K] = ELLIP(...), the zeros and poles are returned in length N column vectors Z
and P, and the gain in scalar K. When used with four left-hand arguments, as in [A,B,C,D] =
ELLIP(...), state-space matrices are returned.
ELLIP(N,Rp,Rs,Wn,'s'), ELLIP(N,Rp,Rs,Wn,'high','s') and ELLIP(N,Rp,Rs,Wn,'stop','s')
design analog elliptic filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.
Cheby1:
Chebyshev Type I digital and analog filter design.
[B,A] = CHEBY1(N,R,Wn) designs an Nth order lowpass digital Chebyshev filter with R decibels of
peak-to-peak ripple in the passband. CHEBY1 returns the filter coefficients in length N+1 vectors B
(numerator) and A (denominator). The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0
corresponding to half the sample rate. Use R=0.5 as a starting point, if you are unsure about
choosing R. If Wn is a two-element vector, Wn = [W1 W2], CHEBY1 returns an order 2N bandpass
filter with passband W1 < W < W2. [B,A] = CHEBY1(N,R,Wn,'high') designs a highpass filter. [B,A] =
CHEBY1(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. When used with three left-hand
arguments, as in [Z,P,K] = CHEBY1(...), the zeros and poles are returned in length N column vectors
Z and P, and the gain in scalar K.
When used with four left-hand arguments, as in [A,B,C,D] = CHEBY1(...), state-space
matrices are returned.
CHEBY1(N,R,Wn,'s'), CHEBY1(N,R,Wn,'high','s') and CHEBY1(N,R,Wn,'stop','s')
design analog Chebyshev Type I filters.In this case, Wn is in [rad/s] and it can be greater
than 1.0.
Buttord and Butter Filter:
Designing IIR Low Pass Filter:
Suppose our target is to design a filter to pass all frequencies below 1200 Hz with pass
band ripples = 1 dB and minimum stop band attenuation of 50 dB at 1500 Hz. The
sampling frequency for the filter is 8000 Hz;
Designing IIR High Pass Filter:
We will consider same filter but our target now is to pass all frequencies above 1200 Hz
Designing IIR Band Pass Filter:
Now we wish to design a filter to pass all frequencies between 1200 Hz and 2800 Hz with pass band ripples = 1 dB and minimum stop band attenuation of 50 dB. The sampling frequency for the filter is 8000 Hz;
fs=8000;
[n,w]=buttord(1200/4000,1500/4000,1,50); % finding the order of the filter
[b,a]=butter(n,w); % finding zeros and poles for filter
figure(1)
freqz(b,a,512,8000);
figure(2)
[h,q] = freqz(b,a,512,8000);
plot(q,abs(h)); % Normalized Magnitude plot
grid
figure(3)
f=1200:2:1500;
freqz(b,a,f,8000) % plotting the Transition band
figure(4)
zplane(b,a) % pole zero constellation diagram
[n,w]=buttord(1200/5000,1500/5000,1,50); [b,a]=butter(n,w,'high'); figure(1) freqz(b,a,512,10000); figure(2) [h,q] = freqz(b,a,512,8000); plot(q,abs(h)); % Normalized Magnitude plot grid figure(3) f=1200:2:1500; freqz(b,a,f,10000) figure(4) zplane(b,a)
Designing IIR Band Stop Filter:
[n,w]=buttord([1200/4000,2800/4000],[400/4000, 3200/4000],1,50); [b,a]=butter(n,w,'bandpass'); figure(1) freqz(b,a,128,8000) figure(2) [h,w]=freqz(b,a,128,8000); plot(w,abs(h)) grid figure(3) f=600:2:1200; freqz(b,a,f,8000); % Transition Band figure(4) f=2800:2:3200; freqz(b,a,f,8000); % Transition Band figure(5) zplane(b,a)
[n,w]=buttord([1200/4000,2800/4000],[400/4000, 3200/4000],1,50); [b,a]=butter(n,w,'stop'); figure(1) freqz(b,a,128,8000) [h,w]=freqz(b,a,128,8000); figure(2) plot(w,abs(h)); grid figure(3) f=600:2:1200; freqz(b,a,f,8000); % Transition Band figure(4) f=2800:2:3200; freqz(b,a,f,8000); % Transition Band figure(5) zplane(b,a);
Problems:
Design all above filter using following commands
• Ellipord( ) • Ellip( ) • Cheb1ord( )
• Cheby1( )
EXPERIMENT NO.13
DFT
The discrete Fourier transform (DFT) X[k] of a finite-length sequence x[n] can be easily computed in
MATLAB using the function fft. There are two versions of this function. fft(x) computes the DFT X[k]
of the sequence x[n] where the length of X[k] is the same as that of x[n]. fft(x,L) computes the L-
point DFT of a sequence x[n] of length N where L ≥ N . If L > N , x[n] is zero-padded with L − N
trailing zero-valued samples before the DFT is computed. The inverse discrete Fourier transform
(IDFT) x[n] of a DFT sequence X[k] can likewise be computed using the function ifft, which also has
two versions.
Project 13.1 DFT Properties
Two important concepts used in the application of the DFT are the circular-shift of a sequence and
the circular convolution of two sequences of the same length. As these operations are needed in
verifying certain properties of the DFT, we implement them as MATLAB functions circshift1 and
circonv as indicated below:
function y = circshift1(x,M) % Develops a sequence y obtained by % circularly shifting a finite-length % sequence x by M samples if abs(M) > length(x) M = rem(M,length(x)); end if M < 0 M = M + length(x); end y = [x(M+1:length(x)) x(1:M)]; end
function y = circonv(x1,x2) L1 = length(x1); L2 = length(x2); if L1 ~= L2, error( 'Sequences of unequal lengths' ), end y = zeros(1,L1); x2tr = [x2(1) x2(L2:-1:2)]; for k = 1:L1 sh = circshift1(x2tr,1-k); h = x1.*sh; y(k) = sum(h); end
Program P13_1 can be used to illustrate the concept of circular shift of a finite-length sequence. It
employs the function circshift1
% Program P13_1 % Illustration of Circular Shift of a Sequence clear all ; close all ; clc M=6; a=[0 1 2 3 4 5 6 7 8 9];
b = circshift1(a,M); L = length(a)-1; n = 0:L; subplot(2,1,1); stem(n,a);axis([0,L,min(a),max(a)]); title( 'Original Sequence' ); subplot(2,1,2); stem(n,b);axis([0,L,min(a),max(a)]); title([ 'Sequence Obtained by Circularly Shifting by ' ,num2str(M), 'Samples' ]);
Program P13_2 can be used to illustrate the circular time-shifting property of the DFT. It employs
the function circshift1.
% Program P13_2 % Circular Time-Shifting Property of DFT close all ; clear all ; clc x=[0 2 4 6 8 10 12 14 16]; N = length(x)-1; n = 0:N; y = circshift1(x,5); XF = fft(x); YF = fft(y); subplot(2,2,1) stem(n,abs(XF)); grid title( 'Magnitude of DFT of Original Sequence' ); subplot(2,2,2) stem(n,abs(YF)); grid title( 'Magnitude of DFT of Circularly Shifted Sequence' ); subplot(2,2,3) stem(n,angle(XF)); grid title( 'Phase of DFT of Original Sequence' ); subplot(2,2,4) stem(n,angle(YF)); grid title( 'Phase of DFT of Circularly Shifted Sequence' );
Program P13_3 can be
used to illustrate the
circular convolution
property of the DFT. It
employs the function
circonv.
0 2 4 6 80
20
40
60
80Magnitude of DFT of Original Sequence
0 2 4 6 80
20
40
60
80Magnitude of DFT of Circularly Shifted Sequence
0 2 4 6 8-4
-2
0
2
4Phase of DFT of Original Sequence
0 2 4 6 8-4
-2
0
2
4Phase of DFT of Circularly Shifted Sequence
% Program P13_3 % Circular Convolution Property of DFT clear all ; close all ; clc g1=[1 2 3 4 5 6]; g2=[1 -2 3 3 -2 1]; ycir = circonv(g1,g2); disp( 'Result of circular convolution = ' ); disp(ycir) G1 = fft(g1); % similarly compute fft of g2 and save in G2 yc = real(ifft(G1.*G2)); disp( 'Result of IDFT of the DFT products = ' ); disp(yc)
Program P13_4 can be used to illustrate the relation between circular and linear convolutions
% Program P13_4 % Linear Convolution via Circular Convolution close all ; clear all ; clc g1=[1 2 3 4 5]; g2 = [2 2 0 1 1]; g1e = [g1 zeros(1,length(g2)-1)]; g2e = [g2 zeros(1,length(g1)-1)]; %Do circular convolution of g1e and g2e and save in ylin yourself disp( 'Linear convolution via circular convolution = ' ); disp(ylin); y = conv(g1, g2); disp( 'Direct linear convolution = ' );disp(y)
Program P6_5 can be used to verify the relation between the DFT of a real sequence, and the DFTs
of its periodic even and the periodic odd parts.
% Program P13_5 % Relations between the DFTs of the Periodic Even % and Odd Parts of a Real Sequence close all ; clear all ; clc x=[1 2 4 2 6 32 6 4 2 zeros(1,247)]; x1 = [x(1) x(256:-1:2)]; xe = 0.5 *(x + x1); XF = fft(x); XEF = fft(xe); k = 0:255; subplot(2,2,1); plot(k/128,real(XF)); grid ylabel( 'Amplitude' ); title( 'Re(DFT\x[n]\)' ); subplot(2,2,2); plot(k/128,imag(XF));
grid ylabel( 'Amplitude' ); title( 'Im(DFT\x[n]\)' ); subplot(2,2,3); plot(k/128,real(XEF)); grid xlabel( 'Time index n' ); ylabel( 'Amplitude' ); title( 'Re(DFT\x_e[n]\ )' ); subplot(2,2,4); plot(k/128,imag(XEF)); grid xlabel( 'Time index n' );ylabel( 'Amplitude' ); title( 'Im(DFT\x_e[n]\)' );
Parseval’s relation can be verified using the following program.
% Program P13_6 % Parseval's Relation x = [(1:128) (128:-1:1)]; XF = fft(x); % Take square of vector x and then add all its % entries and save in “a” . Do yourself b = round(sum(abs(XF).^2)/256)
0 0.5 1 1.5 2-50
0
50
100
Am
plitu
de
Re(DFTx[n])
0 0.5 1 1.5 2-100
-50
0
50
100A
mpl
itude
Im(DFTx[n])
0 0.5 1 1.5 2-50
0
50
100
Time index n
Am
plitu
de
Re(DFTxe[n] )
0 0.5 1 1.5 2
-0.5
0
0.5
x 10-14
Time index n
Am
plitu
de
Im(DFTxe[n])
EXPERIMENT NO. 14
(DECIMATION & INTERPOLATION)
The digital signal processing structures discussed so far belong to the class of single-rate systems as
the sampling rates at the input and the output and all internal nodes are the same. There are
applications where it is necessary and often convenient to have unequal rates of sampling at various
parts of the system including the input and the output. In this laboratory exercise you will investigate
first using MATLAB the properties of the up-sampler and the down-sampler, the two basic
components of a multi-rate system. You will then investigate their use in designing more complex
systems, such as interpolators and decimators, and filter banks.
1.1 Basic Sampling Rate Alteration Devices
The objective of this section is to investigate using MATLAB the operations of the up-
sampler and the down-sampler both in the time domain and in the frequency domain.
Project 10.1 Input-Output Relations in the Time-Domain
Program P10_1 can be used to study the operation of a up-sampler.
%Program14_1 %Illustration of Up-Sampling by an Integer Factor % close all ; clear all ; clc n=0:50; x=sin(2*pi*0.12*n); y=zeros(1,3*length(x)); y([1:3:length(y)])=x; subplot(2,1,1) stem(n,x); title( 'InputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' ); subplot(2,1,2) stem(n,y(1:length(x))); title( 'OutputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' );
0 5 10 15 20 25 30 35 40 45 50-1
-0.5
0
0.5
1InputSequence
Timeindexn
Am
plitu
de
0 5 10 15 20 25 30 35 40 45 50-1
-0.5
0
0.5
1OutputSequence
Timeindexn
Am
plitu
de
%ProgramP14_2 %Illustration of Down-Sampling by an Integer Factor % close all ; clear all ; clc n = 0:49; m = 0:50*3-1; x = sin(2*pi*0.042*m); y = x([1:3:length(x)]); subplot(2,1,1) stem(n,x(1:50));axis([0 50 -1.2 1.2]); title( 'InputSequence' ); xlabel( 'Timeindexn' ); ylabel( 'Amplitude' ); subplot(2,1,2) stem(n,y);axis([0 50 -1.2 1.2]); title( 'OutputSequence' ); xlabel( 'Timeindexn' ); ylabel( 'Amplitude' );
The Signal Processing Toolbox includes three M-functions which can be employed to design and
implement an interpolator or a decimator. The three M-functions are decimate, interp, and
resample. Each function is available with several options. In this section you will study the
decimation and interpolation operation using these functions.
Project 14.2 Decimator Design and Implementation
Program P10_3 illustrates the use of the M-function decimate in the design and implementation of
a decimator with an integer-valued decimation factor M. In the option utilized in this program,
decimate designs and uses a lowpass decimation filter with a stopband edge.
%ProgramP14_3 %Illustration of Decimation Process % clear all ; close all ; clc M=input( 'Down-samplingfactor=' ); n=0:99; x=sin(2*pi*0.043*n)+sin(2*pi*0.031*n); y=decimate(x,M, 'fir' ); subplot(2,1,1); stem(n,x(1:100)); title( 'InputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' ); subplot(2,1,2); m=0:(100/M)-1; stem(m,y(1:100/M)); title( 'OutputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' );
1.2 Decimator and Interpolator Design and Implementation
Project 10.3 Interpolator Design and Implementation
Program P10_4 illustrates the use of the M-function interp in the design and implementation of
an interpolator with an integer-valued interpolation factor L. interp designs and uses a lowpass
interpolation filter with a stopband edge satisfying Eq. (10.1).
tuP/QRSt = ,|r| ≤ r/0,/ ≤ |r| ≤
(10.1)
%ProgramP14_4 %Illustration of Interpolation Process % clear all ; close all ; clc L=input( 'Up-samplingfactor=' ); % Generate the input sequence n=0:49; x=sin(2*pi*0.043*n)+sin(2*pi*0.031*n); % Generate the interpolated output sequence y=interp(x,L); % Plot the input and the output sequences
0 10 20 30 40 50 60 70 80 90 100-2
-1
0
1
2InputSequence
Timeindexn
Am
plitu
de
0 5 10 15 20 25 30 35 40 45 50-2
-1
0
1
2OutputSequence
Timeindexn
Am
plitu
de
subplot(2,1,1); stem(n,x(1:50)); title( 'InputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' ); subplot(2,1,2); m=0:(50*L)-1; stem(m,y(1:50*L)); title( 'OutputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' );
Project 10.4 Fractional-Rate Sampling Rate Alteration
Program P10_5 illustrates the use of the M-function resample in the design and implementation
of an interpolator with a fractional-rate interpolation factor L/M. Resample designs and uses a
lowpass interpolation filter with a stopband edge.
% Program14_5 % Illustration of Sampling Rate Alteration by % a Ratio of Two Integers % close all ; clear all ; clc L=input( 'Up-samplingfactor=' ); M=input( 'Down-samplingfactor=' ); n=0:29; x=sin(2*pi*0.43*n)+sin(2*pi*0.31*n);
0 5 10 15 20 25 30 35 40 45 50-2
-1
0
1
2InputSequence
Timeindexn
Am
plitu
de
0 10 20 30 40 50 60 70 80 90 100-2
-1
0
1
2OutputSequence
Timeindexn
Am
plitu
de
y=resample(x,L,M); subplot(2,1,1); stem(n,x(1:30));axis([0 29 -2.2 2.2]); title( 'InputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' ); subplot(2,1,2); m=0:(30*L/M)-1; stem(m,y(1:30*L/M));axis([0 (30*L/M)-1 -2.2 2.2]); title( 'OutputSequence' ); xlabel( 'Timeindexn' );ylabel( 'Amplitude' );
1.3 Lab Task
1. What is the angular frequency in radians of the sinusoidal sequence in Program P10_1? What is its
length? What is the up-sampling factor L?
2. How is the up-sampling operation implemented in Program P10_1?
3. Modify Program P10_1 to study the operation of an up-sampler on a ramp sequence.
4. Program P10_2 can be used to study the operation of a down-sampler
5. What is the angular frequency in radians of the sinusoidal sequence Program P10_2? What is its
length? What is the down-sampling factor M?
6. How is the down-sampling operation implemented in Program P10_2?
7. What are the frequencies of the two sinusoidal sequences forming the input sequence in Program
P10_3? What is the length of the input?
8. What are the type and order of the decimation filter?
9. Run Program P10_3 for M = 4 and comment on the results.
10. Change the frequencies of the two sinusoidal sequences in Program P10_3 in the input signal to
0.045 and 0.029, and the length of the input to 120. Run the modified Program P10 5 for M = 3.
Comment on your results.
EXPERIMENT NO.15
Filter designing by Matlab tools
Description:
There are two tool boxes available for designing, analyzing and for viewing different responses
(Impulse & Step) of FIR and IIR filters.
• fvtool
• fdatool
•
Filter Visualization Tool:
FVTOOL is a Graphical User Interface (GUI) that allows you to analyze digital filters. FVTOOL (B,A)
launches the Filter Visualization Tool and computes the magnitude Response for the filter defined
in B and A. FVTOOL(B,A,B1,A1,...) will perform an analysis on multiple filters. The real advantage of
this visualization tool is that we can view the magnitude response and phase response
simultaneously, the impulse response, step response the coefficients of the filter etc Let us
consider a Low Pass FIR filter of order 30 which passes all frequencies below 2000 Hz with sampling
rate of 8000 Hz.
b=fir1(30,2000/4000,’low’);
fvtool(b,1)
Filter Design & Analysis Tool.
FDATOOL launches the Filter Design & Analysis Tool (FDATool). FDATool is a Graphical User
Interface (GUI) that allows you to design or import, and analyze digital FIR and IIR filters. If the
Filter Design Toolbox is installed, FDATool seamlessly integrates advanced filter design methods
and the ability to quantize filters.
Now we will design a LPF on fdatool, the specifications for the filter are shown in respective
columns of FDA tool
Problems: Design IIR butter worth filter with following specifications
• -50 dB or more for 0 to 1200 Hz ( Stop Band Attenuation ) • -1 dB or less from 2000 Hz to 4000 Hz ( Pass Band Characteristics ) • -50 dB or more above 6000 Hz ( Stop Band Attenuation )
Sampling frequency 16000 Hz
EXPERIMENT No.16
Design an IIR filter to suppress
frequencies of 5 Hz and 30 Hz from
given signal.
Description:
We know from Fourier analysis that signals can be described by a summation of frequency
components. Typically, a filter is used to enhance signals by attenuating unwanted frequency
components and retaining desired frequency components. In this practical we begin by creating a
signals ‘s’ with three sinusoidal components ( at 5,15,30 Hz) and a time vector ‘t’ of 100 samples
with a sampling rate of 100 Hz, and displaying it in the time domain. The Matlab commands are
shown below.
fs=100;
t=(1:100)/fs;
s=sin(2*pi*t*5)+sin(2*pi*t*15)+sin(2*pi*t*30);
plot(t,s)
grid
Now we design a filter to keep the 15 Hz sinusoid and eliminate the 5 and 30 Hz sinusoids. We use
the functions ellipord and ellip to create an infinite impulse response (IIR) filter with a pass band
from 10 to 20 Hz. The ellipord function requires the specification of pass band corner frequencies,
minimum transition band frequencies near the pass band corner frequencies, the maximum pass
band ripple in decibels (dB), and the minimum stop band attenuation in dB. In this example, we
choose a transition frequency to be ±5 Hz near the pass band corners, with a maximum of 0.1 dB
ripple in the pass band, and a minimum of 40 dB attenuation in the stop bands. We start by
determining the minimum order (pass band and stop band frequencies are normalized to the
Nyquist frequency):
wp1 = 10/50;
wp2 = 20/50;
ws1 = 5/50;
ws2 = 25/50;
wp = [Wp1 Wp2];
ws = [Ws1 Ws2];
rp = 0.1;
rs = 40;
[n,wn] = ellipord(wp,ws,rp,rs);
ellipord returns an order of 5, the minimum possible order for a low pass prototype that will meet
the constraints upon transformation to a band pass filter. When we apply this order to the ellip
function, internally we transform the low pass prototype to a band pass filter using the function
lp2bp. This doubles the order, making n = 10. Next we use n, the order, and Wn, the pass band
corner frequencies, to actually design the filter. We also use freqz, a tool for computing and
displaying the frequency response of the descriptive transfer function. When called with no left-
hand-side arguments (i.e., return values), freqz displays the magnitude and phase response of the
filter normalized to the Nyquist frequency.
[b,a] = ellip(n,.1,40,w);
freqz(b,a,128,100)
[h,w]=freqz(b,a,128,100);
plot(w,abs(h));
grid
title(‘Normalized Magnitude Response’);
axis([0 50 0 1.2]);
figure(4)
sf=filter(b,a,s); % Time domain Response of the Filter
plot(t,sf)
grid
xlabel('Time (seconds)');
ylabel('Signal Amplitude');
title('Filtered Signal only 15 Hz frequency');
Problem: Design an IIR filter to remove 100 and 150 frequencies from above signal. x=1+sin (2*pi*50*t) + sin (2*pi*100*t) + 0.5 sin (2*pi*125*t) + 0.25 sin (2*pi*150*t);
Top Related