DSP - 502 - Lab Manual
DSP - 502 - Lab Manual
DepartmentofElectronicsandCommunication
Engineering
LABMANUAL
DigitalSignalProcessingLabManual(BEC5
02)
Prepared by Swetha
Rani M Assistant
Professor Department
of
Electronics and Communication
Engineering
VijayaVittalaInstituteOfTechnology
DepartmentofElectronicsandCommunication
Engineering
AboutTheCollege
Vision
EmergeasapremierInstituteinofferingtechnicaleducationandresearchopportunitiestome
etthe growing technological needs of the society.
Mission
Toprovideholisticlearningambianceformoderneducationinengineeringblended
withethical values.
Topromoteallroundpersonalitydevelopmentandenhancecareeropportuniti
esthrough interaction with alumni, academia and industry.
Toinculcatearesearchcultureleading toinnovatorsandentrepreneurs.
VijayaVittalaInstituteOfTechnology
DepartmentofElectronicsandCommunication
Engineering
AboutTheDepartment
TheDepartmentofElectronicsEngineeringwasestablishedintheyear2009.Fromtheveryinc
eption,this department has established itself as an efficient, self reliant and quality
conscious entity with the sole aim of producing the most energetic, enthusiastic and
professionally competent Electronic Engineers with ability to take up the challenges
posed to them..
The department of Electronics Engineering at V.V.I.T. offers, Bachelor's Degree in
Electronics Engineering,Thedepartmentaims
todeepentheknowledgeandskillsofthestudentsonthebasic concepts and theories that
will equip them in their professional work involving analysis, systems
implementation,operation,production,and maintenance ofthe variousapplicationsinthe
field of Electronics and Communications Engineering.
Vision
Tobethehubofexcellenceinfrontier areas.
Mission
Transforminglifeofstudentsbyfosteringdeepunderstandingofintellectuallychall
engingand significant learning to become technically competent
professionals and socially responsible citizens.
TocreateanenablingenvironmentforR&Dand
collaborativeactivitieswithindustryandacademiaforsustainablegrowth.
ProgramOutcomes
Programtogeneratethefollowingdiscretetimesignals.a)Unitsamplesequenc
1
e,b)Unit step sequence, c) Exponential sequence, d)Sinusoidal sequence,
e) Random sequence
Programtoperformthefollowingoperationsonsignals.a)Signaladdition,b)Sig
2
nal multiplication, c)Scaling, d) Shifting, e)Folding
Using the DFT and IDFT, compute the following for any two given
6 sequences
a) Circular convolution b)Linear convolution
VerificationofLinearityproperty,circulartimeshiftproperty&circularfrequenc
7
yshift property of DFT.
DesignandimplementationofdigitallowpassFIRfilterusingawindowtomeetth
8
egiven specifications
DesignandimplementationofdigitalhighpassFIRfilterusingawindowtomeet
9
the given specifications
DesignandimplementationofdigitalIIRButterworthlowpassfiltertomeetthegi
10
ven specifications.
DesignandimplementationofdigitalIIRButterworthhighpassfiltertomeetthe
11
given specifications
DSPLABBEC502 INTRODUCTIONTOMAT 2024-25
LAB
1 DeptOfECE,VVIT
DSPLABBEC502 2024-25
At its core, MATLAB is essentially a set (a“toolbox”) of routines (called
“mfiles’ or “mexfiles”) that sit on your computer and a window that
allows you to create new variables with names (e.g. voltage and time)
and process those variables with any of those routines (e.g. plot
voltage against time ,find the largest voltage, etc.)
MATLAB®is a high-level language and interactive environment
that enables you to perform computationally intensive tasks faster
than with traditional programming languages such as C,C++,and
Fortran.
KeyFeatures:
High-level language for technical computing.
Development environment for managing code, files, and data.
Interactive tools for iterative exploration, design, and problem solving.
Mathematicalfunctionsforlinearalgebra,statistics,Fourieranalysis,
Filtering, optimization, and numerical integration.
2-Dand3-Dgraphicsfunctionsforvisualizingdata.
Tools for building custom graphical user interfaces.
Functions for integrating MATLAB based algorithms with
external applications and languages, such as C, C++, Fortran,
Java, COM, and Microsoft® Excel®.
MATLAB Windows:
MATLAB works with through three basic windows
Command Window: This is the main window. It is characterized by
MATLAB command prompt(>>) when you launch the application
programMATLABputsyouinthiswindowallcommandsincludingthosefo
ruser- written programs, are typed in this window at the MATLAB
prompt. Graphics window: The output of all graphics commands
typed in the command window are flushed to the graphics or figure
window, a separate gray window with white background color the
user can create as many windows as the system memory will allow.
Edit window: This is where you write edit, create and save your own
programs in files called M files.
2 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Input-output:
MATLAB supports interactive computation taking the input from
the screen
andflushingtheoutputtothescreen.Inadditionitcanreadinputfilesand
write output files.
DataType: The fundamental data-type in MATLAB is the array. It
encompasses several distinct data objects- integers, real numbers,
matrices. Character strings, structures and cells. There is no need
to declare variables as real or complex, MATLAB automatically sets
the variable to be real.
Dimensioning: Dimensioning is automatic in MATLAB. No dimension
statements are required for vectors or arrays. We can find the
dimensions of an existing matrix or a vector with the size and
length commands.
Basic Instructions in Matlab
1) T=0:1:10
This instruction indicates a vector T which as initial value 0 and
final value 10with an increment of 1.
Therefore,
T=
0 1 2 3 4 5 6 7 8 9 10
2) T=Zeros(2,3)
The above instruction creates a vector of two rows and three
columns whose values are zero.
T=
0 0 0
0 0 0
3) T=Ones(3,2)
The above instruction creates a vector of three rows and two
columns whose values are one
T=
1 1
1 1
1 1
3 DeptOfECE,VVIT
DSPLABBEC502 2024-25
4) a=[123] b=[456]
a.*b= [41018], which is the result of individual elements.
1 2 3
4 5 6
7 8 10
a
+10
ans=
11 12 13
14 15 16
17 18 20
sin(
a)
ans=
4 DeptOfECE,VVIT
DSPLABBEC502 2024-25
ans=
1 4 7
2 5 8
3 6 10
You can perform standard matrix multiplication, which computes
the inner products between rows and columns, using the *
operator. For example, confirm that a matrix times its inverse
returns the identity matrix:
p=a*inv(a)
p=
1.0000 0 -
0.000
0
0 1.0000 0
0 0 1.000
0
1 4 9
16 25 36
49 64 10
5 DeptOfECE,VVIT
DSPLABBEC502 2024-25
0
The matrix operators for multiplication, division, and power each have
a corresponding array operator that operates element-wise. For
example, raise each element of a to the third power:
6 DeptOfECE,VVIT
DSPLABBEC502 2024-25
a.^3
ans=
1 8 27
64 125 216
Concatenation:
Concatenation is the process of joining arrays to make larger ones.
Infact, you made your first array by concatenating its individual
elements. The pair of square brackets[] is the concatenation operator.
A
=[a,a] A
=
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
A=
[a;a] A =
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
7 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Complex Numbers:
Complex numbers have both real and imaginary parts, where the
imaginary unit is the square root of –1.
sqrt(-1)
ans=0+1.0000i
either I or j. c=[3+4i,4+3j,-i,10j]
Array Indexing:
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
8 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Using a single subscript to refer to a particular element in an array is
called
Linear indexing.
If you try to refer to elements outside an array on the right side
of an assignment statement, MATLAB throws an error.
test=A(4,5)
Attempted to access A(4,5); index out of bounds because
size(A)=[4,4]. However, on the left side of an assignment
statement, you can specify elements outside the current
dimensions. The size of the array increases to accommodate the
newcomers.
A(4,5)=17
Example:
A=
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
Torefertomultipleelementsofanarray,usethecolonoperator,whichallows
youtospecifyarangeoftheformstart:end.Forexample,listtheelementsin
the first three rows and the second column of A:
A(1:3,2)
ans=2
11
7
Thecolonalone,withoutstartorendvalues,specifiesalloftheelements
inthatdimension.Forexample,selectallthecolumnsinthethirdrowofA:
A(3,:)
ans= 9 7 6 12 0
The colon operator also allows you to create an equally
spaced vector of values using themore
generalformstart:step:end.
9 DeptOfECE,VVIT
DSPLABBEC502 2024-25
6) Plot
(t,m)
Ifm=[6789]
t=[1234]
This instruction will display a figure window which
indicates the plot ofm versus t.
7) Stem(t,m)
ThisInstructionwilldisplayafigurewindowasshownbelow,
10 DeptOfECE,VVIT
DSPLABBEC502 2024-25
1. Programtogeneratethefollowingdiscrete-timesignals:
a) Unitsamplesequence
b) Unitstepsequence
c) Exponentialsequence
d) Sinusoidalsequence
e) Randomsequence
Aim:Generationofunitsamplesignal.
Theory:
Theunitsamplesequence,often calledthediscrete-timedeltafunction
orKroneckerdeltaδ[n], is a
fundamentalbuildingblockforanalyzinganddescribingdiscrete-timesystems.
Mathematically,theunitsamplesequenceδ[n]-delta[n]isdefinedas:
MATLABcode:
n=-10:10;%Definetherangeofn
x=(n==0);%Generateunitsamplesequence stem(n,
x); % Plot the sequence
title('UnitSampleSequence');
xlabel('n');
ylabel('x[n]');
grid on;
ExpectedOutputSignal:
11 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Aim:Generationofunitstepsignal.
Theory:
Theunitstepsequenceisafundamentaldiscrete-
timesignalthatplaysacrucialrolein analyzingandrepresentingdiscrete-
timesystems.Itiscommonlydenotedbyu[n]andis
usedextensivelyinsignalprocessing,controlsystems,anddigitalcommunicati
ons.
Theunitstepsequenceu[n]isdefinedmathematicallyasfollows:
MATLABcode:
n=-10:10;%Definetherangeofn
u=(n>=0);%Generatetheunitstepsequence
stem(n, u); % Plot the unit step sequence
xlabel('Time');
ylabel('Amplitude');
title('Discretetimeunitstepfunction');
ExpectedOutput:
Aim:Generation of
exponentialsequence.Theory:
Anexponentialsequenceisatypeofdiscrete-
timesignalthatisfundamentalforanalyzing andunderstanding
thebehaviorofdiscrete-timesystems,particularlylineartime-invariant
(LTI)systems.Exponential sequencesoftenarisein the studyof
systemresponses,stability analysis, and signal representation.
Adiscrete-timeexponentialsequenceisdescribedbythegeneralform:
12 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABcode:
x= -2:0.5:10;
y=exp(x/2);
stem(x,y);
title("TheExponentialSequence");
xlabel('n');
ylabel('exp(n)');
grid on;
ExpectedOutputsignal:
Aim:Generationofsinusoidalsequence.
Theory:
A sinusoidal signalisoneof the mostfundamentalandwidelyusedtypesof
signalsforanalyzing and
understandingsystems,particularlyinthecontextofsignalprocessing,communicati
ons,and
controlsystems.Asinusoidalsignaldescribesperiodicoscillationsandservesasthebu
ildingblock for many complex signals.
A sinusoidalsignalinthediscrete-timedomainistypicallydescribedbythegeneralform:
13 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABCode:
t=0:0.2:2*pi;%Timevector A
= 1; % Amplitude
f= 1; % Frequency
y=A*sin(f*t);%Sinusoidalsequence stem(t, y);
xlabel('Time (s)');
ylabel('Amplitude');
title('SinusoidalSequence'
); grid on;
ExpectedOutput:
Aim:GenerationofRandomsequence.
Theory:
Arandomsequence signalrefersto adiscrete-timesignalwhose
valuesaregovernedbya probabilisticprocess, meaning
thateachvalueinthesequenceisnotdeterministicbutinstead
followsaprobabilitydistribution.Randomsequencesarefundamentalinfieldssuchas
signal
processing,communications,andcontrolsystems,wherenoise,uncertainty,andstoc
hastic processes play a key role.
Arandomsequencesignal,typicallydenotedbyx[n],isasequencewhereeachsamplex
[n]isa randomvariable.Mathematically, the sequencecan berepresentedas:
14 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Eachelementofthesequencex[n]isdrawnfromaprobabilitydistribution(e.g.,G
aussian, uniform, Poisson), making the overall sequence a realization of a
stochastic process.
MATLABCode:
n=10;%Lengthoftherandomsequence
random_sequence=rand(1,n); %Generatearandomsequenceoflengthn
stem(random_sequence); % Display the random sequence
ExpectedOutput:
15 DeptOfECE,VVIT
DSPLABBEC502 2024-25
2. Programtoperformthefollowingoperationsonthesignal:
a)Signaladdition
b)Signalmultiplication
c)Scaling
d)Shifting
e)Folding
Aim:Toaddtwosignals.
Theory:
Addingtwosignalsisfundamentalinsignalprocessing.Whentwosignalsa
re combined,their amplitudes aresummed ateachpointintime.This
canbe expressed mathematically as:
y(t)=x1(t)+x2(t)
wherex1(t)andx2(t)arethetwoinputsignals,andy(t)istheresultingsigna
l.
MATLABCode:
%Definethetimevector t
= 0:0.01:1;
%Definetwo signals
signal1 = sin(2 * pi * 5 * t); % 5 Hz sine wave
signal2=0.5*sin(2*pi*5*t);%10Hzsinewave
%Plotthesignals
figure;subplot(3
, 1, 1); plot(t,
signal1);
title('Signal1(5Hz)');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t,signal2);
title('Signal2(10Hz)');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3, 1, 3);
plot(t,resultant_signal);
title('ResultantSignal(Signal1+Signal2)');
xlabel('Time (s)');
ylabel('Amplitude');
16 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Expectedoutput:
Aim:Tomultiplytwosignals.
Theory:
Multiplyingtwosignalscanbedescribedmathematicallyas:y(t)=x1(t)*
x2(t)where
x1(t)andx2(t)arethetwoinputsignalsandy(t)istheoutputsignal.Thiso
peration
issignificantinmodulationschemesandcanproducesignalsbasedonth
einputsat new frequencies.
MATLABCode:
%Importnecessarylibraries
%Noadditionallibrariesareneededforbasicsignal multiplication
%Definetwosamplesignals
t=0:0.01:1;%Timevector
signal1 = sin(2 * pi * 5 * t); % First signal (sine wave)
signal2=cos(2*pi*5*t);%Secondsignal(cosinewave)
%Performsignalmultiplication
result = signal1 .* signal2;
%Plotthesignalsandtheresult
figure;
subplot(3,1,1);
plot(t,signal1);
title('Signal1(SineWave)');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t,signal2);
title('Signal2(CosineWave)');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,3);
plot(t, result);
title('ResultofSignalMultiplication');
xlabel('Time (s)');
ylabel('Amplitude');
17 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Expectedoutput:
Aim:ToScaleasignal.
Theory:
Scalingasignalinvolvesmultiplyingtheamplitudeofthesignalbya
constant factor. This can be mathematically expressed as:
y(t)=K⋅x(t)y(t)
wherey(t)isthescaledoutputsignal,x(t)istheinputsignal,and
Kisthescaling
factor.Ascalingfactorgreaterthan1increasestheamplitude,whileaf
actorless than 1 decreases it.
MATLABCode:
%SignalScalinginMATLAB
% Generate a sample
signal
t=0:0.01:1;%Timevector
signal=sin(2*pi*5*t);%Samplesignal(sinewave)
% Scaling factor
scaling_factor=5;
%Scalethe signal
scaled_signal=scaling_factor*signal;
18 DeptOfECE,VVIT
DSPLABBEC502 2024-25
%Plotoriginalandscaledsignals
figure;
subplot(2,1,1);
plot(t, signal);
title('OriginalSignal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(2, 1, 2);
plot(t,scaled_signal)
;
title('ScaledSignal')
; xlabel('Time (s)');
ylabel('Amplitude');
Expectedoutput:
Aim:Toshifta signal.
Theory:
Shiftingasignalinvolveschangingitstimedomainrepresentationwithoutalteringitss
hape.This can be done by adding or subtracting a constant value from the time
variable t in the signal equation:
y(t)=x(t−t0)
wheret0isthetimeshift.Positive t0resultsinarightwardshift(delay),whilenegativet0
resultsin a leftward shift (advance).
19 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABCode:
%Definetheoriginalsignal t
= 0:0.01:1; % Time vector
signal=sin(2*pi*5*t);%Originalsignal(sinewave)
%Definetheshiftamount
shift_amount=0.2;%Shifttotherightby0.2seconds
%Performtheshiftoperation
t_shifted = t + shift_amount; % Shifted time vector
signal_shifted=sin(2*pi*5*t_shifted);%Shiftedsignal
%Plottheoriginalandshiftedsignals figure;
subplot(2,1,1);
plot(t, signal);
title('OriginalSignal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(2, 1, 2);
plot(t_shifted,signal_shifted
); title('Shifted Signal');
xlabel('Time (s)');
ylabel('Amplitude');
Expectedoutput:
20 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Aim:Tofolda signal.
Theory:
Foldingasignalinvolvesreflectingitaboutaspecifiedaxis,us
uallythe vertical axis (time reversal). Mathematically,
this can be expressed as y(t)=x(−t). This transformation
effectively reverses the signal in time, allowing for
analysis of its properties and behaviors.
MATLABCode:
%Importnecessarylibraries
%Noadditionallibrariesareneededforthisoperation
%Definethe signal
t=0:0.01:1;%Timevector
signal=sin(2*pi*5*t);%Examplesignal(sinewave)
%Performfoldingoperation
folded_signal=flip(signal);%Flipthesignal
%Plotoriginalandfoldedsignals
figure;
subplot(2,1,1);
plot(t, signal);
title('OriginalSignal');
xlabel('Time (s)');
ylabel('Amplitude');
ylabel('Amplitude');
subplot(2, 1, 2);
plot(t,folded_signal)
;
title('FoldedSignal')
; xlabel('Time (s)');
ylabel('Amplitude');
ylabel('Amplitude');
Expectedoutput:
21 DeptOfECE,VVIT
DSPLABBEC502 2024-25
3. Programtoperformconvolutionoftwogivensequences(withoutusinga
built-in
function)anddisplaythesignals.
AIM:DevelopaMATLABcodetoperformconvolutionoftwogivensequences(witho
utusinga built-in function) and display the signals.
THEORY:
Convolution is a mathematical operation that combines two signals to produce
a third signal,
representingtheoverlapofonesignalasitpassesoveranother.Mathematically,thec
onvolution of two continuous-time signals x(t)and h(t) is defined as:
∞
y(t)=(x∗h)(t)=∫−∞x(τ)h(t−τ)dτ.
Indiscretetime,theconvolutionisdefinedas:
y[n]=∑∞
𝑚=−∞ 𝑥[𝑚]ℎ[𝑛−𝑚].
MATLABCode:
%Definethetwosignals(youcanmodifythese) x =
[1, 2, 3]; % First signal
h=[0.5,1,0.5];%Secondsignal
%Lengthsofthesignals
len_x = length(x);
len_h= length(h);
%Lengthoftheoutputsignal
len_y = len_x + len_h - 1;
%Preallocatetheoutputsignal
y = zeros(1, len_y);
%Performconvolutionmanually
for n = 1:len_y
fork=1: len_h
if(n-k+1)>0&&(n-k+1)<=len_x y(n) = y(n) +
x(n - k + 1) * h(k);
end
end en
d
22 DeptOfECE,VVIT
DSPLABBEC502 2024-25
disp('ConvolvedSignal(y):');
disp(y);
23 DeptOfECE,VVIT
DSPLABBEC502 2024-25
%Optional:Plottingthesignals
figure;
subplot(3,1, 1);
stem(x, 'filled');
title('FirstSignal(x)');
xlabel('Sample Index');
ylabel('Amplitude');
subplot(3,1, 2);
stem(h, 'filled');
title('SecondSignal(h)');
xlabel('Sample Index');
ylabel('Amplitude');
subplot(3,1, 3);
stem(y, 'filled');
title('ConvolvedSignal(y)');
xlabel('Sample Index');
ylabel('Amplitude');
or
%Definethetwosignals(youcanmodifythese) x =
[1, 2, 3]; % First signal
h=[0.5,1,0.5];%Secondsignal y =
conv(x,h);
%Optional:Plottingthesignals
figure;
subplot(3,1, 1);
stem(x, 'filled');
title('FirstSignal(x)');
xlabel('Sample Index');
ylabel('Amplitude');
subplot(3,1, 2);
stem(h, 'filled');
title('SecondSignal(h)');
xlabel('Sample Index');
ylabel('Amplitude');
subplot(3,1, 3);
stem(y, 'filled');
title('ConvolvedSignal(y)');
xlabel('Sample Index');
ylabel('Amplitude');
24 DeptOfECE,VVIT
DSPLABBEC502 2024-25
EXPECTED OUTPUT:
25 DeptOfECE,VVIT
DSPLABBEC502 2024-25
4. Consideracausalsystemy(n)=0.9y(n-1)+x(n).
DetermineH(z)andsketchitspole-zeroplot
Plot|H(ejω)|and∠H(ejω)
Determinetheimpulseresponseh(n)
Aim:TodetermineH(z)andimpulseresponseh(n)thenplot
i) Pole-zeroplot
ii)|H(ejω)|and∠H(ejω)
Theory:
Toanalyzethecausalsystem
𝑦(𝑛) =0.9𝑦(𝑛−1)+𝑥(𝑛)
y(n)=0.9y(n−1)+x(n),weneedtofollowthese steps:
1. Determine𝐻andsketch thepole-zeroplot
Thesystemisalineardifferenceequation,andwecanexpressitintermsoftheZ-
transformto find
𝐻(𝑧).
Thedifferenceequationis:
𝑦(𝑛)=0.9𝑦(𝑛−1)+𝑥(𝑛)
TakingtheZ-transformonbothsides,assuminginitialrestconditions:
𝑌(𝑧)=0.9𝑧−1𝑌(𝑧)
+𝑋(𝑧)
Solvingfor𝐻(𝑧)=𝑌(𝑧)/
𝑋(𝑧):
𝑌(𝑧) 1
𝑋(𝑧) 1−0.9𝑧−1
H(z)= =
2.Plot
∣𝐻(𝑒𝑗𝜔)∣and∠𝐻(𝑒𝑗𝜔)
Forthefrequencyresponse,weevaluate𝐻(𝑧)on theunitcircle(𝑧=𝑒𝑗𝜔).
3. Determinetheimpulseresponse
ℎ(𝑛)
26 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Theimpulseresponseℎ(n)istheinverseZ-transformofH(𝑧),andforthissystem,
ℎ(𝑛)=(0.9)𝑛𝑢(𝑛),whereu(n)istheunitstepfunction.
27 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABCode:
%Given parameters
a=0.9;%Coefficientofy(n-1)inthedifferenceequation
%Plotpole-zeroplot
figure;
pzmap(H_z);
title('Pole-ZeroPlotofH(z)');
grid on;
%DefinethesystemfunctionH(e^jω)H=1
./(1-0.9*exp(-1j*omega));
%Calculatemagnitudeandphase
magnitude = abs(H);
phase= angle(H);
% Plot
magnitude
figure;
subplot(2,1,1);
plot(omega, magnitude); title('|
H(e^{j\omega})|'); xlabel('\
omega(radians)');
ylabel('Magnitude');
gridon;
% Plot phase
subplot(2, 1, 2);
plot(omega,phase);
title('\angleH(e^{j\
omega})'); xlabel('\omega
(radians)');
ylabel('Phase(radians)');gri
d on;
%3.ImpulseResponse h(n)
n = 0:20; %Timevectorforimpulseresponse
h_n=a.^n; %Impulseresponseh(n)=(0.9)^nforcausalsystem
%Plotimpulseresponse
figure;
stem(n, h_n, 'filled');
title('ImpulseResponseh(n)')
; xlabel('n');
ylabel('h(n)');
grid on;
28 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Expectedoutput:
29 DeptOfECE,VVIT
DSPLABBEC502 2024-25
30 DeptOfECE,VVIT
DSPLABBEC502 2024-25
5. ComputationofNpointDFTofagivensequence(withoutusingabuilt-in
function)andplotthemagnitudeandphasespectrum
Aim:
Thisexperiment usesMATLAB to compute the N-pointDiscrete
FourierTransform (DFT) ofa discrete-
timesignalandanalyzethefrequencydomainrepresentation.Theexperimentaim
sto familiarize with the mathematical formulation of DFT, its practical
implementation, and the interpretation of results in the frequency domain.
Theory:
The Discrete Fourier Transform (DFT) is a fundamental tool in digital signal
processing, used to analyze the frequency content of discrete-time signals. The
DFT transforms a finite sequence of time-
domainsamplesintoasequenceoffrequency-
domainsamples.Itisdefinedmathematically for a sequence𝑥(𝑛)
x(n)oflength Nas:
Where:
X(k)istheDFToutputrepresentingthefrequencydomaincomponents.
x(n)istheinputsequenceinthetimedomain.
Nisthetotalnumber ofpointsintheDFT(lengthofthesequence).
Krepresentsthe frequencyindex (rangingfrom0toN-1).
j2πk𝚗
𝑒−𝑁
isthecomplexexponential,representingthebasisfunctionforthefrequency
components.
31 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABCode:
%Definetheinputsequencex(n)
x=[1,2,3,4];%Examplesequence,youcanmodifythisasneeded N =
length(x); % Number of points in the DFT
%InitializetheDFTresultX(k)
X=zeros(1,N);
%ComputetheDFTmanually for
k = 0:N-1
forn=0:N-1
X(k+1)=X(k+1)+x(n+1)*exp(-1j*2*pi*k*n/N);
end
end
%CalculatethemagnitudeandphaseoftheDFT
magnitude = abs(X);
phase= angle(X);
%Plotthemagnitudespectrum|X(k)|
figure;
subplot(2,1, 1);
stem(0:N-1, magnitude, 'filled');
title('MagnitudeSpectrum|X(k)|');
xlabel('Frequency index k');
ylabel('|X(k)|');
gridon;
%Plotthephasespectrum∠X(k)
subplot(2, 1, 2);
stem(0:N-1, phase, 'filled');
title('PhaseSpectrum\angleX(k)');
xlabel('Frequency index k');
ylabel('Phase (radians)');
gridon;
ExpectedOutput:
32 DeptOfECE,VVIT
DSPLABBEC502 2024-25
6. UsingtheDFTandIDFT,computethefollowingforanytwogivenseque
nces a) Circular convolution b) Linear convolution
Aim:
Thisexperimentaimsto computethecircularconvolutionandlinear
convolutionforanytwogiven sequences
Theory:
Convolutionisamathematicaloperationusedtocombinetwosignals.Incircularconvo
lution,the signals are treated as periodic, meaning that the computation "wraps
around" the boundaries.
Circularconvolutiondiffersfromlinearconvolutioninthatitassumes
thesignalsareperiodicand results in a periodic sequence.
Giventwodiscrete-time sequences:
x[n]={x0,x1,
…,xN−1} and
h[n]={h0, h1,…, hN−1}
Thecircularconvolutiony[n]ofx[n]andh[n]isdefine
𝑚=
das: y[n]= ∑𝑁−1x[m] ⋅ h[(n − m) mod N]
Where:
Nisthelengthoftheperiodic signals.
Themodulooperationensuresthattheindices"wraparound"whentheyexceed
thesignal length.
Circularconvolutioncanalsobeefficientlycomputedinthefrequencydomainusingthe
Discrete Fourier Transform (DFT):
y[n]=IDFT(DFT(x[n])⋅DFT(h[n]))
Where:
DFTrepresentstheDiscreteFourierTransform,and
IDFTistheInverseDiscreteFourierTransform.
Linearconvolution,specifically,involvessummingtheweightedsuperpositionsofone
signal shifted over another. It is widely used in the analysis of signals and
systems, particularly in determining the output of an LTI system.
Giventwodiscrete-
timesignals: x[n]= {x0,
x1,…,xL−1}
33 DeptOfECE,VVIT
DSPLABBEC502 2024-25
h[n]={h0,h1,…,hM−1}
34 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Thelinearconvolutiony[n]ofx[n]andh[n]isdefinedas:
y[n]=∑𝑀−1
𝑚= x[m]⋅ h[n−
m], Where:
L is the length of the first signal x[n],
M is the length of the second signal h[n], and
y[n] is the linear convolution result, with a length of L+M−1.
Linearconvolutioncanbethoughtofastheprocessof"sliding"onesignaloveranotheran
d summing the overlap at each step, which gives the resulting output signal.
MATLABCode:
a) Circular convolution
%Definetwoinputsequences
x=[1,2,3,4];%Examplesequencex
h=[1,1,1,1];%Examplesequenceh
%Makesurethesequencesareofthesamelength N =
max(length(x), length(h));
x=[x,zeros(1,N- length(x))];
h=[h,zeros(1,N- length(h))];
%ComputetheDFTofthesequences
X=fft(x,N);
H=fft(h,N);
%Performelement-wisemultiplicationinthefrequencydomain Y
= X .* H;
%ComputetheinverseDFTtogetthecircularconvolutionresult y =
ifft(Y);
%Displaythe result
disp('CircularConvolutionResult:')
; disp(y);
Expected output:
35 DeptOfECE,VVIT
DSPLABBEC502 2024-25
b) Linear convolution
%Definetheinputsequences
x=[1,2,3,4];%Firstsequence
h=[1,1, 1]; %Secondsequence
%Computethelengthsofthesequences N
= length(x);
M = length(h);
%ComputetheDFTofbothsequences
X=fft(x,N +M- 1);
H=fft(h,N +M- 1);
%ComputethelinearconvolutionusingtheDFT Y
= X .* H;
%ComputetheIDFTtogetthelinearconvolutionresult y =
ifft(Y);
%Displaythe result
disp('LinearConvolutionResult:');
disp(y);
Expected Output:
1 3 6 9 7 4
36 DeptOfECE,VVIT
DSPLABBEC502 2024-25
7. Verification of Linearity property, circular time shift property &
circular frequency
Shift property of DFT
Aim: This experiment aims to compute and verify DFT's Linearity, circular time
shift, and circular frequency shift properties.
Theory:
Linearity property of DFT:
ToverifythelinearitypropertyinMATLAB, we
canapplyasystemtoacombinationofsignalsand then check whether the system
behaves linearly. A system is linear if it satisfies the following two properties:
1. Additivity: T{x1(n)
+x2(n)}=T{x1(n)}
+T{x2(n)}
2. Homogeneity(Sca
ling):
T{a⋅x(n)}=a⋅T{x(n)}
WhereTrepresentsthesystem,andx(n)istheinputsignal.
CircularTimeShiftPropertyofDFT:
Thecirculartimeshiftpropertystatesthatifasequencex(n)x(n)x(n)undergoesacir
culartime shift, the DFT of the shifted sequence corresponds to a phase shift
in the DFT of the original sequence. Specifically:
xshifted(n)=x((n−k)modN)
TheDFToftheshiftedsequenceXshifted(k)isrelatedtotheDFToftheoriginalsequence
X(k)as:
2𝜋𝑘𝑚
−𝑗
Xshifted(k)=X(k)⋅𝑒 𝑁
Where:
kisthefrequency index.
misthecircularshiftamount.
Nisthelengthofthe sequence.
CircularfrequencyshiftpropertyofDFT
37 DeptOfECE,VVIT
DSPLABBEC502 2024-25
The circular frequency shift property states that if the DFT of a sequence x(n) is
shifted in the
frequencydomainbymultiplyingthesequencebyacomplexexponential,theresultisa
circular time shift in the original sequence.
38 DeptOfECE,VVIT
DSPLABBEC502 2024-25
IfX(k)istheDFTofx(n),thecircularfrequencyshiftpropertyis:
2𝜋𝑘0𝑚
−𝑗
xshifted(n)=x(n)⋅𝑒 𝑁
TheDFTofthemodifiedsequencexshifted(n)resultsinacircularshiftinthefrequenc
ydomain: Xshifted(k)=X((k−k0)modN)
Where:
k0istheamountofcircularfrequencyshift.
Nisthelengthofthe signal.
MATLABCode:
%Importnecessarylibraries
clc;
clear;
closeall;
% Parameters
N=16; %DFTsize
n=0:N-1;%Timeindex
%Originalsignal
x=sin(2*pi*0.1*n)+0.5*sin(2*pi*0.2*n);
%Linearityproperty
a = 2; b = 3;
y_linear=a*x+b*x;%Linearcombination Y_linear
= fft(y_linear, N);
Y1=a*fft(x,N)+b*fft(x,N);%DFToflinearcombination
%Circulartimeshiftproperty
k = 5; % Shift amount
x_shifted = circshift(x,
k);
Y_shifted=fft(x_shifted,N);
Y_circular_shift=exp(-1j*2*pi*k*(0:N-1)/N).*fft(x,N);%DFTofshiftedsignal
%Circularfrequencyshiftproperty
f_shift = 0.1; % Frequency shift
x_freq_shifted=x.*exp(1j*2*pi*f_shift*n);
Y_freq_shifted = fft(x_freq_shifted, N);
Y_circular_freq_shift=fft(x,N).*exp(1j*2*pi*f_shift*(0:N-1)/N);%DFToffrequency
shifted signal
%Plotting
figure;
%Linearityproperty
subplot(3, 2, 1);
stem(n,abs(Y_linear),'filled');
title('Linearity Property');
xlabel('Frequency Index');
ylabel('Magnitude');
39 DeptOfECE,VVIT
DSPLABBEC502 2024-25
subplot(3,2, 2);
stem(n, abs(Y_linear), 'filled');
title('LinearityProperty-Error');
xlabel('Frequency Index');
ylabel('Magnitude');
%Circulartimeshiftproperty
subplot(3, 2, 3);
stem(n, abs(Y_shifted), 'filled');
title('CircularTimeShiftProperty');
xlabel('Frequency Index');
ylabel('Magnitude');
subplot(3,2, 4);
stem(n,abs(Y_shifted-Y_circular_shift),'filled');
title('Circular Time Shift Property - Error');
xlabel('Frequency Index');
ylabel('Magnitude');
%Circularfrequencyshiftproperty
subplot(3, 2, 5);
stem(n, abs(Y_freq_shifted), 'filled');
title('CircularFrequencyShiftProperty');
xlabel('Frequency Index');
ylabel('Magnitude');
subplot(3,2, 6);
stem(n,abs(Y_freq_shifted-Y_circular_freq_shift),'filled');
title('Circular Frequency Shift Property - Error');
xlabel('Frequency Index');
ylabel('Magnitude');
sgtitle('DFTPropertiesVerification');
Expected Output:
40 DeptOfECE,VVIT
DSPLABBEC502 2024-25
8. DesignandimplementationofdigitallowpassFIRfilterusingawindowtomeett
hegiven specifications
Aim: To design and implement digital lowpass FIR filter using a window to meet
the given specifications
Theory:
FIR filters are filters with a finite-duration impulse response, meaning that they
only depend on a finite number of input samples. FIR filters are commonly used
due to their inherent stability and linearphasecharacteristics.Alow-
passfilterallowsfrequenciesbelowacertaincutofffrequencyto pass while
attenuating frequencies higher than the cutoff.
The general transfer function of an FIR filter of order N is given by:
Whereωc=2πfcisthecutofffrequency.
Thecorrespondingidealimpulseresponsehd[n]inthetimedomaincanbederivedas:
This is known as the sinc function. However, the ideal impulse response is
infinitely long, and
truncationisrequiredtomakeitrealizable.Thistruncationisachievedusinga
windowfunction,
whichsmoothensthesharptransitionsandreducestheripplesinthefilter'sfrequencyre
sponse.
41 DeptOfECE,VVIT
DSPLABBEC502 2024-25
Rectangular window: Direct truncation, leading to high ripples.
Hamming window: Reduces the ripples by tapering the impulse response
at the ends.
Hann window: A compromise between side lobe reduction and transition
width.
42 DeptOfECE,VVIT
DSPLABBEC502 2024-25
The windowed FIR filter impulse response h[n] is obtained as:
h[n]=hd[n]⋅w[n]
Where w[n] is the window function applied to the ideal impulse response.
MATLAB Code:
fp=100;
fs=500;
rp=0.001;
rs=0.005;
Fs=600;
FN=Fs/2;
wp=2*fp/Fs;
ws=2*fs/Fs;
numa=-20*(log10(sqrt(rp*rs))-
13); dena=14.6*(fs-fp)/Fs;
N=ceil(numa/dena);
N1=N+1;
if(rem(N,2)~=0)
N1=N;
N=N-1;
end;
%RectangularWindow
y=boxcar(N1);
% Low Pass Filter
b=fir1(N,wp,'low',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
%subplot(2,2,2);
plot(o/pi,m);
title('LPF');
xlabel('normalizedfrequency->');
ylabel('gain in db-');
grid on;
Expected Output:
43 DeptOfECE,VVIT
DSPLABBEC502 2024-25
9. DesignandimplementationofdigitalhighpassFIRfilterusingawindowtomeett
hegiven specifications.
Aim:TodesignandimplementadigitalhighpassFIRfilterusingawindowtomeetthegive
n specifications
Theory:
FIRfilters
aredigitalfilterswithafiniteimpulseresponse.Thesefiltersareinherentlystableand
can have an exact linear phase. A high-pass filter passes frequencies above a
certain cutoff frequency while attenuating frequencies below that cutoff.
To design a high-pass FIR filter, we first determine the ideal impulse response in
the frequency domain, then convert it to the time domain using the inverse
Fourier transform. The result is
typicallyinfiniteinduration,soweapplyawindowtotruncateitandreduceunwantedarti
facts.
IdealHigh-PassFilterImpulseResponse:
Theideal frequencyresponseofahigh-passfilterisdefined as:
Whereωc=2πfcisthecutofffrequency.
Thecorrespondingidealimpulseresponseinthetimedomainis:
Thisisessentiallyasincfunctionshiftedandinvertedtorepresentahigh-passfilter.
Windowing:
Theidealimpulseresponseisofinfinitelength,soweapplyawindowfunctiontotruncatei
ttoa finite length and smoothen the transitions. Common window functions
include:
Rectangularwindow:Simplytruncatestheimpulseresponse,butcauseslarge
ripples.
Hammingwindow:Providessmoothertransitions,reducingsideloberipples.
Hannwindow:Acompromisebetweenthemainlobewidthandsidelobe
attenuation.
44 DeptOfECE,VVIT
DSPLABBEC502 2024-25
ThewindowedFIRfilterimpulseresponseh[n]isobtainedbymultiplyingtheidealim
pulse response with the window function:
h[n]=hd[n]⋅w[n]
45 DeptOfECE,VVIT
DSPLABBEC502 2024-25
MATLABCode:
fp=100;
fs=500;
rp=0.001;
rs=0.005;
Fs=600;
FN=Fs/2;
wp=2*fp/Fs;
ws=2*fs/Fs;
numa=-20*(log10(sqrt(rp*rs))-
13); dena=14.6*(fs-fp)/Fs;
N=ceil(numa/dena);
N1=N+1;
if(rem(N,2)~=0)
N1=N;
N=N-1;
end
%RectangularWindow
y=boxcar(N1);
ExpectedOutput:
46 DeptOfECE,VVIT
DSPLABBEC502 2024-25
10. Designandimplementationof
digitalIIRButterworthlowpassfiltertomeetthegiven specifications.
Aim:TodesignandimplementadigitalIIRButterworthlowpassfiltertomeetthegiven
specifications.
Theory:
IIR filters are digital filters that have an infinite impulse response, meaning
that their response to an impulse input theoretically continues indefinitely. IIR
filters are commonly used due to their efficiency in achieving sharp transitions
with fewer coefficients compared to FIR filters.
The Butterworth filter is a type of IIR filter known for having a maximally flat
response in the passband. This makes the Butterworth filter ideal for applications
where it is essential to have a smooth frequency response with no pass band
ripples. The trade-off is a relatively slower roll-off compared to other IIR filter
types like Chebyshev or Elliptic filters.
The magnitude response of a Butterworth filter is defined as:
Where:
Ω is the angular frequency.
Ωc is the cut off frequency.
N is the order of the filter.
A higher-order Butterworth filter results in a steeper roll-off at the expense of
increased phase distortion and more complex implementation.
MATLABCode:
%thespecifications
clc;
clearall;
closeall;
alphap=3;
alphas=15;
fp=500;
fs=750;
f=2000;
omp=2*fp/f;
oms=2*fs/f;
47 DeptOfECE,VVIT
DSPLABBEC502 2024-25
%t of indcutofffrequency&orderofthefilter
[N,Wn]=buttord(omp,oms,alphap,alphas)
disp('order of the filter n =');
disp(N);
disp('cutofffrequencyWn=');
disp(Wn);
%system function of the
filter
[b,a]=butter(N,Wn)
w=0:0.01:pi;
[h,om]=freqz(b,a,w,'whole')
; m=abs(h);
an=angle(h);
subplot(2,1,1);
plot(om/pi,20*log(m));
grid;
ylabel('gain in dB');
xlabel('normalizedfrequency'
);
subplot(2,1,2);plot(om/pi,an
);
grid;
ylabel('phase in radian');
xlabel('normalizedfrequency');
%toconvertanalogfiltertodigitalfilter
%usingbilineartransformation
[bz,az]=bilinear(b,a,f);
ExpectedOutput:
48 DeptOfECE,VVIT
DSPLABBEC502 2024-25
11. DesignandimplementationofdigitalIIRButterworthhighpassfiltertome
etthegiven specifications
Aim:TodesignandimplementadigitalIIRButterworthhighpassfiltertomeetthegiven
specifications.
Theory:
IIR filters are digital filters characterized by their infinite impulse response,
meaning that their
outputdependsonbothpastandpresentinputvalues.Theyaremorecomputationally
efficient than FIR filters for achieving similar magnitude response
characteristics because they require fewer coefficients.
The Butterworth filter is a popular type of IIR filter designed to have a
maximally flat magnitude
responseinthepassband,meaningithasnoripples,andthetransitionfrompassbandto
stopband is smooth. A high-pass Butterworth filter passes frequencies
above the cutoff frequency and attenuates those below it.
ThemagnituderesponseofaButterworthfilterisgivenby:
Where:
ωistheangularfrequency.
ωcisthecutoff frequency.
N isthe filterorder.
Ahigherfilterorderresultsinasharpertransitionbetweenthepassbandandstopband.
Fordigital
filters,thecutofffrequencyisnormalizedwithrespecttotheNyquistfrequency(halfth
esampling frequency).
MATLABCode:
%thespecifications
clc;
clearall;
closeall;
alphap=3;
alphas=15;
fp=500;
fs=750;
f=2000;
omp=2*fp/f;
oms=2*fs/f;
%tofindcutofffrequency&orderofthefilter
49 DeptOfECE,VVIT
DSPLABBEC502 2024-25
[N,Wn]=buttord(omp,oms,alphap,alphas)disp('o
rder of the filter n =');
50 DeptOfECE,VVIT
DSPLABBEC502 2024-25
disp(N);
disp('cutofffrequencyWn=');
disp(Wn);
%systemfunctionofthefilter
[b,a]=butter(N,Wn,'high')
w=0:0.01:pi;
[h,om]=freqz(b,a,w,'whole')
; m=abs(h);
an=angle(h);
subplot(2,1,1);
plot(om/pi,20*log(m));
grid;
ylabel('gain in dB');
xlabel('normalizedfrequency'
);
subplot(2,1,2);plot(om/pi,an
);
grid on;
[bz,az]=bilinear(b,a,f);
ylabel('phase in radian');
xlabel('normalizedfrequency'
);
%toconvertanalogfiltertodigitalfilter
%usingbilineartransformation
ExpectedOutput:
51 DeptOfECE,VVIT