Sei sulla pagina 1di 158

SS Lab # 1

OBJECTIVESOFTHELAB

Matlabwillbeusedextensivelyinallthesucceedinglabs.Thegoalofthisfirstlabistogainfamiliarity
withMatlabandbuildsomebasicskillsintheMatlablanguage.Somespecifictopicscoveredinthislab
are:
IntroductiontoMatlab
MatlabEnvironment
MatlabHelp
Variablearithmetic
BuiltinMathematicalFunctions
Inputanddisplay
Timingfunctions
IntroductiontoMfiles

1.1 WHAT IS MATLAB?


MATLAB is a commercial "MATrix LABoratory" package, by MathWorks, which operates as an
interactive programming environment with graphical output. The MATLAB programming language is
exceptionallystraightforwardsincealmosteverydataobjectisassumedtobeanarray.Hence,forsome
areas of engineering MATLAB is displacing popular programming languages, due to its interactive
interface,reliablealgorithmicfoundation,fullyextensibleenvironment,andcomputationalspeed.

1.2 ENTERING AND RUNNING MATLAB

DoubleclickontheMATLABicontolaunchandacommandwindowwillappearwiththeprompt:
>>
YouarenowinMATLAB.Fromthispointon,individualMATLABcommandsmaybegivenattheprogram
prompt. They will be processed when you hit the <ENTER> key. The following figure shows the
screenshotofmatlab.

1.3 LEAVING MATLAB


AMATLABsessionmaybeterminatedbysimplytyping
>>quit
orbytyping
>>exit
attheMATLABprompt.

1.4 MATLAB HELP


OnlinehelpisavailablefromtheMATLABprompt,bothgenerally(listingallavailablecommands).
>>help
[alonglistofhelptopicsfollows]
andforspecificcommands:
>>helpcommand_name

If you want to search for all the commands related to some particular functionality, use the keyword
lookforfollowedbyakeywordthatexplainsthefunctionality.
>>lookforconvolution
willreturnanumberofcommandsthatperformconvolutionrelatedtasks.

1.5 VARIABLES

MATLABhasbuiltinvariableslikepi,eps,andans.Youcanlearntheirvaluesfromthe
MATLABinterpreter.
>>eps
eps=
2.2204e16
>>pi
ans=
3.1416

1.5.1

Variable Assignment

Theequalitysignisusedtoassignvaluestovariables:
>>x=3
x=
3
>>y=x^2
y=
9

Variables in MATLAB are case sensitive. Hence, the variables "x" and "y" are distinct from "X"
and"Y"(atthispoint,thelatterareinfact,undefined).
Outputcanbesuppressedbyappendingasemicolontothecommandlines.
>>x=3;
>>y=x^2;
>>y
y=
9

1.5.2

Active Variables

Atanytimeyouwanttoknowtheactivevariablesyoucanusewho:
>>who
Yourvariablesare:
ansxy

1.5.3

Removing a Variable

Toremoveavariable,trythis:
>>clearx
Toremoveallthevariablesfromworkspace,useclear
>>clear

1.5.4

Saving and Restoring Variables

Tosavethevalueofthevariable"x"toaplaintextfilenamed"x.value"use
>>savex.valuexascii
Tosaveallvariablesinafilenamedmysession.mat,inreloadableformat,use
>>savemysession
Torestorethesession,use
>>loadmysession

1.6 VARIABLE ARITHMETIC

MATLABusessomefairlystandardnotation.Morethanonecommandmaybeenteredonasingleline,
iftheyareseparatedbycommas.
>>2+3;
>>3*4,4^2;
Powers are performed before division and multiplication, which are done before subtraction and
addition.Forexample
>>2+3*4^2;
generatesans=50.Thatis:
2+3*4^2==>2+3*4^2<==exponenthasthehighestprecedence
==>2+3*16<==thenmultiplicationoperator
==>2+48<==thenadditionoperator
==>50

1.6.1

Double Precision Arithmetic

Allarithmeticisdonetodoubleprecision,whichfor32bitmachinesmeanstoabout16decimal
digitsofaccuracy.Normallytheresultswillbedisplayedinashorterform.
>>a=sqrt(2)
a=
1.4142
>>formatlong,b=sqrt(2)
b=

1.41421356237310
>>formatshort

1.6.2

Command-Line Editing

The arrow keys allow "commandline editing," which cuts down on the amount of typing
required, and allows easy error correction. Press the "up" arrow, and add "/2." What will this
produce?
>>2+3*4^2/2
Parenthesesmaybeusedtogroupterms,ortomakethemmorereadable.Forexample:
>>(2+3*4^2)/2
generatesans=25.

1.6.3

Built-In Mathematical Functions

MATLABhasaplatterofbuiltinfunctionsformathematicalandscientificcomputations.Hereisa
summaryofrelevantfunctions.

Function Meaning Example


======================================================
sin
sine
sin(pi) = 0.0
cos
cosine
cos(pi) = 1.0
tan
tangent
tan(pi/4) = 1.0
asin
arcsine
asin(pi/2)= 1.0
acos
arccosine
acos(pi/2)= 0.0
atan
arctangent
atan(pi/4)= 1.0
exp
exponential
exp(1.0) = 2.7183
log
natural logarithm
log(2.7183) = 1.0
log10
logarithm base 10
log10(100.0) = 2.0
======================================================

Theargumentstotrigonometricfunctionsaregiveninradians.

Example: Let'sverifythat
sin(x)^2+cos(x)^2=1.0
forarbitraryx.TheMATLABcodeis:
>>x=pi/3;
>>sin(x)^2+cos(x)^21.0
ans=

1.7 TIMING COMMANDS

Timing functions may be required to determine the time taken by a command to execute or an
operationtocomplete.Severalcommandsareavailabletoaccomplishit:

1.7.1

Clock

CLOCKreturnsCurrent dateand timeasdatevector.CLOCKreturnsasix elementdatevector


containingthecurrenttimeanddateindecimalform:
CLOCK=[yearmonthdayhourminuteseconds]
Thefirstfiveelementsareintegers.Thesecondselementisaccuratetoseveraldigitsbeyondthe
decimalpoint.FIX(CLOCK)roundstointegerdisplayformat.

1.7.2

Etime

ETIMEElapsedtime.
ETIME(T1,T0)returnsthetimeinsecondsthathaselapsedbetweenvectorsT1andT0.Thetwo
vectorsmustbesixelementslong,intheformatreturnedbyCLOCK:
T=[YearMonthDayHourMinuteSecond]
Time differences over many orders of magnitude are computed accurately. The result can be
thousands of seconds if T1 and T0 differ in their first five components or small fractions of
secondsifthefirstfivecomponentsareequal.
t0=clock;
operation
etime(clock,t0)

1.7.3

Tic Toc

TICStartastopwatchtimer.
Thesequenceofcommands
TIC,operation,TOC
printsthenumberofsecondsrequiredfortheoperation.

1.8 INPUT & DISPLAY

1.8.1

INPUT

INPUTpromptsforuserinput.
R=INPUT('Howmanyapples')
givestheuserthepromptinthetextstringandthenwaitsforinputfromthekeyboard.Theinput
canbeanyMATLABexpression,whichisevaluated,usingthevariablesinthecurrentworkspace,
and the result returned in R. If the user presses the return key without entering anything,
INPUTreturnsanemptymatrix.

Example:Enteringasinglevariable
>>x=input('Enteravariable:')
Enteravariable:4
x=
4

Example:Enteringavector
Avectorisenteredbyspecifying[]andelementsareinsertedinsidethesebrackets,separatedby
space.
>>x=input('Enteravector:')
Enteravector:[341]
x=
341

Example:A\nenteredafterthestringresultsinstartinganewline.
>>x=input('Enteravalue\n')
Enteravalue
5
x=

1.8.2

DISP

DISPDisplayarray.
DISP(X) displays the array, without printing the array name. In all other ways it's the same as
leavingthesemicolonoffanexpressionexceptthatemptyarraysdon'tdisplay.
DISP(string)isanothervariationofthesamefunctionthatisusedtodisplayastringonthe
commandprompt.
Example:
>>disp('IamusingMATLAB7.0')
IamusingMATLAB7.0

1.9 M-Files

Typingerrorsaretimeconsumingtofixifyouareworkinginthecommandwindowbecauseyouneed
toretypeallorpartoftheprogram.Evenifyoudonotmakeanymistakes,allofyourworkmaybelost
ifyouinadvertentlyquitMATLAB.Topreservelargesetsofcommands,youcanstoretheminaspecial
typeoffilecalledanMfile.MATLABsupportstwotypesofMfiles:scriptandfunctionMfiles.Toholda
largecollectionofcommands,weuseascriptMfile.ThefunctionMfileisdiscussedincominglab.The
script file has a '.m'

extension and is referred to as an Mfile (for example, myfile.m

myfuncion.m,etc.).Thecommandsinthescriptfilecanthenbeexecutedbytyping thefilename
withoutitsextensioninthecommandwindow.Commandsinascriptutilizeandmodifythecontentsof
thecurrentworkspace.Itispossibletoembedcommentsinascriptfile.

TomakeascriptMfile,youneedtoopenafileusingthebuiltinMATLABeditor.Therearetwowaysto
accomplishit:
1. Fromfilemenu,clickNEW
2. Typeeditoncommandline
Anewwindowappearslikeoneshowninthefigurebelow.


Whenyouarefinishedwithtypinginthisnewwindow,clickFile>Savetosavethisfile.Theextensionof
thisfilebe.m.Inordertoexecutethisprogram,
1. Writethenameoffileoncommandwindow(excludingthe.m)or
2. ClickDebug>Run

-------------------------TASK 01-------------------------Matlabstoresnumericdataasdoubleprecisionfloatingpointbydefault.Tostoredataasan8
bitinteger,int8(aconversionfunction)canbeused.Typethesamplecodeinmatlabcommand
window:
>>x=26

>>whos
>>y=int8(x)
>>whos
Whatdifferencedoyousee?Stateyourfindings.

-------------------------TASK 02-------------------------Takeyournameincommandwindowe.g.name=Ali.Convertitinto8bitintegerformatusing
int8function.

-------------------------TASK 03-------------------------Createlogicalarrayxof5elementsbyenteringatrue(1)orfalse(0)valueforeachelement.

-------------------------TASK 04-------------------------Createanmfiletoget10numbersfromuserandgeneratethesquareofthosenumbers.

-------------------------TASK 05-------------------------WritaCalculatorprogram:Taketwovariablesi.e.xandyfromuser.Findtheirsum,difference,
product,multiplication,andmodulus.Showtheresults.

Lab # 2

OBJECTIVESOFTHELAB

Inthislab,wewillcoverthefollowingtopics:
BuiltinMatrixFunctions
IndexingMatrices
SubMatrices
Matrixelementleveloperations
RoundFloatingPointnumberstoIntegers

2.1 MATRICES

MATLAB works with essentially only one kind of object, a rectangular numerical matrix possibly, with
complex entries. Every MATLAB variable refers to a matrix [a number is a 1 by 1 matrix]. In some
situations,1by1matricesareinterpretedasscalars,andmatriceswithonlyoneroworonecolumnare
interpretedasvectors.
Amatrixisarectangulararrayofnumbers.Forexample:

3
1

6
4
8
4

9
8
7
2

2
5

definesamatrixwith4rows,4columns,and16elements.

Example:
Considerthefollowingthreeequations:

Thisfamilyofequationscanbewrittenintheform
X=

,where

DependingonthespecificvaluesofcoefficientsinmatricesAandB,theremaybe:
(a) nosolutionsto
(b) auniquesolutionto

,or
,or

(c) aninfinitenumberofsolutionsto
Inaboveexample,thesolutionmatrixis

2.1.1

Defining Matrices In Matlab

MATLAB is designed to make definition of matrices and matrix manipulation as simple as


possible.

Matrices can be introduced into MATLAB in several different ways. For example, either of the
statements
>>A=[123;456;789];
and
>>A=[123
456
789]
createstheobvious3by3matrixandassignsittoavariableA.

Notethat:

Theelementswithinarowofamatrixmaybeseparatedbycommasaswellasablank.

Theelementsofamatrixbeingenteredareenclosedbybrackets;

Amatrixisenteredin"rowmajororder"[i.e.allofthefirstrow,thenallofthesecond
row,etc];

Rowsareseparatedbyasemicolon[oranewline],andtheelementsoftherowmaybe
separatedbyeitheracommaoraspace.[Caution:Watchoutforextraspaces!]

ThematrixelementlocatedintheithrowandjthcolumnofAisreferredtointheusualway:
>>A(1,2),A(2,3)
ans=
2
ans=
6
It'sveryeasytomodifymatrices:
>>A(2,3)=10;

2.1.2

Building Matrices from a Block

Largematricescanbeassembledfromsmallermatrixblocks.Forexample,withmatrixAinhand,
wecanenterthefollowingcommands:
>>C=[A;101112];

<==generatesa(4x3)matrix

>>D=[A;A;A];

<==generatesa(9x3)matrix

>>E=[A,A,A];

<==generatesa(3x9)matrix

As with variables, use of a semicolon with matrices suppresses output. This feature can be
especiallyusefulwhenlargematricesarebeinggenerated.

2.1.3

Built-in matrix functions

MATLABhasmanytypesofmatriceswhicharebuiltintoitssystem.Forexample,
Function Description
===============================================
diag
returns diagonal M.E. as vector
eye
identity matrix
hilb
Hilbert matrix
magic
magic square
ones
matrix of ones
rand
randomly generated matrix
triu
upper triangular part of a matrix
tril
lower triangular part of a matrix
zeros
matrix of zeros
===============================================

Here are some examples:


i.

Matrices of Random Entries: A 3 by 3 matrix with random entries is produced by


typing
>>rand(3)
ans=
0.0470

0.9347

0.8310

0.6789

0.3835

0.0346

0.6793

0.5194

0.0535

Generalmbynmatricesofrandomentriesaregeneratedwith
>>rand(m,n);

ii.

Magic Squares: Amagicsquareisasquarematrixwhichhasequalsumsalongallits


rowsandcolumns.Forexample:
>>magic(4)
ans=
16

13

11

10

12

14

15

Theelementsofeachrowandcolumnsumto34.

iii.

iv.

Matrices of Ones: Thefunctions

eye(m,n)producesanmbynmatrixofones.

eye(n)producesannbynmatrixofones.

Matrices of Zeros: Thecommands

zeros(m,n)producesanmbynmatrixofzeros.

zeros(n)producesannbynone;

IfAisamatrix,thenzeros(A)producesamatrixofzerosofthesamesizeasA.

v.

Diagonal Matrices: If x is a vector, diag(x) is the diagonal matrix with x down the
diagonal.
IfAisasquarematrix,thendiag(A)isavectorconsistingofthediagonalofA.
Whatisdiag(diag(A))?Tryit.

2.2 MATRIX OPERATIONS

ThefollowingmatrixoperationsareavailableinMATLAB:
Operator Description Operator Description
================================================
+ addition
' transpose
- subtraction
\ left division
* multiplication
/ right division
^ power
================================================

Thesematrixoperationsapply,ofcourse,toscalars(1by1matrices)aswell.Ifthesizesofthematrices
are incompatible for the matrix operation, an error message will result, except in the case of scalar
matrixoperations(foraddition,subtraction,anddivisionaswellasformultiplication)inwhichcaseeach
entryofthematrixisoperatedonbythescalar.

2.2.1

Matrix Transpose

Thetransposeofamatrixistheresultofinterchangingrowsandcolumns.MATLABdenotesthe
[conjugate]transposebyfollowingthematrixwiththesinglequote[apostrophe].Forexample:
>>A'
ans=
1

>>B=[1+i

2+2*i

33*i]'

B=
1.00001.0000i
2.00002.0000i
3.0000+3.0000i

2.2.2

Matrix Addition/Subtraction

Let matrix "A" have m rows and n columns, and matrix "B" have p rows and q columns. The
matrixsum"A+B"isdefinedonlywhenmequalspandnequalsq,theresultisnbymmatrix
havingtheelementbyelementsumofcomponentsinAandB.
Forexample:
>>E=[23;45.0;67];
>>F=[12;36.5;1045];
>>E+F
ans=
3.0000

1.0000

7.0000

11.5000

16.0000

38.0000

2.2.3

Matrix Multiplication

Matrixmultiplicationrequiresthatthesizesmatch.Iftheydon't,anerrormessageisgenerated.
>>A*B,B*A;
>>B'*A;
>>A*A',A'*A;
>>B'*B,B*B';
Scalars multiply matrices as expected, and matrices may be added in the usual way (both are
done"elementbyelement):
>>2*A,A/4;
>>A+[b,b,b];

Example:
Wecanusematrixmultiplicationtocheckthe"magic"propertyofmagicsquares.
>>A=magic(5);
>>b=ones(5,1);
>>A*b;

<==(5x1)matrixcontainingrowsums.

<==(1x5)matrixcontainingcolumnsum.

>>v=ones(1,5);
>>v*A;

2.2.4

Matrix Functions "any" and "all

There is a function to determine if a matrix has at least one nonzero entry, any, as well as a
functiontodetermineifalltheentriesarenonzero,all.
>>A=zeros(1,4)
>>any(A)
>>D=ones(1,4)
>>any(D)
>>all(A)

2.2.5

Returning more than One Value

SomeMATLABfunctionscanreturnmorethanonevalue.
Inthecaseofmaxtheinterpreterreturnsthemaximumvalueandalsothecolumnindexwhere
themaximumvalueoccurs.

>>[m,i]=max(B)
>>min(A)
>>b=2*ones(A)
>>A*B
>>A

2.2.6

Size of Matrix

Sizeofamatrixcanbecalculatebyusingfunctionsize.
>>x=[123;123];
>>s=size(x)
s=
23

2.2.7

Length of Array

Lengthofanarraycanbefoundusingfunctionlength.
>>n=[3:1:3];
>>l=length(n)
l=

2.2.8

Finding an element in a matrix

Thisfunctioncanbeusedtofindindexofanyparticularvalue.Saygivenarrayis
x=[02468];
Tofindtheindicesofallvaluesthataregreaterthan4,followingisused
>>y=find(x>4)
y=

45

-------------------------TASK 01-------------------------Write a program to generate a new matrix B from the matrix A given below such that each
columninthenewmatrixexceptthefirstoneistheresultofsubtractionofthatcolumnfrom

thepreviousonei.e.2ndnewcolumnistheresultofsubtractionof2ndcolumnand1stcolumn
andsoon.Copythefirstcolumnasitisinthenewmatrix.

3 6 9
A = 1 4 8
2 8 7

-------------------------TASK 02-------------------------Generatetwo5000sampledrandomdiscretetimesignals(1dimensional)usingrand()function
i.e. rand(1, 5000). Write a program to add the two signals together using simple vector
addition.

2.3 SUB-MATRICES

2.3.1

A note on colon notation

AcentralpartoftheMATLABlanguagesyntaxisthe"colonoperator,"whichproducesalist.For
example:
>>x=3:3
x=
3210123

Thedefaultincrementisby1,butthatcanbechanged.Forexample:
>>x=3:.5:3
x=

Columns1through7

3.00002.50002.00001.50001.00000.50000

Columns8through13

0.50001.00001.50002.00002.50003.0000

Thiscanberead:"xisthenameofthelist,whichbeginsat3,andwhoseentriesincreaseby.5,
until3issurpassed."Youmaythinkofxasalist,avector,oramatrix,whicheveryoulike.

Inourthirdexample,thefollowingstatementsgenerateatableofsine.
>>x=[0.0:0.1:2.0]';
>>y=sin(x);
>>[xy]
Tryit.Notethatsincesinoperatesentrywise,itproducesavectoryfromthevectorx.

Thecolonnotationcanalsobecombinedwiththeearliermethodofconstructingmatrices.
>>a=[1:6;2:7;4:9]

-------------------------TASK 03-------------------------Usingcolonnotation,generatethefollowingsequence:

120,116,112,...,4,0,4,8,...,112,116,120.

2.3.2

Sub-matrix extraction using colon notation

Colonnotationcanbeusedtogeneratevectors.Averycommonuseofthecolonnotationisto
extract rows, or columns, as a sort of "wildcard" operator which produces a default list. For
example,

A(1:4,3)

isthecolumnvectorconsistingofthefirstfourentriesofthethirdcolumnofA

A(:,3)

isthethirdcolumnofA.Acolonbyitselfdenotesanentireroworcolumn

A(1:4,:)

isthefirstfourrowsofA.

Anarbitraryintegralvectorcanbeusedassubscripts.Thestatement
A(:,[24])

containsascolumns,columns2and4ofmatrixA.

Thissubscriptingschemecanbeusedonbothsidesofanassignmentstatement:
A(:,[245])=B(:,1:3)
Itreplacescolumns2,4,and5ofmatrixAwiththefirstthreecolumnsofmatrixB.Notethatthe
"entire"alteredmatrixAisprintedandassigned.Tryit.

-------------------------TASK 04-------------------------Giventhematrices:

7 16
A=
,
4
9

6 5
B=

12 2

Findthefollowing:
1) Arrayaddition;storetheresultinmatrixC
2) Arraysubtraction;storetheresultinmatrixD
3) Arraymultiplicationusing.*operator;storetheresultinmatrixE
4) Arraydivisionusing./operator;storetheresultinmatrixF
5) Arrayexponentiationusing.^operator;storetheresultinmatrixG

-------------------------TASK 05-------------------------Typethegivenmatrixinmatlab:

3
5
A=
6

15

7 4 12
9 10 2
13 8 11

5 4 1

Findthefollowing:
1) Create4x3arrayBconsistingofallelementsinthesecondthroughfourthcolumnsofA
2) Create3x4arrayCconsistingofallelementsinthesecondthroughfourthrowsofA
3) Create2x3arrayDconsistingofallelementsinthefirsttworowsandthelastthree
columnsofA

-------------------------TASK 06-------------------------MATLABhasfunctionstoroundfloatingpointnumberstointegers.Theseareround,fix,ceil,
andfloor.Testhowthesefunctionswork.Determinetheoutputofthefollowing:
>>f=[.5.1.5];
>>round(f)
>>fix(f)
>>ceil(f)

>>floor(f)

-------------------------TASK 07-------------------------Giventhefollowingmatrix:

3 5
A=

4
8

Findthefollowing:
1) ColumnwisesumofallelementsofAusingsumfunction;forinformationaboutsum
function,typehelpsuminmatlab
2) ColumnwiseproductofallelementsofAusingprodfunction;forinformationabout
prodfunction,typehelpprodinmatlab
3) LengthofmatrixA
4) SizeofmatrixA

Lab # 3

OBJECTIVESOFTHELAB

Inthislab,wewillgetanunderstandingofthefollowingtopics:
MakingFunctions
ControlStructures
RelationalConstructs
LogicalConstructs
BranchingConstructs
Loopingconstructs

3.1 MAKING FUNCTIONS

Afunctioncanbecreatedbythefollowingsyntax:
function[output1,output2,...]=function_name(input1,input2,...)

A function is a reusable piece of code that can be called from program to accomplish some specified
functionality.Afunctiontakessomeinputargumentsandreturnssomeoutput.Tocreateafunctionthat
addstwonumbersandstorestheresultinathirdvariable,typeinitthefollowingcode:
function add
x = 3;
y = 5;
z = x + y
Savethefilebythenameofadd(inworkfolder,whichischosenbydefault),gobacktothecommand
windowandwrite
>>add
z=
8
Youseethatthesumzisdisplayedinthecommandwindow.Nowgobacktotheeditor/debuggerand
modifytheprogramasfollows
function addv(x,y)
z = x + y
Save the above program with a new name addv, go back to the command window and type the
following:
>>addv(3,5)
z=
8
>>addv(5,5)
z=
10
Wehaveactuallycreatedafunctionofourownandcalleditinthemainprogramandgavevaluestothe
variables(x,y).

Nowgobacktotheeditor/debuggerandmodifytheprogramasfollows
function adv(x, y)

%------------------------------------------------% This function takes two values as input,


% finds its sum, & displays the result.
% inputs: x & y
% output: z
% Example: addv(3,6)
% Result: z=9
%-------------------------------------------------z = x + y

Savetheprogramwiththesamenameaddv,gobacktocommandwindow,typethefollowing
>>helpaddv

Thisfunctiontakestwovaluesasinput,
findsitssum,&displaystheresult.
inputs:x&y
output:z
Example:addv(3,6)
Result:z=9

3.1.1

Script Vs Function

1) AscriptissimplyacollectionofMatlabcommandsinanmfile.Upontypingthenameofthefile
(without the extension), those commands are executed as if they had been entered at the
keyboard.
Functionsareusedtocreateuserdefinedmatlabcommands.

2) Ascriptcanhaveanyname.
Afunctionfileisstoredwiththenamespecifiedafterkeywordfunction.

3) ThecommandsinthescriptcanrefertothevariablesalreadydefinedinMatlab,whicharesaid
tobeintheglobalworkspace.
Whenafunctionisinvoked,Matlab createsalocal workspace. Thecommandsinthefunction
cannot refer to variables from the global (interactive) workspace unless they are passed as
inputs. By the same token, variables created as the function executes are erased when the
executionofthefunctionends,unlesstheyarepassedbackasoutputs.

-------------------------TASK 01-------------------------WriteafunctionthatacceptstemperatureindegreesFandcomputesthecorrespondingvalue
indegreesC.Therelationbetweenthetwois

Tc =

5
(Tc 32 )
9

Besuretotestyourfunction.

3.2 CONTROL STRUCTURES

ControlofflowinMATLABprogramsisachievedwithlogical/relationalconstructs,branchingconstructs,
andavarietyofloopingconstructs.

3.2.1

Relational and logical constructs

TherelationaloperatorsinMATLABare
Operator Description
===================================
<
less than
>
greater than
<=
less than or equal
>=
greater than or equal
==
equal
~=
not equal
===================================

Notethat''=''isusedinanassignmentstatementwhile''==''isusedinarelation.
Relationsmaybeconnectedorquantifiedbythelogicaloperators
Operator Description
===================================
&
and
|
or
~
not
===================================

Whenappliedtoscalars,arelationisactuallythescalar1or0dependingonwhethertherelation
istrueorfalse(indeed,throughoutthissectionyoushouldthinkof1astrueand0asfalse).For
example
>>3<5
ans=
1

>>a=(3==5)
a=
0

Whenlogicaloperandsareappliedtomatricesofthesamesize,arelationisamatrixof0'sand
1'sgivingthevalueoftherelationbetweencorrespondingentries.Forexample:
>>A=[12;34];
>>B=[67;89];
>>A==B
ans=
0

0
>>A<B

ans=
1

Toseehowtheotherlogicaloperatorswork,youshouldalsotry
>>~A
>>A&B
>>A&~B
>>A|B
>>A|~A

-------------------------TASK 02-------------------------For the arrays x and y given below, write matlab code to find all the elements in x that are
greaterthanthecorrespondingelementsiny.
x=[3,0,0,2,6,8]y=[5,2,0,3,4,10]

3.2.2

Branching constructs

MATLABprovidesanumberoflanguageconstructsforbranchingaprogram'scontrolofflow.
i.

ifendConstruct:Themostbasicconstructis:
if <condition>
<program>
end
Here the condition is a logical expression that will evaluate to either true or false (i.e.,
withvalues1or0).Whenalogicalexpressionevaluatesto0,programcontrolmoveson
tothenextprogramconstruction.YoushouldkeepinmindthatMATLABregardsA==B
andA<=Basfunctionswithvalues0or1.

Example:
>>a=1;
>>b=2;
>>ifa<b
c=3;
end
>>c
c=
3

ii.

IfelseendConstruct: Frequently,thisconstructioniselaboratedwith
if <condition1>
<program1>
else
<program2>
end
Inthiscaseifconditionis0,thenprogram2isexecuted.

iii.

If-elseif-end Construct: Anothervariationis


if <condition1>
<program>
elseif <condition2>
<program2>
end

Nowifcondition1isnot0,thenprogram1isexecuted,ifcondition1is0andifcondition2isnot
0,thenprogram2isexecuted,andotherwisecontrolispassedontothenextconstruction.

-------------------------TASK 03-------------------------For0<a16,findthevaluesofCdefinedasfollows:
C= 4ab
ab

for

1a8

for

8<a16

andb=12.

-------------------------TASK 04-------------------------Forthevaluesofintegeragoingfrom1to10,usingseparatelythemethodsofifsyntaxandthe
Booleanalternativeexpressions,findthevaluesofCif:

C=

a2

a+3
a

for
for
for

a<3
3a<7
a>7

-------------------------TASK 05-------------------------Rewritethefollowingstatementstouseonlyoneifstatement.
ifx<y
ifz<5
w=x*y*z
end
end

3.2.3
i.

Looping constructs
For Loop : Aforloopisaconstructionoftheform
for i= 1 : n
<program>
end

Thiswillrepeat<program>onceforeachindexvaluei=1,2....n.Herearesomeexamplesof
MATLAB'sforloopcapabilities:

Example: Thebasicforloop
>>fori=1:5
c=2*i
end
c=
2
.....linesofoutputremoved...
c=
10
computesandprints"c=2*i"fori=1,2,...5.

Example: For looping constructs may be nested. Here is an example of creating a matrix
contentinsideanestedforloop:
>>fori=1:10
forj=1:10
A(i,j)=i/j;
end
end
Thereareactuallytwoloopshere,withonenestedinsidetheother;theydefine
A(1,1),A(1,2),A(1,3)...A(1,10),A(2,1),A(2,2)...A(2,10),...A(10,1),A(10,2)...A(10,10)
inthatorder.

Example: MATLAB will allow you to put any vector in place of the vector 1:n in this
construction.Thustheconstruction
>>fori=[2,4,5,6,10]
<program>
end
isperfectlylegitimate.
Inthiscaseprogramwillexecute5timesandthevaluesforthevariableiduringexecutionare
successively,2,4,5,6,10.

-------------------------TASK 06-------------------------Usingforloop,generatethecubeofthefirsttenintegers.

-------------------------TASK 07-------------------------Addthefollowingtwomatricesusingforloop.
5 12 3
A = 9 6 5
2 2 1

2 1 9
B = 10 5 6
3 4 2

-------------------------TASK 08-------------------------Write matlab function that creates a special square matrix that has ones in the first row and
first column, and whose remaining elements are the sum of two elements i.e. the element
above and the element to the left, if the sum is less than 20. Otherwise, the element is the
maximumofthosetwoelementvalues.Namethefunctionspecmatwithsingleinputdefining
thematrixdimension.Asampleprogramrunis:
>>specmat(3)
ans=

1 1 1
1 2 3

1 3 6

ii.

While Loops

Awhileloopisaconstructionoftheform
while <condition>
<program>
end
where condition is a MATLAB function, as with the branching construction. The program will
execute successively as long as the value of condition is not 0. While loops carry an implicit
dangerinthatthereisnoguaranteeingeneralthatyouwillexitawhileloop.Hereisasample
programusingawhileloop.

Example:
function l = twolog(n)
% l = twolog(n). l is the floor of the base 2
% logarithm of n.
l = 0;

m = 2;
while m<=n
l=l+1;
m=2*m;
end

-------------------------TASK 09-------------------------Consider the following script file. Fill in the lines of the following table with the values that
wouldbedisplayedimmediatelyafterthewhilestatementifyouranthescriptfile.Writeinthe
valuesthevariableshaveeachtimethewhilestatementisexecuted.Youmightneedmoreor
fewerlinesinthetable.Thentypeinthefile,andrunittocheckyouranswers.
k = 1; b = -2; x = -1; y = -2;
while k <= 3
k, b, x, y
y = x^2 -3;
if y < b
b = y;
end
x = x + 1;
k = k + 1;

Pass
First
Second
Third
Fourth
Fifth

end

-------------------------TASK 10-------------------------Create an mfile that inputs a number from user and then finds out the factorial of that
number.

-------------------------TASK 11-------------------------Createanmfilethattakestwovectorsfromuser.Makesurethatthesecondvectortakenisof
thesamesizeasthefirstvector(Hint:usewhileloop).Inawhileloop,generateathirdvector
thatcontainsthesumofthesquaresofcorrespondingentriesofboththevectors.

Lab # 4

OBJECTIVESOFTHELAB

Thislabwillhelpyougraspthefollowingconcepts:
DiscreteSignalrepresentationinMatlab
MatlabGraphics
TwoDimensionalPlots
Plotandsubplot
DifferentPlottingFunctionsUsedinMatlab

4.1 DISCRETE-TIME SIGNAL REPRESENTATION IN MATLAB


In MATLAB, finiteduration sequence (or discrete time signal) is represented by row matrix/vector of
appropriate values. Such representation does not have any information about sample position n.
Therefore,forcorrectrepresentation,twovectorsarerequired,oneforxandotherforn.Considerthe
followingfinitedurationsequence&itsimplementation:
x(n)={1102146}

>>n=[3:1:3]
n=

3210123
>>x=[1102146]

x=
1102146
NOTE#01:Whenthesequencebeginsatn=0,xvectorrepresentationaloneisenough.
NOTE#02:AnarbitraryinfinitesequencecantberepresentedinMATLABduetolimitedmemory.

-------------------------TASK 01-------------------------Giventhesignals:
x1[n]=[25843]
x2[n]=[432]
a) WriteaMatlabprogramthataddsthesetwosignals.Usevectoradditionandmultiplication.
b) Instead of using vector addition and multiplication, use for loop to add and multiply the
signals.

-------------------------TASK 02-------------------------Amplitudescalingbyafactorcauseseachsampletogetmultipliedby.Writeauserdefined
function that has two input arguments: (i) a signal to be scaled and (ii) scaling factor . The
functionshouldreturnthescaledoutputtothecallingprogram.Inthecallingprogram,getthe
discretetimesignalaswellasthescalingfactorfromuserandthencalltheabovementioned
function.

-------------------------TASK 03-------------------------

X2[n]
X1[n]

3
2

2
1

01234

WriteaMatlabprogramtocomparethesignalsx1[n]andx2[n].Determinetheindexwherea
sampleofx1[n]hassmalleramplitudeascomparedtothecorrespondingsampleofx2[n].Use
forloop.

4.2 GRAPHICS
TwoandthreedimensionalMATLABgraphscanbegiventitles,havetheiraxeslabeled,andhavetext
placedwithinthegraph.Thebasicfunctionsare:
Function Description
============================================================================
plot(x,y)
plots y vs x
plot(x,y1,x,y2,x,y3)
plots y1, y2 and y3 vs x on the same graph
stem(x)
plots x and draws a vertical line at each
datapoint to the horizontal axis
xlabel('x axis label') labels x axis
ylabel('y axis label') labels y axis
title ('title of plot') puts a title on the plot
gtext('text')
activates the use of the mouse to position a
crosshair on the graph, at which point the
'text' will be placed when any key is pressed.
zoom
allows zoom IN/OUT using the mouse cursor
grid
draws a grid on the graph area
print filename.ps
saves the plot as a black and white postscript
file
Shg
brings the current figure window forward.
CLF
clears current figure.
============================================================================

4.2.1

Two-dimensional plots

The plot command creates linear xy plots; if x and y are vectors of the same length, the
commandplot(x,y)opensagraphicswindowanddrawsanxyplotoftheelementsofxversus
theelementsofy.

Example: Let's draw the graph of the sine function over the interval 4 to 4 with the following
commands:

>>x=4:.01:4;y=sin(x);plot(x,y)
>>grid
>>xlabel('x')
>>ylabel('sin(x)')
Thevectorxisapartitionofthedomainwithmeshsize0.01whileyisavectorgivingthevalues
ofsineatthenodesofthispartition(recallthatsinoperatesentrywise).Followingfigureshows
theresult.

4.2.1.1 MULTIPLE PLOTS ON SAME FIGURE WINDOW


Twowaystomakemultipleplotsonasinglegraphare:
i.

Singleplotcommand
x = 0:.01:2*pi;
y1=sin(x);
y2=sin(2*x);
y3 = sin(4*x);
plot(x,y1,x,y2,x,y3)

ii.

Multipleplotcommands

Another way is with hold. The command hold freezes the current graphics screen so that
subsequentplotsaresuperimposedonit.Enteringholdagainreleasesthe``hold.''
x = 0:.01:2*pi;

y1=sin(x);
y2=sin(2*x);
y3 = sin(4*x);
plot(x,y1);
hold on;
plot(x, y2);
plot(x,y3);

4.2.1.2 OVERRIDING THE DEFAULT PLOT SETTINGS


Onecanoverridethedefaultlinetypesandpointtypes.Forexample,thecommandsequence
x = 0:.01:2*pi;
y1=sin(x);
y2=sin(2*x);
y3=sin(4*x);
plot(x,y1,'--',x,y2,':',x,y3,'+')
grid
title ('Dashed line and dotted line graph')

Thelinetypeandmarktypeare
=============================================================
Linetypes : solid (-), dashed (-). dotted (:), dashdot (-.)
Marktypes : point (.), plus (+), star (*, circle (o),
x-mark (x)
=============================================================

-------------------------TASK 04-------------------------Plotthetwocurvesy1=2x+3andy2=4x+3onthesamegraphusingdifferentplotstyles.
4.2.1.3 AXES COMMANDS (MANUAL ZOOMING)
MATLAB automatically adjusts the scale on a graph to accommodate the coordinates of the
points being plotted. The axis scaling can be manually enforced by using the command
axis([xminxmax ymin ymax]). Asignalcanbezoomedoutbyspecifyingtheaxiscoordinatesby
userhimself.
Example:
x = -5*pi:.01:5*pi;
y1=sin(x);
plot(x,y1, 'r')
Theplotisshowninthefigurebelow.

In order to see only one cycle of this signal from 0 to 2, the signal is zoomed using axis
command.Herewehavespecifiedxminandxmaxas0and2respectively.

x = -5*pi:0.01:5*pi;
y1=sin(x);
plot(x,y1, 'r')
axis([0 2*pi -1 1])
Themagnifiedplotisshowninthefigurebelow.

Similarlytheyaxiscanbeadjustedaccordingtorequirements.
x = -5*pi:0.01:5*pi;
y1=sin(x);
plot(x,y1, 'r')
axis([0 2*pi -2 2])

4.2.1.4 LABELING A GRAPH


Toaddlabelstoyourgraph,thefunctionsxlabel,ylabel,andtitlecanbeusedasfollows:
xlabel('xaxis')
ylabel('yaxis')
title('pointsinaplane')

4.2.1.5 SUBPLOT
SUBPLOTCreateaxesintiledpositions.
MATLABgraphicswindowswillcontainoneplotbydefault.Thecommandsubplotcanbeused
topartitionthescreensothatuptofourplotscanbeviewedsimultaneously.Asinglefigurecan
bedividedintoanumberofplottingareaswheredifferentgraphscanbeplotted.Thiscanbe
accomplishedbyusingthecommandsubplot(m,n,p)wherem,nspecifiesthetotalnumberof
rowsandcolumnsrespectivelyinthefigurewindowandpspecifiesthespecificcelltoplotinto.
x=0:1:10;
y=x.^2;
z=10*x;
Now type the following code

figure
subplot (1,2,1)
plot(x,y)
subplot (1,2,2)
plot(x,z)

In the above case subplot(m,n,p) command was used, in our case subplot (1,2,1) and
subplot (1,2,2). Here m=1 means that divide the figure into 1 row, n=2 means to divide
the figure into 2 columns. This gives us a total of 2 subplots in one figure. Where p=1
means the window on the left (starting from row 1 and counting p=1 subplots to the
right) and p=2 means the subplot on the right (starting from row 1 and counting p=2
subplots to the right).

Example:Performingoperationsonsignalsenteredbyuser
clear
x=input('Enter the first discrete time signal\n');
len_x=length(x);
y=input('Enter the second discrete time signal\n');
len_y=length(y);

while(len_y~=len_x)
disp('Error: Length of signals must match. Enter the 2nd
signal again')
y=input('');
len_y=length(y);
end
z=x+y;
subplot(3,1,1)
stem(x,'filled')
title('Signal 1')
xlabel('Sample number')
ylabel('Signal Amplitude')
subplot(3,1,2)
stem(y,'filled')
title('Signal 2')
xlabel('Sample number')
ylabel('Signal Amplitude')
subplot(3,1,3)
stem(z,'filled')
title('Resultant Signal')
xlabel('Sample number')
ylabel('Signal Amplitude')

output:
Enterthefirstdiscretetimesignal
[35102]
Entertheseconddiscretetimesignal
[11321]

-------------------------TASK 05-------------------------Maketwoseparatefunctionsforsignaladditionandmultiplication.Thefunctionsshouldtake
thesignalsasinputargumentsandreturntheresultantsignal.Inthemainprogram,getthe
signalsfromuser,callthefunctionsforsignaladditionandmultiplication,andplottheoriginal
signalsaswellastheresultantsignals.

-------------------------TASK 06-------------------------Giventhesignals:
X1[n]=2[n]+5[n1]+8[n2]+4[n3]+3[n4]
X2[n]=[n4]+4[n5]+3[n6]+2[n7]
WriteaMatlabprogramthataddsthesetwosignals.Plottheoriginalsignalsaswellasthefinal
result.

-------------------------TASK 07-------------------------Take a discretetime signal from user. Count the number of samples with amplitude greater
thanathresholdof3andlessthanathresholdof3(useforloop).

-------------------------TASK 08-------------------------Write your own function to downsample a signal i.e. retain odd numbered samples of the
originalsignalanddiscardtheevennumbered(downsamplingby2).Thefunctionmusttakea
signal as input and return the downsampeled version of that signal. See Fig forexample. Call
thisfunctionfromamatlabfile.Verifyyourresultbyusingthecommanddownsample.Plot

theoriginalsignal,downsampledsignaldeterminedbyyourprogram,anddownsampledsignal
obtainedbythecommanddownsample.

Fig. DownSampling

-------------------------TASK 09-------------------------Writeyourownfunctiontoupsampleasignali.e.copythe1stsampleoforiginalsignalinthe
newsignalandthenplaceanextrasampleof0,copythe2ndsampleoforiginalsignalandthen
placea0,andsoon.SeeFigforexample.Callthisfunctionfromamatlabfile.Verifyyourresult
by using the command upsample. Plot the original signal, upsampled signal determined by
yourprogram,andupsampledsignalobtainedbythecommandupsample.

Fig. Upsampling

Lab # 5

OBJECTIVESOFTHELAB

Inthislab,wewillcoverthefollowingtopics:

GainfamiliaritywithComplexNumbersandplotthem
Complexexponentialsignals
Realexponentialsignals

5.1 COMPLEX NUMBERS


Acomplexnumberzisanorderedpair(x,y)ofrealnumbers.Complexnumberscanberepresentedin
rectangularformasz=x+iy,whichisthevectorintwodimensionalplane.Thehorizontalcoordinatex
iscalledtherealpartofzandcanberepresentedasx=Re{z},whiletheverticalcoordinateyiscalled
theimaginarypartofzandrepresentedasy=Imag{z}.Thatis:
z=(x,y)
=x+iy
=Re{x}+iImag{x}
Anotherwaytorepresentacomplexnumberisinpolarform.Inpolarform,thevectorisdefinedbyits
length(r)ormagnitude(|z|)anditsdirection().Arectangularformcanbeconvertedintopolarform
usingformulas:
|z|=r=(x2+y2)
=arctan(y/x)
z=rej
whereej=cos+isin,andknownastheEulersformula.

5.2 BUILT-IN MATRIX FUNCTIONS


Function Description
==================================================
real
returns the real part x of z
imag
returns the imaginary part y of z
abs
returns the length r of z
angle
returns the direction of z
conj
returns the complex conjugate of z
==================================================

Here are some examples:

Example
Todefinethecomplexnumber,forinstance,z=(3,4)inmatlabwriteinmatlabeditor
>>z=3+4i
z=

3.0000+4.0000i

Example
Tofindtherealandimaginarypartsofthecomplexnumber,write
>>x=real(z)
x=

3
>>y=imag(z)

y=

Example
Tofindthelengthanddirectionofz,write
>>r=abs(z)
r=

5
>>=angle(z)

0.9273

Example
Tofindtheconjugateofz,write
>>zx=conj(z)
zx=

3.00004.0000i

-------------------------TASK 01-------------------------Writematlabfunctionzprint,whichtakesacomplexnumberandreturnsitrealpart,imaginary
part,magnitude,phaseinradians,andphaseindegrees.
Asamplerunofprogramis:
>>zprint(z)
Z=X+jYMagnitudePhasePh(deg)
3450.92753.13

-------------------------TASK 02-------------------------Computetheconjugate(i.e.z_conj[givevariablename])andtheinverse1/z(i.e.z_inv[give
variablename])foranycomplexnumberz.Displaytheresultsnumericallywithzprint.

-------------------------TASK 03-------------------------Taketwocomplexnumberandcomputez1+z2anddisplaytheresultsnumericallyusingzprint.

-------------------------TASK 04-------------------------Take two complex numbers and compute z1z2 and z1/z2. Use zprint to display the results
numerically.

5.3 COMPLEX EXPONENTIAL SIGNALS


Thecomplexexponentialsignalisdefinedas
x(t)=Aej(w0t+)
whichisacomplexvaluedfunctionoft,wherethemagnitudeofx(t)is
|x(t)|=A

argx(t)=(w0t+)

magnitudeorlengthofx(t)
angleordirectionofx(t)

UsingEulersformula,itcanbeexpressedinrectangularorCartesianform,i.e.
x(t)=Aej(w0t+)=Acos(w0t+)+jAsin(w0t+)
where
A=amplitude,

=phaseshift

w0=frequencyinrad/sec

Example
clear, close all, clc
n=0:1/10:10;
k=5;
a=pi/2;
x=k * exp(a*n*i);
% plot the real part
subplot(2,1,1)
stem(n, real(x), 'filled')

title('Real part of complex exp')


xlabel('sample #')
ylabel('signal amplitude')
grid
% plot the imaginary part
subplot(2,1,2)
stem(n, imag(x), 'filled')
title('Imaginary part of complex exp')
xlabel('sample #')
ylabel('signal amplitude')
grid

-------------------------TASK 05-------------------------Determinethecomplexconjugateoftheexponentialsignalgiveninaboveexampleandplotits
realandimaginaryportions.

-------------------------TASK 06-------------------------Generatethecomplexvaluedsignal
y(n)=exp

(-0.2 + j0.5)n

, 10n10

andplotitsmagnitude,phase,therealpart,andtheimaginarypartinseparatesubplots.

-------------------------TASK 07--------------------------

a) Generatearealexponentialx=anfora=0.7andnrangingfrom010.Findthediscretetime
as well as the continuous time version of this signal. Plot the two signals on same graph
(holdingboththegraphs).
b) Repeatthesameprogramwithvalueofa=1.3.

-------------------------TASK 08--------------------------

Multiplythetwodiscretesignalsx1=5exp(i*n*pi/4)andx2=an(usepointbypointmultiplicationof
thetwosignals).Plottherealaswellastheexponentialpartsfor0<a<1anda>1.

-------------------------TASK 09-------------------------Plotthediscretesignalx=a^|n|fornrangingfrom10to10.Drawtwosubplotsfor0<a<1and
a>1.

-------------------------TASK 10--------------------------

a) Generatethesignalx(t)=Aej(t + )forA=3,=0.4,and=2(1250).Takearangefort
thatwillcover2or3periods.
b) Plot the real part versus t and the imaginary part versus t. Use subplot(2,1,i) to put both
plotsinthesamewindow.
c) Verify that the real and imaginary parts are sinusoids and that they have the correct
frequency,phase,andamplitude.

Lab # 6

OBJECTIVESOFTHELAB

Inthislab,wewillcoverthefollowingtopics:

GeneratingSinusoids
AdditionofSinusoidswithVariationinParametersandtheirPlots
LinearPhaseShiftConceptWhenDealingWithSumofSinusoids

6.1

GENERATING SINUSOIDS

Sinusoidalsequencesareimplementedusingsin()&cos()functions.

Example:ContinuousTimeSinusoid
clc;
clear all;
close all;
f0 = 3;
A = 5;
t = -1:0.005:1;
y = A*cos(2*pi*f0*t);
figure, plot(t, y,'*:');
xlabel('Time, sec'), ylabel('Amplitude');
title('Graph of sinusoid');

Program:DiscreteTimeSinusoid
clc;
clear all;
close all;
M=10;

%samples/sec

n=-3:1/M:3;
A=2;
phase=0;
f=1;
x=A * sin(2*pi*f*n + phase);
stem(n,x,'linewidth', 2)
title('Discrete-Time Sine Wave: A sin(2*\pi*f*n + \phi)')
xlabel('Time Index')
ylabel('Signal Amplitude')
axis([n(1) n(end) -A A])
grid

6.2

CREATING PHASE SHIFT

Phaseshiftcanbecreatedbyaddinganangleto2ftforasinusoid.

Example
clc;
clear all;
close all;
fs=1000;
t=-3:1/fs:3;
A=2;
phase=0;
f=1;
x=A * sin(2*pi*f*t + phase);
plot(t,x, 'linewidth', 2)
title('Continuous-Time Sine Wave: A sin(2*\pi*f*t + \phi)')
xlabel('Time Index')
ylabel('Signal Amplitude')
axis([t(1) t(end) -A A])
grid

-------------------------TASK 01-------------------------Generatethe1x10rowvectorvwhoseithcomponentiscos(i/4).

-------------------------TASK 02-------------------------Write matlab code that draw graphs of sin (nx) on the interval 1x1 for n = 1, 2, 3, , 8.
(Hint:Useforloop)

-------------------------TASK 03-------------------------Given the signal exp(x)sin(8x) for 0x2, plot its continuoustime and discretetime
representations.Usesubplotandlabelproperly.

-------------------------TASK 04-------------------------Modifytheexamplegivenintopic6.2togenerateasinewavewithphaseshiftof+pi/2.Then
plot a cosine wave of same frequency, amplitude, and phase shift of 0 in another subplot.
Compareboththesignalsanddeterminetherelationshipbetweenthetwo.

-------------------------TASK 05-------------------------Write a program to generate a continuoustime sine wave of frequency 3 Hz, positive phase
shiftofpi/2,andamplitudeof5.Alsogenerateacontinuoustimecosinewaveoffrequency3
Hz,amplitudeof5,andphaseshiftof0.Plotthetwosignalsonseparatesubplotsandproperly
labelthem.Determinetherelationshipbetweenthetwosignals.

6.3

ADDITION OF SINUSOIDS
6.3.1

CASE 1: When Frequency, Phases, and amplitude of the sinusoids are same

clc ;
clear all;
close all;
t=-2:0.01:2;
x1=cos(2*pi*0.5*t);
x2=cos(2*pi*0.5*t);
x3=x1+x2;
subplot(3,1,1);
plot(t,x1,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');

title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase = 0


RADIAN');
subplot(3,1,2);
plot(t,x2,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase= 0
RADIAN');
subplot(3,1,3);
plot(t,x3,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('SUM OF THE ABOVE TWO COSINE SIGNALS');

6.3.2 CASE 2: When Frequencies and Phases of the sinusoids are same but
Amplitudes are different.

t=-2:0.01:2;

x1=2*cos(2*pi*0.5*t);
x2=cos(2*pi*0.5*t);
x3=x1+x2;
subplot(3,1,1);
plot(t,x1,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('COS WAVE , AMPLITUDE = 2, FREQ = 0.5 HZ, Phase = 0
RADIAN');
subplot(3,1,2);
plot(t,x2,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase= 0
RADIAN');
subplot(3,1,3);
plot(t,x3,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('SUM OF THE ABOVE TWO COSINE SIGNALS');

6.3.3 CASE 3: When Amplitudes and Phases of the sinusoids are the same but
Frequencies are different.

t=-2:0.01:2;
x1=cos(2*pi*0.5*t);
x2=cos(2*pi*1*t);
x3=x1+x2;
subplot(3,1,1);
plot(t,x1,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase = 0
RADIAN');
subplot(3,1,2);
plot(t,x2,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');

title('COS WAVE , AMPLITUDE = 1, FREQ = 1 HZ, Phase = 0


RADIAN');
subplot(3,1,3);
plot(t,x3,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('SUM OF THE ABOVE TWO COSINE SIGNALS');

6.3.4 CASE 4: When Amplitudes and Frequencies of the sinusoids are the same
but Phases are different

t=-2:0.01:2;
x1=cos(2*pi*0.5*t);
x2=cos((2*pi*0.5*t)+1);
x3=x1+x2;
subplot(3,1,1);
plot(t,x1,'linewidth',3);
grid;
ylabel('Amplitude');

xlabel('Time');
title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase = 0
RADIAN');
subplot(3,1,2);
plot(t,x2,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('COS WAVE , AMPLITUDE = 1, FREQ = 0.5 HZ, Phase = 1
RADIAN');
subplot(3,1,3);
plot(t,x3,'linewidth',3);
grid;
ylabel('Amplitude');
xlabel('Time');
title('SUM OF THE ABOVE TWO COSINE SIGNALS');

-------------------------TASK 06-------------------------Writeageneralprogramthattakesnsinusoidsfromuserofsamefrequency,amplitude,and
phase.Plottheindividualsinusoids&theresultantusingsubplotfunctiononsamefigure.Do
performproperlabeling.Note:Taketheamplitude,frequency,andphasegiveninexampleof
case1.Runthecodefordifferentvaluesofnandstatetheresultonpaper.

-------------------------TASK 07-------------------------Writeageneralprogramthattakesnsinusoidsfromuserofsamefrequencyandphasewith
varyingamplitudes.Takeamplitudefromuseronruntime.Plottheindividualsinusoids&the
resultant using subplot function on same figure. Do perform proper labeling. Note: Take the
amplitudeandfrequencygiveninexampleofcase2.Runthecodefordifferentvaluesofnand
statetheresultonpaper.

-------------------------TASK 08-------------------------Writeageneralprogramthattakesnsinusoidsfromuserofsameamplitudeandphasewith
varyingfrequencies.Takeeachfrequencyfromuseronruntime.Plottheindividualsinusoids&
theresultantusingsubplotfunctiononsamefigure.Doperformproperlabeling.Note:Takethe
amplitude and phase given in example of case 3. Run the code for different values of n and
statetheresultonpaper.

-------------------------TASK 09-------------------------Writeageneralprogramthattakesnsinusoidsfromuserofsameamplitudeandfrequency
withvaryingphases.Takeeachphasefromuseronruntime.Plottheindividualsinusoids&the
resultant using subplot function on same figure. Do perform proper labeling. Note: Take the
amplitudeandfrequencygiveninexampleofcase4.Runthecodefordifferentvaluesofnand
statetheresultonpaper.

Lab # 7

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

Generatingunitimpulseandunitstepsequences
Basicsignaloperations

------------------------------------------------------------------------------------------------------------

7.1 GENERATING UNIT IMPULSE AND UNIT STEP SEQUENCES


Usematlabcommandszerosandonestogenerateunitimpulseandunitstepsequences.

Example:UnitImpulseSequence
n=10:10;
%unitimpulse
x1=[zeros(1,10)1zeros(1,10)];
stem(n,x1,'filled');
xlabel('sample#');
ylabel('signalamplitude');
title('Unitimpulse');
axis([101012]);

Example:UnitStepSequence
n=10:10;
%unitstep
x1=[zeros(1,10)ones(1,11)];
stem(n,x1,'filled');
xlabel('sample#');
ylabel('signalamplitude');
title('Unitstep');
axis([101012]);

-----------------------------TASK 1-------------------------Usingonesfunction,plotthesignumsequenceoverinterval10n10.Itcanbedefinedas:

1,
1,
0,

0
0
0

------------------------------Task 2-------------------------Provethefollowing:

1
7.2 BASIC SIGNAL OPERATIONS
1) Signal Shifting
clc
clearall
closeall
n=0:0.002:4;
x=sin(2*pi*1*n);
subplot(2,1,1);
plot(n,x,'linewidth',2);
title('OriginalSignal');
xlabel('Time');
ylabel('SignalAmplitude');
axis([3411]);
grid;
subplot(2,1,2);
plot(n1,x,'linewidth',2);
title('Advancedsignal');
xlabel('Time');
ylabel('SignalAmplitude');

axis([3411]);
grid;

------------------------------Task 3-------------------------Delaytheoriginalsignalgiveninaboveexampleby1sec.Plotboththedelayed&originalsignalon
thesamefigure.

2) Signal Flipping
clear
n=1:1/1000:1;
x1=5*sin(2*pi*1*n);
subplot(2,1,1);
plot(n,x1,'g','linewidth',2);
axis([1155]);
xlabel('time');
ylabel('signalamplitude');

title('Originalsinewave');
grid;
subplot(2,1,2);
plot(n,x1,'r','linewidth',2);
axis([1155]);
xlabel('time');
ylabel('signalamplitude');
title('Flippedsinewave');
grid;

------------------------------Task 4-------------------------Flipthefollowingsignal:

5exp

Plottheoriginalsignalaswellastheflippedoneinthesamefigure.

------------------------------Task 5-------------------------Flipthefollowingsignal:
x[n]=2[n]+5[n1]+8[n2]+4[n3]+3[n4]
Plottheoriginalsignalaswellastheflippedoneinthesamefigure.

3) Amplitude Scaling
clear
n=1:7;
x=[1223221];

subplot(2,1,1);
stem(n,x,'filled');
title('Originalsignal');
xlabel('Timeindex');
ylabel('SignalAmplitude');
axis([1704]);
grid;

S=2;
subplot(2,1,2);
stem(n,S*x,'filled');
title('AmplitudeScaledsignal');
xlabel('Timeindex');
ylabel('SignalAmplitude');
axis([1708]);grid;

------------------------------Task 6-------------------------Scalethecontinuoustimesinusoidusedinsignalshiftingexamplebyafactorof2.

4) Time Scaling
%Decimation(downsampling)
clear
n=2:1/1000:2;
x1=sin(2*pi*2*n);
x2=decimate(x1,2);
subplot(2,1,1);
plot(x1);
title('Originalsignal');
xlabel('SampleNumber');
ylabel('SignalAmplitude');

axis([0400011]);
grid;
subplot(2,1,2);
plot(x2);
title('Decimatedsignal');
xlabel('SampleNumber');
ylabel('SignalAmplitude');
axis([0200011]);
grid;

------------------------------Task 7-------------------------Useinterpcommandintheaboveprogramtointerpolate(upsample)thesignalbyafactorof2.

5) Amplitude Clipping

clear
x=[34421442];
len=length(x);
y=x;
hi=3;
lo=3;
fori=1:len
if(y(i)>hi)
y(i)=hi;
elseif(y(i)<lo)
y(i)=lo;
end
end

subplot(2,1,1);
stem(x,'filled');
title('originalsignal');
xlabel('Samplenumber');
ylabel('SignalAmplitude');
subplot(2,1,2);
stem(y,'filled');
title('ClippedSignal');
xlabel('Samplenumber');
ylabel('SignalAmplitude');

6) Signal Replication
clear
x=[12321];
y=[xxxx];
subplot(2,1,1);
stem(x,'filled');
title('OriginalSignal');
xlabel('SampleNumber');
ylabel('SignalAmplitude');
axis([12003]);
grid;
subplot(2,1,2);
stem(y,'filled');
title('ReplicatedSignal');

xlabel('SampleNumber');
ylabel('SignalAmplitude');
axis([12003]);
grid;

Lab # 8

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

MakingSignalsCausalandNonCausal
Convolution
PropertiesofConvolution

------------------------------------------------------------------------------------------------------------

8.1 MAKING SIGNALS CAUSAL AND NON-CAUSAL


Causal Signals: A signal is said to be causal if it is zero for time t<0. A signal can be made causal by
multiplyingitwithunitstep.

Example
clc
clearall
closeall
t=2:1/1000:2;
x1=sin(2*pi*2*t);
subplot(3,1,1);
plot(t,x1,'LineWidth',2);
xlabel('time');
ylabel('signalamplitude');
title('sin(2*\pi*f*t)');
u=(t>=0);
x2=x1.*u;

subplot(3,1,2);
plot(t,u,'r','LineWidth',2);
xlabel('time');
ylabel('SignalAmplitude');
title('UnitStep');
subplot(3,1,3);
plot(t,x2,'k','LineWidth',2);
xlabel('time');
ylabel('signalamplitude');
title('causalversionofsin(2*\pi*f*t)');
figure;
plot(t,x1,t,u,'.',t,x2,'LineWidth',2);
text(0,1.2,'u(t)','FontSize',16);
text(1.2,1.1,'x(t)','FontSize',16);
text(0.8,1.1,'x(t)*u(t)','FontSize',16);
axis([221.51.5]);

----------------------------TASK 1---------------------------Samplethesignalgiveninaboveexampletogetitsdiscretetimecounterpart(take10samples/sec
assamplingrate).Maketheresultantsignalcausal.Displaythelollipopplotofeachsignal.

----------------------------TASK 2---------------------------Asignalissaidtobeanticausalifitexistsforvaluesofn<0.Makethesignalgiveninaboveexample
anticausal.

----------------------------TASK 3---------------------------Createafunctionbynameofsig_causalinmatlabthathastwoinputarguments:(i)adiscretetime
signal,and(ii)aposition vector.Thefunctionshouldmakethegivensignalcausalandreturnthe
resultantsignaltothecallingprogram.
AnoncausalsignalisshownintheFigbelow.Writematlabcodetomakethesignalcausalbycalling
theabovementionedfunction.Plottheoriginalnoncausalsignalandtheresultantcausalsignal.

8.2 CONVOLUTION
Usethematlabcommandconv(h,x)tofindconvolutionwhere
himpulseresponse
xinputsignal
Example
clc
clearall
closeall
h=[123454321];
x=sin(0.2*pi*[0:20]);

y=conv(h,x);
figure(1);
stem(x);
title('DiscreteFilterInputx[n]');
xlabel('index,n');
ylabel('Value,x[n]');
figure(2);
stem(y,'r');
title('DiscreteFilterOutputy[n]');
xlabel('index,n');
ylabel('Value,y[n]');

Eventhoughthereareonly21pointsinthexarray,theconvfunctionproduces8morepointsbecauseit
usestheconvolutionsummationandassumesthatx[n]=0whenn>20.

----------------------------TASK 4---------------------------Convolvethefollowingsignals:
x=[24642];
h=[3121];
Plottheinputsignalaswellastheoutputsignal.

----------------------------TASK 5---------------------------Convolve the signal x[n]=[1 2 3 4 5 6] with an impulse delayed by two samples. Plot the original
signalandtheresultofconvolution.

----------------------------TASK 6---------------------------Convolutionisassociative.Giventhethreesignalx1[n],x2[n],andx3[n]as:
x1[n]=[311]
x2[n]=[421]
x3[n]=[32123]
Showthat(x1[n]*x2[n])*x3[n]=x1[n]*(x2[n]*x3[n]).

----------------------------TASK 7---------------------------Convolutioniscommutative.Givenx[n]andh[n]as:
X[n]=[1321]
H[n]=[112]
Showthatx[n]*h[n]=h[n]*x[n].

----------------------------TASK 8---------------------------Determineh[n]forthesystem:
yn

kx n

Whenx[n]=2[n].Plottheinputsignal,impulseresponse,andoutputsignal.

----------------------------TASK 9---------------------------Giventheimpulseresponseofthesystemsas:
h[n]=2[n]+[n1]+2[n2]+4[n3]+3[n4]
Iftheinputx[n]=[n]+4[n1]+3[n2]+2[n3]isappliedtothesystem,determinetheoutputof
thesystem.

----------------------------TASK 10-------------------------Twosystemsareconnectedincascade.
x[n]

h1[n]

h2[n]

y[n]

h1[n]=[1321]
h2[n]=[112]
Iftheinputx[n]=[n]+4[n1]+3[n2]+2[n3]isapplied,determinetheoutput.

----------------------------TASK 11-------------------------Giventhesignals:
x1[n]=2[n]3[n1]+3[n2]+4[n3]2[n4]
x2[n]=4[n]+2[n1]+3[n2][n3]2[n4]
x3[n]=3[n]+5[n1]3[n2]+4[n3]
Verifythat
x1[n]*(x2[n]*x3[n])=(x1[n]*x2[n])*x3[n]
x1[n]*x2[n]=x2[n]*x1[n]

Lab # 9

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

PowerofContinuous&DiscretetimeSignals
ApplicationofFourierSeries
SynthesisofSquareWave
SynthesisofTriangularWave

------------------------------------------------------------------------------------------------------------

9.1 SIGNAL POWER


Averagepowerofcontinuoustimesignalcanbecalculatedusingtheformula:
T

1
P=
T

| x(t ) |

dt

Tocarryouttheintegral,EulerApproximationcanbeused.Itsimplytellsthatadefiniteintegralcanbe
approximatedusingasumi.e.
b

x(t )dt

N 1

x(a + nt )t , t =

n =0

ba
N

Inthismethod,theregionoverwhichintegraliscarriedoutisdividedintoNpartsorintervals,eachof
durationt,suchthatfunctionstaysconstantoverthoseshortintervals.Approximatingfunctioninthis
wayisshownbelow.NotethatasthenumberofintervalsNisincreased,theapproximationgetsbetter.

Approximatingintegralsusingsumsisadeepsubjectofnumericalanalysisbyitself;thereforeitsfurther
detailisoutofscope.ItisenoughtoknowthatEulersformulaiseasytoimplementandproducesgood
resultsforalmostallthesignalsthatwillbestudiedhereaslongasNisselectedlargeenough.

ExamplePowerofContinuousTimeCosine
clc
clearall
closeall

t=1:0.005:0.995;%timedurationofgivensignal;
xt=cos(2*pi*t/2);%generatesignal

plot(t,xt);

%plotsignal

%takeabsolutesquareofsignal

%lengthofinterval

delta_t=0.005;

%intervalduration

xlabel('time,t');
ylabel('Amplitude,A');
title('ContinuousTimeCosine');

abs_xt_2=abs(xt).^2;

T=2;

pxt=sum(abs_xt_2)*delta_t/T

%powerofgivensignal

pxt=

0.5000

---------------------------TASK 1---------------------------Calculate the power of discretetime cosine signal with period 20, defined over interval 0:19
usingthefollowingformula:

1
P=
N

N 1

| x[n] |
0

9.2 FOURIER SERIES


Fourierseriestheorystatesthataperiodicwavecanberepresentedasasummationofsinusoidalwaves
withdifferentfrequencies,amplitudesandphasevalues.

9.2.1

Synthesis of Square wave

Thesquarewaveforonecyclecanberepresentedmathematicallyas:
x(t)=

0<=t<T/2

T/2<=t<T

TheComplexAmplitudeisgivenby:
Xk=

(4/j*pi*k)

for

k=1,3,5..

for

k=0,2,4,6..

Forf=1/T=25Hz,onlythefrequencies25,50,75etc.areinthespectrum.

i.

Effect of Adding Fundamental, third, fifth, and seventh Harmonics

Example
clc
clearall
closeall

t=0:0.0001:8;
ff=0.5;

%WEAREUSINGSINEFUNCTIONBECAUSEFROMEXPONENTIALFORMOFFOURIER
%SERIESFINALLYWEARELEFTWITHSINETERMS
y=(4/pi)*sin(2*pi*ff*t);
%COMPLEXAMPLITUDE=(4/(j*pi*k))
fork=3:2:7
fh=k*ff;

x=(4/(k*pi))*sin(2*pi*fh*t);
y=y+x;
end

plot(t,y,'linewidth',1.5);
title('Asquarewavewithharmonics1st,3rd,5th,and7th');
xlabel('Time');
ylabel('Amplitude');

ii.

Effect of Adding 1st to 17th harmonics

Example
clc
clearall

t=0:0.0001:8;
ff=0.5;

%WEAREUSINGSINEFUNCTIONBECAUSEFROMEXPONENTIALFORMOFFOURIER

%SERIESFINALLYWEARELEFTWITHSINETERMS
y=(4/pi)*sin(2*pi*ff*t);
%COMPLEXAMPLITUDE=(4/(j*pi*k))
fork=3:2:17
fh=k*ff;
x=(4/(k*pi))*sin(2*pi*fh*t);
y=y+x;
end

plot(t,y,'linewidth',1.5);
title('Asquarewavewithharmonics1st17th');
xlabel('Time');
ylabel('Amplitude');

iii.

Effect of Adding 1st to 27th harmonics

Example
clc
clearall

closeall

t=0:0.0001:8;
ff=0.5;

%WEAREUSINGSINEFUNCTIONBECAUSEFROMEXPONENTIALFORMOFFOURIER
%SERIESFINALLYWEARELEFTWITHSINETERMS
y=(4/pi)*sin(2*pi*ff*t);
%COMPLEXAMPLITUDE=(4/(j*pi*k))
fork=3:2:55
fh=k*ff;
x=(4/(k*pi))*sin(2*pi*fh*t);
y=y+x;
end

plot(t,y,'linewidth',1.5);
title('Asquarewavewithharmonics1stto27th');
xlabel('Time');
ylabel('Amplitude');

---------------------------TASK 2---------------------------Writeaprogramthatplotsthesignals(t).
N

sin(2 nt )

n =1

s (t ) =

s (t ) = sin( 2 * t ) +

wheren=1,3,5,7,9andN=9or

sin(6 * t ) sin(10 * t ) sin(14 * t ) sin(18 * t )

+
+
+
3
5
7
9

---------------------------TASK 3---------------------------Writeaprogramthatplotsthesignals(t)butwithN=100.

---------------------------TASK 4---------------------------WhatdoyouconcludefromTASKS2&3?

9.2.2 Synthesis of Triangular wave


TheComplexAmplitudeisgivenby:
Xk=(8/*pi^2*k^2)forkisanoddinteger

forkforkisaneveninteger

Forf=1/T=25Hz

Example:TriangularwavewithN=3
clc;clearall;closeall
t=0:0.001:5;

x=(8/(pi*pi))*exp(i*(2*pi*0.5*t));
y=(8/(9*pi*pi))*exp(i*(2*pi*0.5*3*t));
s=x+y;

plot(t,real(s),'linewidth',3);
title('TriangularWavewithN=3');
ylabel('Amplitude');
xlabel('Time');

grid;

Example:TriangularwavewithN=11
clc;clearall;closeall

t=0:0.01:0.25;
ff=25;

x1=(8/(pi^2))*exp(i*(2*pi*ff*t));
fork=3:2:21,
fh=ff*k;
x=(8/(pi^2*k^2))*exp(i*(2*pi*fh*t));
y=x1+x;
end

plot(t,real(y),'linewidth',3);
title('TriangularWavewithN=11');
ylabel('Amplitude');
xlabel('Time');
grid;

Lab # 10

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

FourierSeriesRepresentationofContinuousTimePeriodSignals
ConvergenceofCTFourierSeries
PropertiesofCTFourierSeries
o Linearity
o TimeShifting
o FrequencyShifting
o TimeReversal
o TimeScaling

------------------------------------------------------------------------------------------------------------

10.1 FOURIER SERIES REPRESENTATION OF CONTINUOUS TIME


PERIOD SIGNALS
Asignalexpressedbytheformula

x(t ) =

a e
k

k =

jkw0t

a e

jk ( 2

)t

k =

isperiodicwithperiodT,asitislinearcombinationofharmonicallyrelatedcomplexexponentialsthat
areallperiodicwithT.Anywellbehavingperiodicfunctioncanbeexpressedasalinearcombinationof
harmonicallyrelatedcomplexexponentials.Therepresentationofperiodicsignalinthiswayisknownas
FourierseriesrepresentationandtheweightaksarereferredtoasFourierseriescoefficients.Givena
periodic signal x(t), it is possible to determine its Fourier series coefficients through the following
integral.
T
T

ak = x(t )e jkw t dt = x(t )e

jk ( 2

)t

dt

ThisintegralcanbedoneoveranytimeintervaloflengthT,theperiodofthesignalx(t).

10.1.1

Synthesis of a Simple Periodic Signal

Followingexampledemonstratesthatthelinearcombinationofharmonicallyrelatedcomplex
exponentialsleadstoaperiodicfunction.Thesignalusedinexampleis

x(t ) =

a e
3

jk0t

k =3

1
1
1
, where a0 = 1, a1 = a1 = , a2 = a2 = , a3 = a3 =
3
2
4

ExampleFSofCTPeriodicSignal
clc
clearall
closeall

t=3:0.01:3;

%durationofsignal

%dccomponentfork=0
x0=1;

%firstharmoniccomponentsfork=1andk=1
x1=(1/4)*exp(j*(1)*2*pi*t)+(1/4)*exp(j*(1)*2*pi*t);

y1=x0+x1;

%sumofdccomponentandfirstharmonic

%secondharmoniccomponentsfork=2andk=2
x2=(1/2)*exp(j*(2)*2*pi*t)+(1/2)*exp(j*(2)*2*pi*t);
y2=y1+x2;

%sumofallcomponentsuntilsecondharmonic

%thirdharmoniccomponentsfork=3andk=3
x3=(1/3)*exp(j*(3)*2*pi*t)+(1/3)*exp(j*(3)*2*pi*t);
x=x0+x1+x2+x3;

figure;
subplot(3,2,1);
plot(t,x1);
axis([3322]);
title('x1(t)');

subplot(3,2,2);
plot(t,y1);
axis([330.22]);
title('x0(t)+x1(t)');

subplot(3,2,3);
plot(t,x2);
axis([3322]);
title('x2(t)');

subplot(3,2,4);
plot(t,y2);
axis([3313]);
title('x0(t)+x1(t)+x2(t)');

subplot(3,2,5);

%sumofallcomponentsuntilthirdharmonic

plot(t,x3);
xlabel('t');
axis([3311]);
title('x3(t)');

subplot(3,2,6);
plot(t,x);
xlabel('t');
axis([3314]);
title('x(t)=x0(t)+x1(t)+x2(t)+x3(t)')

---------------------------TASK 1---------------------------Inaboveexample,aksarechosentobesymmetricabouttheindexk=0,i.e.ak=ak.Selectnew
aksonyourowntoalterthissymmetryandformthenewsignal.Whatdoyouobserve?Isx(t)a
realsignalwhencoefficientsarenotsymmetric?

---------------------------TASK 2---------------------------Acontinuoustimeperiodicsignalx(t)isrealvaluedandhasafundamentalperiodofT=8.The
nonzeroFourierseriescoefficientsforx(t)are

a1 = a1 = 2,

a3 = a*3 = 4 j

Expressx(t)aslinearcombinationofthesecoefficients.

---------------------------TASK 3---------------------------Adiscretetimeperiodicsignalx[n]isrealvaluedandhasafundamentalperiodofN=5.The
nonzeroFourierseriescoefficientsforx[n]are
j

a0 = 1, a2 = a2 = e , a4 = a4 = 2e

Expressx[n]aslinearcombinationofgivencoefficients.

10.1.2

Synthesis of a Simple Periodic Signal

Once the Fourier series (FS) coefficient of a continuous time periodic signal is
determined analytically using analysis equation, signal can be reconstructed using
synthesisequation.Considertheperiodicsquarewavesignaldefinedas

1,
x(t ) =
0,

| t |< T1
T1 <| t |< T

whereTisthetimeperiodandT1isthedutycyclewithFScoefficients

a0 =

sin( k 0T1 ) sin( k 2 (T1 T ))


2T1
, ak =
=
for k 0
T
k
k

Inthefollowingexamples,firstandidealsquarewaveiscreatedandthensquarewave
isapproximatedfromitsharmonicsusingsynthesisequationbylettingkinthepartial
sumgofromMtoMinsteadofto+,whereMis10,20,and100.Inallexamples

Tistakenas1sec.

ExampleIdealSquareWavecreatedbythresholding1HzCosineWave
%generateperfectsquarewave
t=1.5:0.005:1.5;%durationofsquarewave
xcos=cos(2*pi*t);%cosinewaveof1Hz
xpsqw=xcos>0;%thresholdingcosinewaveusingrelationaloperator

figure(1);
set(gcf,'defaultaxesfontsize',9);

plot(t,xpsqw,'lineWidth',2);
xlabel('t');
ylabel('x(t)');
title('PeriodicSquareWave(T=1)');
axis([1.51.50.11.1]);
grid;

ExampleFScoefficientsforSquarewavewithperiod1sec&variabledutycycle
k=15:15;

%numberofsquarewavecoefficients

T=1;

%timeperiodofsquarewave

T1=1/4;

%dutycycleofsquarewave

ak1=sin(k*2*pi*(T1/T))./(k*pi);

%squarewaveFourierseriescoefficients

%Ignorethe"dividebyzero"warningthathappens
%becausekinthedenominatorhits0.Wewillnowdo
%amanualcorrectionfora0>ak1(16)

ak1(16)=2*T1/T;

figure;
set(gcf,'defaultaxesfontsize',8);
subplot(3,1,1);
stem(k,ak1,'filled');
ylabel('ak');
title('FSCoefficientsforPeriodicSquareWave(T=1,T1=1/4)');

T1=1/8;
ak2=sin(k*2*pi*(T1/T))./(k*pi);
ak2(16)=2*T1/T;%Manualcorrectionfora0>ak2(16)

subplot(3,1,2);
stem(k,ak2,'filled');
ylabel('ak');
title('FSCoefficientsforPeriodicSquareWave...(T=1,T1=1/8)');

T1=1/16;
ak3=sin(k*2*pi*(T1/T))./(k*pi);
ak3(16)=2*T1/T;%Manualcorrectionfora0>ak3(16)

subplot(3,1,3);
stem(k,ak3,'filled');
xlabel('k');
ylabel('ak');
title('FSCoefficientsforPeriodicSquareWave(T=1,T1=1/16)');

---------------------------TASK 4---------------------------ConsideringtheFScoefficientsplotgivenbelow,whatdoyouobservehappenstotheenvelope
ofthecoefficientswhenT1isreducedfrom1/4to1/16withconstanttimeperiodT?


ExampleReconstructionofSquareWaveusing10termsi.e.M=10
clc
clearall
closeall

t=1.5:0.005:1.5;

%squarewaveduration

T=1;

%timeperiodofsquarewave

T1=1/4;

%dutycycleofsquarewave

w0=2*pi/T;

%fundamentalradianfrequencyofsquarewave

M=10;

%numberofcoefficients

k=M:M;

%2M+1totalcoefficientstoconstructsquarewave

ak=sin(k*2*pi*(T1/T))./(k*pi);
ak(M+1)=2*T1/T;

x=zeros(1,length(t));

%Manualcorrectionfora0>ak(M+1)

fork=M:M
x=x+ak(k+M+1)*exp(j*k*w0*t);
end

figure;
set(gcf,'defaultaxesfontsize',9);
plot(t,real(x),'lineWidth',2);
grid;
xlabel('t');
ylabel('x(t)');
title('ReconstructionfromFourierSerieswith21terms');

ExampleReconstructionofSquareWaveusing20termsi.e.M=20
clc
clearall
closeall


t=1.5:0.005:1.5;
T=1;
T1=1/4;
w0=2*pi/T;
M=20;
k=M:M;
ak=sin(k*2*pi*(T1/T))./(k*pi);

%Manualcorrectionfora0>ak(M+1)
ak(M+1)=2*T1/T;
x=zeros(1,length(t));
fork=M:M
x=x+ak(k+M+1)*exp(j*k*w0*t);
end

figure;
set(gcf,'defaultaxesfontsize',9);
plot(t,real(x),'lineWidth',2);
grid;
xlabel('t');
ylabel('x(t)');
title('ReconstructionfromFourierSerieswith41terms');

ExampleReconstructionofSquareWaveusing100termsi.e.M=100
clc
clearall
closeall

t=1.5:0.005:1.5;
T=1;
T1=1/4;


w0=2*pi/T;
M=100;
k=M:M;
ak=sin(k*2*pi*(T1/T))./(k*pi);
ak(M+1)=2*T1/T;%Manualcorrectionfora0>ak(M+1)

x=zeros(1,length(t));
fork=M:M
x=x+ak(k+M+1)*exp(j*k*w0*t);
end

figure;
set(gcf,'defaultaxesfontsize',9)
plot(t,real(x),'lineWidth',2);
grid;

xlabel('t');
ylabel('x(t)');
title('ReconstructionfromFourierSerieswith201terms');

---------------------------TASK 5---------------------------ConsideringtheplotsofsquarewavereconstructedusingM=10,20,&100termsabove,what
doyouobserveaboutGibbsphenomena?

---------------------------TASK 6---------------------------GiventhefollowingFScoefficients:

1,
ak =
2,

k even
k odd

Plot the coefficients & reconstructed signal. Take the terms for reconstructed signal to be
M=10,20,&50.WhateffectdoyouseewhenMisvaried?

---------------------------TASK 7---------------------------GiventhefollowingFScoefficients:

jk ,
ak =
0,

| k |< 3
otherwise

Plotthecoefficients&reconstructedsignal.Take10terms(M=10)forreconstructedsignal.

10.2 PROPERTIES OF FOURIER SERIES


10.2.1

Linearity

Given two periodic signals x(t) and y(t) having same period, linearity property of FS
representationcanbeexpressedas

FS
FS
FS

x(t ) a k , y (t ) bk x(t ) + y (t ) a k + bk

Where ak and bk are FS coefficients of x(t) and y(t) respectively. This property can be used in
evaluatingFScoefficientsofaperiodicsignalthatcanbeexpressedasalinearcombinationof
otherperiodicsignalswhoseFScoefficientsareknown.

Following example demonstrates the validity of linearity property using two periodic square
wavesignaslx(t)andy(t)withT=1anddifferentT1parameters.

1,
x(t ) =
0,

| t |< T1

1,
y (t ) =
0,

| t |< T1

T1 <| t |< T

T1 <| t |< T

T = 1 T1 = 1
2

T = 1 T1 = 1
2

ExampleDemonstrationofLinearityPropertyofFS
clc
clearall
closeall

%Generationof1stsignalx(t)
t=1.5:0.005:1.5;
xcos=cos(2*pi*t);

xt=xcos>0;

figure(1);
set(gcf,'defaultaxesfontsize',9)
subplot(2,1,1);
plot(t,xt,'lineWidth',2);
xlabel('t');
ylabel('x(t)');
title('PeridoicSquareWave(T=1,T1=0.250)');
axis([1.51.50.11.1]);
grid;

%Generationof2ndsignaly(t)
T=1;
T1=0.125;
lenT=T/0.005;
ytemp=zeros(1,lenT);
lenT1=T1/0.005;
ytemp(round(lenT/2)lenT1:round(lenT/2)+lenT11)=ones(1,2*lenT1);

yt=[ytempytempytemp0];%Thelast0addedtomakethesizeofytequaltolength(t)

subplot(2,1,2);
plot(t,yt,'lineWidth',2);
xlabel('t');
ylabel('y(t)');
title('PeriodicSquareWave(T=1,T1=0.125)');
axis([1.51.50.11.1]);
grid;

%FScoefficientsofperiodicsquarewaves
k=50:50;

T1=0.25;
ak=sin(k*2*pi*(T1/T))./(k*pi);
ak(51)=2*T1/T;%Manualcorrectionfora0>ak(51)

T1=0.125;
bk=sin(k*2*pi*(T1/T))./(k*pi);
bk(51)=2*T1/T;%Manualcorrectionforb0>bk(51)

%ApplicationoflinearitypropertyofFS
ck=ak+bk;

%ReconstructionwithM=50
w0=2*pi/T;
zt=zeros(1,length(t));
fork=50:50
zt=zt+ck(k+51)*exp(j*k*w0*t);
end

figure(2);
set(gcf,'defaultaxesfontsize',9)
plot(t,real(zt),'lineWidth',2);
xlabel('t');
ylabel('z(t)=x(t)+y(t)');
title('Reconstructionfromak+bk''swith101terms');
grid;

---------------------------TASK 8---------------------------PlottheFScoefficientsandreconstructthesignalforthefollowingsequence:

10.2.2

Time Shifting

ThetimeshiftingpropertyofFSstatesthat

FS
FS

x(t ) ak x(t t 0 ) e jk0t ak , 0 = 2 T

Wherex(t)isaperiodicsignalwithFScoefficientsakandx(tt0)isthetimeshiftedversionofit.
ThispropertycanbeusedtoevaluateFScoefficientsofaperiodicsignalthatcanbeexpressed
astimeshiftedversionofanotherperiodicsignalwhoseFScoefficientsareknown.

Followingexampledemonstratesthevalidityoftimeshiftingproperty.Considerperiodicsquare
wavewithperiodT=1andT1=0.25,itsFScoefficientsaksare

2T
sin( k 2 (T1 T )) sin( k / 2))

=
for k 0
a0 = 1 = 0.5, ak =

k
k
T

Letitbeshiftedbyt0=0.25,thenFScoefficientsbksforx(tt0)=x(t0.25)canbefoundusing
timeshiftingpropertyas

bk = e jk0t0 ak ,
t 0 = 0.25,
0 = 2 T = 2

ExampleDemonstrationofTimeShiftingPropertyofFS
clc
clearall
closeall

%Generationofperiodicsquarewave
t=1.5:0.005:1.5;
xcos=cos(2*pi*t);
xt=xcos>0;

%FScoefficientsofperiodicsquarewave
k=50:50;
T=1;
T1=0.25;
ak=sin(k*2*pi*(T1/T))./(k*pi);

ak(51)=2*T1/T;%Manualcorrectionfora0>ak(51)

%Amountoftimeshift
t0=0.25;

%FScoefficientsofthetimeshiftedsignal
w0=2*pi/T;
bk=ak.*exp(j*k*w0*t0);

%Reconstructionfrombk'swith101terms(M=50)
yt=zeros(1,length(t));
fork=50:50
yt=yt+bk(k+51)*exp(j*k*w0*t);
end

figure(1);
set(gcf,'defaultaxesfontsize',9);
subplot(2,1,1);
plot(t,xt,'lineWidth',2);
xlabel('t');
ylabel('x(t)');
title('PeriodicSquareWave(T=1,T1=0.25)');
axis([1.51.50.21.2]);
grid;

subplot(2,1,2);
plot(t,real(yt),'lineWidth',2);
xlabel('t');
ylabel('y(t)=x(t0.5)');
title('Reconstructionfrombk''swith101terms');
axis([1.51.50.21.2]);
grid;

---------------------------TASK 9---------------------------Giventhesquarewave,plottheFScoefficientsandreconstructthesignalforthefollowing:
FS
FS

jM0t
x(t ) ak e
x(t ) ak M , 0 = 2 T

10.2.3

Time Reversal

ThetimereversalpropertyofFSstatesthat

FS
FS

x(t ) ak x(t ) a k ,

If FS representation for a periodic signal x(t) is known, then FS representation for the time
reversedversionofthesignalx(t)canbedeterminedthroughthisproperty.

ExampleDemonstrationofTimeReversalPropertyofFS
clc
clearall

closeall

%Generationofperiodicsquarewave
t=1.5:0.005:1.5;
xsin=sin(2*pi*t);
xt=xsin>0;

%FScoefficientsofperiodicsquarewave
k=50:50;
T=1;
T1=0.25;
w0=2*pi/T;
t0=0.25;
ak=exp(j*k*w0*t0).*sin(k*2*pi*(T1/T))./(k*pi);
ak(51)=2*T1/T;%Manualcorrectionfora0>ak(51)

%FScoefficientsofthetimereversedsignal
bk=fliplr(ak);

%Reconstructionfromak'swith101terms(M=50)
xtr=zeros(1,length(t));
fork=50:50
xtr=xtr+ak(k+51)*exp(j*k*w0*t);
end

%Reconstructionfrombk'swith101terms(M=50)
yt=zeros(1,length(t));
fork=50:50
yt=yt+bk(k+51)*exp(j*k*w0*t);
end

figure(1);

set(gcf,'defaultaxesfontsize',8);
subplot(3,1,1);
plot(t,xt,'lineWidth',2);
ylabel('x(t)');
title('PeriodicSquareWave(T=1,T1=0.25)');
axis([1.51.50.21.2]);
grid;

subplot(3,1,2);
plot(t,xtr,'lineWidth',2);
ylabel('x(t)');
title('PeriodicSquareWaveReconstructedfromitsFS');
axis([1.51.50.21.2]);
grid;

subplot(3,1,3);
plot(t,real(yt),'lineWidth',2);
xlabel('t');
ylabel('y(t)=x(t)');
title('Reconstructionfrombk''swith101terms');
axis([1.51.50.21.2]);
grid;

---------------------------TASK 10--------------------------Giventhesignalx(t)intask7,dothefollowing:

a) Plotthetimereverseversionofthesignalx(t)directly,
b) PlotFScoefficientsakoftimereversedsignal,
c) PlotthereconstructedtimereversedsignalusingFScoefficientsak

10.2.4

Time Scaling

ThetimescalingpropertyofFSstatesthat

jMt
x(t ) = ak e
x(t ) = ak e jMt

k =
k =

That is, if x(t) is periodic with period T and fundamental frequency w=2/T, then time scaled
version of x(t), x(t) where being positve real number has w as its fundamental frequency
and the FS coefficients for x(t) is same as those of x(t). Be careful about using the right i.e.
scaledfrequency(orperiod)inthereconstruction.

Mathematicallyitcanbeexpressedas:

FS
FS

x(t ) ak

x(t ) = x(t + T ), =

2
T

x(t ) ak

x(t ) = x( (t +

)), =

2
T

ExampleDemonstrationofTimeScalingPropertyofFShaving=0.5
clc
clearall
closeall

%Generationofperiodicsquarewave
t=1.5:0.005:1.5;
xcos=cos(2*pi*t);
xt=xcos>0;

%FScoefficientsofperiodicsquarewave
k=50:50;
T=1;
T1=0.25;
ak=sin(k*2*pi*(T1/T))./(k*pi);
ak(51)=2*T1/T;%Manualcorrectionfora0>ak(51)

%Timescalingparameters
alp1=0.5;

%w'sforthetimescaledsignals
w0=2*pi/T;
w1=alp1*w0;

%Reconstructionfromak'swith101terms(M=50)
xat1=zeros(1,length(t));
fork=50:50
xat1=xat1+ak(k+51)*exp(j*k*w1*t);
end

figure(1);

set(gcf,'defaultaxesfontsize',8);
subplot(2,1,1);
plot(t,xt,'lineWidth',2);
ylabel('x(t)');
title('PeriodicSquareWave(T=1,T1=0.25)');
axis([1.51.50.21.2]);
grid;

subplot(2,1,2);
plot(t,real(xat1),'lineWidth',2);
ylabel('x(t)');
title('Reconstructionfromak''s(alp1=0.5,w1=0.5*w0)');
axis([1.51.50.21.2]);grid;

---------------------------TASK 11--------------------------Given the periodic square wave x(t) with T = 1 & T1 = 0.25, rewrite the above code for time
scalingwhenvalueofalphais2i.e.x(t)=x(2t).

Lab # 11

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

PropertiesofCTFourierSeries
o Multiplication
o Conjugation&ConjugateSymmetry
CharacterizationofLTISystems
FilteringSignals
DelayFilter

------------------------------------------------------------------------------------------------------------

11.1 PROPERTIES OF FOURIER SERIES


11.1.1

Multiplication

Giventwoperiodicsignalsx(t)andy(t)havingsameperiodTwithFScoefficientsakandbk,there
product signal x(t)y(t) is also periodic and its FS coefficients can be determined using
multiplicationproperty:

FS
FS
FS
x
(
t
)

a
,
y
(
t
)

x
(
t
)
y
(
t
)

c
=
al bk l

k
k
k
l =

Whereckisthediscretetimeconvolutionoftwosequencesaksandbks

Following example demonstrates the validity of multiplication property using periodic square
wavesignalx(t)andcosingsignaly(t).ForthesquarewavesignalwithT=1andT1=0.25,FS
coefficientsaksare

2T
sin( k 2 (T1 T )) sin( k / 2))
=
for k 0
a0 = 1 = 0.5, ak =

k
k
T

Forthecosinesignalof1Hz,FScoefficientsbksare

k = 1
0.5,

= 0.5 (k + 1) + 0.5 (k 1)
bk =

0
,
otherwise

Tocarryoutconvolutionofakandbksequences,twoapproachesareused:firstoneisthedirect
implementionofsumformulaforckgiveninmultiplicationpropertyusingforloop;andsecond
oneisbyusingthefollowingpropertyofimpulsefunction

x[k ] * (k k 0 ) = x(k k 0 )

Applyingitonakandbk:

ak * bk = ak * (0.5 (k + 1) + 0.5 (k 1))

= 0.5ak (k + 1) + 0.5ak (k 1)

ExampleDemonstrationofMultiplicationPropertyofFS
clc
clearall
closeall

%Generationof1Hzcosine
t=1.5:0.005:1.5;
yt=cos(2*pi*t);
xt=yt>0;%Generationofperiodicsquarewave

%FScoefficientsofperiodicsquarewave
k=50:50;
T=1;
T1=0.25;
ak=sin(k*2*pi*(T1/T))./(k*pi);
ak(51)=2*T1/T;

%1stwaytocreateck's
%Forloopimplementationofconvolution
bk=zeros(1,201);%FScoefficientsof1Hzcosine(overk=100:100)
bk(100)=0.5;
bk(102)=0.5;
ck1=zeros(1,101);
fork=50:50
u=0;
forL=50:50
u=u+ak(L+51)*bk(kL+101);
end
ck1(k+51)=u;
end

%2ndwaytocreateck's
%Asimplerwayofimplementingconvolutionusingpropertiesofimpulse
bk=zeros(1,101);%FScoefficientsof1Hzcosine(overk=50:50)
bk(50)=0.5;
bk(52)=0.5;
ck2=0.5*[ak(2:101)0]+0.5*[0ak(1:100)];


%Checktheequalityofck1andck2
ck1ck2

%Reconstructionfromck1'swith101terms(M=50)
w0=2*pi/T;
zt=zeros(1,length(t));
fork=50:50
zt=zt+ck1(k+51)*exp(j*k*w0*t);
end

figure(1);
set(gcf,'defaultaxesfontsize',8);
subplot(3,1,1);
plot(t,xt,'lineWidth',2);
ylabel('x(t)','lineWidth',2);
title('PeriodicSquareWave(T=1,T1=0.25)');
axis([1.51.51.21.2]);
grid;

subplot(3,1,2);
plot(t,yt,'lineWidth',2);
ylabel('y(t)');
title('1HzCosine');
axis([1.51.51.21.2]);
grid;

subplot(3,1,3);
plot(t,real(zt),'lineWidth',2);
xlabel('t');
ylabel('z(t)=x(t)*y(t)');
title('Reconstructionfromck''s');

axis([1.51.51.21.2]);
grid;

---------------------------TASK 1---------------------------AnotherwaytocomputeFScoefficientsofckisbyusingmatlabconvolutionfunctioni.e.conv
toconvolveakandbksequences.Dothefollowingstepstoachievethis:

a) Createcosinesignalof1Hzandgeneratesquarewavefromit
b) ComputeFScoefficientsakofsquarewavewithT=1andT1=0.25overk=50:50.What
isthelengthofsequence?
c) ComputeFScoefficientsbkofcosinesignalusingequation

bk = 0.5 (k + 1) + 0.5 (k 1)

Whatisthelengthofbk?
d) Convolveakandbkusingconv.Whatisthelengthofthesequence?
e) ReconstructtheresultantsignalfromckforM=50.
f) Plotx(t),y(t)andreconstructedsignal.

---------------------------TASK 2---------------------------ConsiderthefollowingthreecontinuoustimesignalswithfundamentalperiodofT=.

x(t ) = cos(4t )

y (t ) = sin(4t )

z (t ) = x(t ) y (t )

a) DeterminetheFScoefficientsofx(t)andy(t)analytically.
b) Usemultiplicationpropertytocomputethecoefficientsofz(t)usingmatlab.
c) Reconstructthesignalz(t)fromitscoefficientsinmatlab.
d) Plotthesignalx(t),y(t),andreconstructedsignalz(t)withproperlabeling.

11.1.2

Conjugation & Conjugate Symmetry

Whencomplexconjugateofperiodicsignalx(t)iscomputed,correspondingFScoefficientsare
timereveresedi.e.flippedaboutk=0andcomplexconjugated.Thatis
FS
FS

*
x(t ) ak x (t ) a*k

Followingexampledemonstratesthevalidityofconjugationproperty.Cosideracomlexperiodic
signal z(t) that has a cosine x(t) and a square wave y(t) as its real and imaginary parts
respoectively.

z = x(t ) + jy (t )

x(t ) = cos(4t )

| t |< 1 4
1,
=
y
(
t
)

T1 <| t |< 1 2
0,

Wherethecoefficientsare:

FS
2T
sin(k 2)

x(t ) ak ,
a0 = 1 ,
ak =
for k 0
T
k

FS

0.5, k = 1
(
)
,
y
t

b
b
=

k
k
otherwise
0,

Given FS representations of x(t) and y(t), FS represenation of z(t) can be computed using the
linearitypropertyofFS.
FS

z (t ) ck = ak + jbk

ExampleDemonstrationofConjugationPropertyofFS
clc
clearall
closeall

%Generationof1Hzcosine(Realpartofoursignal)
t=1.5:0.005:1.5;
xt=cos(2*pi*t);
yt=xt>0;
zt=xt+j*yt;%perodiccomplexvaluedsignal

%FScoefficientsof1Hzcosine,xt(overk=50..50)
ak=zeros(1,101);
ak(50)=0.5;
ak(52)=0.5;

%FScoefficientsofperiodicsquarewave,yt
k=50:50;
T=1;
T1=0.25;
bk=sin(k*2*pi*(T1/T))./(k*pi);
bk(51)=2*T1/T;

%FScoefficientsofzt(usinglineartypropertyofFS)
ck=ak+j*bk;
%Flipck'sandconjugate
dk=conj(fliplr(ck));
%Reconstructionfromdk'swith101terms(M=50)
w0=2*pi/T;
zrt=zeros(1,length(t));
fork=50:50

zrt=zrt+dk(k+51)*exp(j*k*w0*t);
end

figure(1);
set(gcf,'defaultaxesfontsize',8);
subplot(2,2,1);
plot(t,xt,'lineWidth',2);
ylabel('x(t)');
title('Realpartofz(t),1HzCosine');
set(gca,'ylim',[1.21.2]);
grid;

subplot(2,2,2);
plot(t,yt,'lineWidth',2);
ylabel('y(t)');
title('Imag.partofz(t),PeriodicSquareWave');
axis([1.51.51.21.2]);
grid;

subplot(2,2,3);
plot(t,real(zrt),'lineWidth',2);
xlabel('t');ylabel('Re[zr(t)]');
title('RealpartofReconstructionfromdk''s');
axis([1.51.51.21.2]);
grid;

subplot(2,2,4);
plot(t,imag(zrt),'lineWidth',2);
xlabel('t');
ylabel('Im[zr(t)]');
title('Imag.partofReconstructionfromdk''s');
axis([1.51.51.21.2]);

grid;

11.2 CHARACTERIZATION OF LSI SYSTEMS


There are different ways to characterize discretetime LSI systems including difference equation,
impulseresponse,transferfunction,andfrequencyresponse.Weareconsideringhereonlydifference
equation.

Difference Equation
AdiscretetimeLSIsystemischaracterizedbythefollowinggeneralformdifferenceequation
y(n) + a1y1(n-1) + a2y2(n-2) + + aNyN(n-N) = b0x0(n) + b1x1(n-1) +
+ bMxM(n-M)
where
x(n)andy(n)areinputandoutput,respectively.
FiniteintegersMandNrepresentthemaximumdelaysintheinputandoutputrespectively.

Theconstantsaiandbiarecalledthefiltercoefficients.
DifferenceequationcanbeimplementedinMatlabasfollow:
y = filter(b, a, x)
whichtakestheinputsignalinvectorxandfiltercoefficientaandb.TheVectorBconstitutesthefeed
forwardfiltercoefficientsandvectorAconstitutesthefeedbackwardfiltercoefficients.IncaseofFIR
filters,thefeedbackwardfiltercoefficientconsistsofasingle1.

ExampleDemonstrationofConjugationPropertyofFS

y[n ] + 2 y[n 1] + 3 y[n 2] = x[n] + 3 x[n 1] + x[ n 2]

A=coefficientsofy(n)=[123]
B=coefficientsofx(n)=[131]
X=inputsequence=[11111]
Program

A=[123];
B=[131];
X=[11111];
Y=filter(B,A,X)

Output:

Y=

12235

---------------------------TASK 3---------------------------Giventhefollowingdifferenceequationandinputsignal,calculatetheoutput.

5 y[n] = 4 x[n] + x[n 1] + 6 x[n 3]

x[n] = [1 3 5 7 9]

11.3 FILTERING SIGNALS


MatlabprovidesthecommandFilterfordevelopingonedimensionaldigitalfilter.
Y=filter(B,A,X)
ItfiltersthedatainvectorXwiththefilterdescribedbyvectorsAandBtocreatethefiltereddataY.
Thefilterisa"DirectFormIITransposed"implementationofthestandarddifferenceequation:
a(1)*y(n)=b(1)*x(n)+b(2)*x(n1)+...+b(nb+1)*x(nnb)
a(2)*y(n1)...a(na+1)*y(nna)
ForFIRfilters,keepa=1.

Example
clc
clear

b=[123454321];
a=1;
x=cos(0.2*pi*[0:20]);
y=filter(b,a,x);

figure;
subplot(2,1,1);
stem(x);
title('DiscreteFilterInputx[n]');
xlabel('index,n');
ylabel('Value,x[n]');

subplot(2,1,2);
stem(y,'r');
title('DiscreteFilterOutputy[n]');
xlabel('index,n');

ylabel('Value,y[n]');

11.3.1

3-Point Averaging Filter

clc
clearall
closeall

n=3:7;

%inputsignal
x=[00024642000];

%filtercoefficients
b=[1/31/31/3];

%feedforwardfiltercoefficientsof3pointaverager

a=1;

%feedbackfiltercoefficients

%outputsignal
y=filter(b,a,x);

subplot(2,1,1);
stem(n,x,'filled');
xlabel('samplenumber');
ylabel('signalamplitude');
title('origianlsignal');

subplot(2,1,2);
stem(n,y,'filled');
xlabel('samplenumber');
ylabel('signalamplitude');
title('Resultof3pointaverager:y[n]=(x[n]+x[n1]+x[n2])/3');

---------------------------TASK 4---------------------------Modifyaboveprogram(i.e.exampleof3ptaveragingfilter)toimplement

1. A3pointnoncausalaverager
2. Acentralizedaverager

---------------------------TASK 5---------------------------Afilterhascoefficientsbk={13241}.Aninputsignal
x[n]=[n]3[n1]+3[n2]+4[n3]2[n4]
isappliedtothefilter.Findtheoutputy[n].

---------------------------TASK 6--------------------------Anonrecursivediscretetimesystemhasfiltercoefficients{1,2,3,2}.Aninputsignal(shown
inFig)isappliedtothesystem.Determinethediscretetimeoutputofthefiltering.Writecode
toplottheoriginalsignalaswellastheoutputontwosubplotsofthesamefigure.

2 2
1

2101234567

11.3.2

Application of 3-Point Averaging Filter to Smooth Signal

clc
clearall
closeall

%durationofinputsignal
n=0:40;

%inputsignal
x=(1.02).^n+0.5*cos(2*pi*n/8+pi/4);

%filtercoefficients
b1=[1/31/31/3];
a1=1;


%plotoforiginalsignal
subplot(2,1,1)
stem(n,x,'filled');
title('inputsignal');
xlabel('samplenumber');
ylabel('signalamplitude');

%outputof3pointfiltering
y1=filter(b1,a1,x);

subplot(2,1,2);
stem(n,y1,'filled');
title('outputof3pointfiltering');
xlabel('samplenumber');
ylabel('signalamplitude');

---------------------------TASK 7--------------------------DevelopacausalFIRfilterthataveragesfivesamplesoftheinputsignal
x[n]=2[n]+5[n1]+8[n2]+4[n3]+3[n4]

---------------------------TASK 8--------------------------Apply7pointfilteringfilterontheinputsignalgiveninexampleofsignalsmoothing.

11.4 DELAY FILTER


AdelaysystemisasimpleFIRfilter.Adelayby2isgivenbyfiltercoefficients{0,0,1}.

---------------------------TASK 9--------------------------Giventhesignal
x[n]=[n]+4[n1]+3[n2]+2[n3]
Delaythissignalby2usingtheabovementionedfiltercoefficientsusingfiltercommand.

---------------------------TASK 10-------------------------Adelayfilterdelaysaninputsignal.Theamountofdelaydependsonfiltercoefficients.Designa
delayfilterthatdelaysaninputsignalby6units.

---------------------------TASK 11-------------------------Usethefilterdesignedintask10todelaytheinputsignal:
x[n]=[n]4[n1]+3[n2]+2[n3]6[n4]+2[n6]

Writecodetoplottheinputsignalaswellastheoutputsignal.

---------------------------TASK 12--------------------------Create a function that takes a signal and a delay count as arguments. The purpose of the
function is to delay the signal by that amount (use filter command). Call this function from a
mainprogramtodelayarequiredsignal.

Lab # 12

OBJECTIVESOFTHELAB
-----------------------------------------------------------------------------------------------------------Thislabaimsattheunderstandingof:

BeatNotes
AmplitudeModulation
DeterminingImpulseResponseofaSystem
DeterminingFrequencyResponseofaSystem
DesigningFiltersusingmatlabcommandFIR1

------------------------------------------------------------------------------------------------------------

12.1 BEAT NOTES


Whentwosinusoidalsignalswithdifferentfrequenciesaremultiplied,abeatnoteisproduced.Tofulfill
the spectrum representation, the resultant signal is expressed as an additive linear combination of
complexexponentialsignals.Forinstance,considerabeatsignalastheproductoftwosinusoids

x(t ) = sin(10t ) cos(t )

= 1 cos 11t + 1 cos 9t


2
2
2
2

Orinotherwords,beatnotecanbeproducedbyaddingtwosinusoidswithnearlyidenticalfrequencies,
i.e.

x(t ) = cos(2f1t ) + cos(


2f 2 t )

where

f1
f2
fc
fd

=
=
=
=

fc fd
fc + fd
1 (f + f )
2
2 1
1 ( f1 f 2 )
2

1)

first frequency
sec ond frequency
center frequency
deviation frequency

And,thus

x(t ) = sin(2f d t ) cos(2f c t )

= 1 cos (2 ( f c f d )t ) + 1 cos (2 ( f c + f d )t )
2
2

2)

= 1 cos(2f1t ) +
2f 2t )
1 cos(
2
2

ExampleBeatNoteimplementationforfc=200andfd=20Hz
clc
clearall
closeall

t=0:0.00001:0.1;

fd=20;Ad=2;
fc=200;Ac=5;

3)

s1=Ad*cos(2*pi*fd*t);
s2=Ac*cos(2*pi*fc*t);

X=s1.*s2;

figure;subplot(3,1,1);
plot(t,s1,'linewidth',1.5);grid;ylabel('Amplitude');xlabel('Time');
title('DifferenceFrequencySignal');

subplot(3,1,2);
plot(t,s2,'linewidth',1.5);grid;ylabel('Amplitude');xlabel('Time');
title('CenterFrequencySignal');

subplot(3,1,3);
plot(t,X,'linewidth',1.5);grid;ylabel('Amplitude');xlabel('Time');
title('BeatSignal');

---------------------------TASK 1---------------------------Modifytheabovebeatsignalcodeinsuchawaythattheresultantbeatsignal&itsenvelope
bothareshowninfollowingfigure.(Hint:Envelopeismadefromdeviationfrequencysignal).

12.2 AMPLITUDE MODULATION


Amplitudemodulationistheprocessofmultiplyingalowfrequencysignalbyahighfrequencysinusoid.
ItisatechniqueusedtobroadcastAMradio.TheAMsignalistheproductoftheform

x(t ) = v(t ) cos(2f c t )

4)

where the frequency of the cosine (fc hertz) is much higher than any frequencies contained in the
spectrumofv(t),whichrepresentthedatasignaltobetransmitted.Thecosinewaveiscalledthecarrier
signal,anditsfrequencyiscalledthecarrierfrequency.

ExampleAMSignalImplementation
clc
clearall
closeall

t=0:0.00001:0.1;


fd=20;Ad=2;
fc=200;Ac=5;

s1=Ad*cos(2*pi*fd*t);
s2=Ac*cos(2*pi*fc*t);

B=s1.*s2;
AM=B+s2;

figure;
subplot(3,1,1);
plot(t,s1,'linewidth',1.5);
grid;
ylabel('Amplitude');
xlabel('Time');
title('ModulatingSignal');

subplot(3,1,2);
plot(t,s2,'linewidth',1.5);
grid;
ylabel('Amplitude');
xlabel('Time');
title('CarrierSignal');

subplot(3,1,3);
plot(t,AM,'linewidth',1.5);
grid;
ylabel('Amplitude');
xlabel('Time');
title('AmplitudeModulatedSignal');

---------------------------TASK 2---------------------------ModifytheaboveAMsignalcodeinsuchawaythattheresultantbeatsignal&itsenvelope
bothareshowninfollowingfigure.(Hint:Envelopeismadefromdeviationfrequencysignal).

12.3 IMPULSE RESPONSE OF SYSTEM


Givenanysystemcharacteristics,itsimpulseresponsecanbedeterminedbyfollowingmatlabfunction:

y = impz ( b, a)
Wherebarecoefficientsofinputsandathatofoutputs.Followingexampleillustratesitsuse:

ExampleImpulseResponseofy[n]=0.2x[n]+0.4x[n1]
clc;clearall;closeall

b=[0.20.4];
a=[1];
y=impz(b,a);

figure;stem(y,'filled');title('ImpulseResponseofanFIRFilter');
xlabel('index,n');ylabel('Value,x[n]');axis([030.51]);

---------------------------TASK 3---------------------------Determinetheimpulseresponseoffollowingdifferenceequation:

y[n] 1.56 y[n 1] + 0.64 y[n 2] = 0.2 x[n] + 0.4 x[n 1] + 0.2 x[n 2]

Consideringtheimpulseresponseofsystemgiveninexample&thistask,whatdoyouobserve?State
yourfindings.

12.4 FREQUENCY RESPONSE OF SYSTEM


Giventhecoefficientsofafilter,frequencyresponsecanbedeterminedforaparticularrangeof
frequenciesbyusingFreqz.Thesyntaxis:

H = freqz (b, a, w)

Wherebandaarethefiltercoefficientsandwistherangeoffrequenciesforwhichthefrequency
responseisdesiredtobedetermined.Toplotthemagnitudeandphaseoffrequencyresponse,useabs
andanglerespectively.

ExampleASimpleLowpassFilter
clc;clearall;closeall

b=[121];
a=1;
w=3*pi:1/100:3*pi;

H=freqz(b,a,w);

figure;subplot(3,1,1);
plot(w,abs(H));
title('MagnitudeofFrequencyResponseoffilterwithcoefficientsb_k={1,2,1}');
xlabel('\omega');ylabel('H(\omega)');grid;

subplot(3,1,2);
plot(w,abs(H));

title('Zoomedviewoftheabovegraphfrom\pito\pi');
xlabel('\omega');ylabel('H(\omega)');
axis([pipimin(H)max(H)]);grid;

subplot(3,1,3);
plot(w,angle(H));
title('PhaseofFrequencyResponseoffilterwithcoefficientsb_k={1,2,1}');
xlabel('\omega');ylabel('H(\omega)');grid;

---------------------------TASK 4---------------------------Plot the magnitude and phase of the frequency response of an FIR filter with coefficients
b={12421}.Determinethetypeoffilter.

---------------------------TASK 5---------------------------Acausalthreepointrunningaveragefilterisgivenby

y[n] = (x[n] + x[n 1] + x[n 2]) 3

Findthefrequencyresponseofthisfilterfrom3to+3.

Note:
Freqzcommandcanalsobeusedas:

[ H W ] = freqz (b, a, n);

WhereHcontainsthefrequencyresponse,Wcontainsthefrequenciesbetween0wheretheresponse
iscalculated,andnisthenumberofpointsatwhichtodeterminethefrequencyresponse.Ifnis
missing,thisvaluedefaultsto512.

Example:AsimpleLowpassfilter
clc
clearall
closeall

b=[12321];
a=[1];

[HW]=freqz(b,a);

figure;
subplot(2,1,1);
plot(W,abs(H),'linewidth',1.5);
title('MagnitudeofFrequencyResponseoffilterwithcoefficientsb_k={1,2,3,2,1}');
xlabel('\omega>');
ylabel('H(\omega)>');
grid;

subplot(2,1,2);
plot(W,angle(H),'g','linewidth',1.5);
title('PhaseofFrequencyResponseoffilterwithcoefficientsb_k={1,2,3,2,1}');
xlabel('\omega>');
ylabel('H(\omega)>');
grid;

---------------------------TASK 6---------------------------Using the abovementioned syntax, determine the frequency response of a filter with filter
coefficients{1,3,1}.Take1024points.

12.5 FILTER DESIGNING USING FIR1


Fir1isusedtodesignfiltercoefficients.Thesyntaxofthiscommandis:

b = fir1( N , c);

Wherebcontainsthefiltercoefficientsreturnedbythiscommand,Nistheorderoffilter,andwcis
thecutofffrequencynormalizedbetween01where1refersto.Thenumberofcoefficientscreated
is one more than the order of filter. By default, a lowpass filter is created. A highpass filter can be
createdusingtheargumenthighattheendintheabovecommand.Abandpassfiltercanbecreated
using [Wa Wb] instead of Wc where frequencies between Wa and Wb are allowed to pass. If such a
vectorisspecifiedinsteadofWc,abandpassfilteriscreatedbydefault.Abandstopfiltercanbecreated
byusingtheargumentstopintheaforementionedcommand.

b = fir1( N , c)

// creates coefficients of lowpass filter

b = fir1( N , c, ' high' )

// creates coefficients of highpass filter

b = fir1( N , c,[Wa Wb])

// creates coefficients of bandpass filter

b = fir1( N , c,[Wa Wb])

// creates
coefficients of bandstop filter

Afterthecoefficientsareobtained,freqzcommandcanbeusedtodeterminethefrequencyresponse.
Note:ForHighpassandbandstopfilters,Nmustbeeven.ElseMatlabwillincreasetheorderitselfby1.

Example:DesigningHighpassfilter
%HighPassfilter
clear,closeall,clc

w=pi:1/100:pi;
b=fir1(4,1/3,'high')
H=freqz(b,1,w);

figure;subplot(2,1,1);
plot(w/pi,abs(H));
title('Highpassfilterwithcutofffrequencyofw_c=\pi/3');
xlabel('Normalized\omega=x\pi');ylabel('H(\omega)');
grid;

b=fir1(1000,1/3,'high');
H=freqz(b,1,w);;

subplot(2,1,2);
plot(w/pi,abs(H));
title('Highpassfilterwithcutofffrequencyofw_c=\pi/3');
xlabel('Normalized\omega=x\pi');ylabel('H(\omega)');
grid;

---------------------------TASK 7---------------------------Designalowpassfilterwith7coefficientsandcutofffrequencyof/2.

---------------------------TASK 8---------------------------Designabandpassfilterwhichallowsonlythefrequenciesbetween/6and2/3topassand
blockstherestoffrequencies.Designitfororder10and1000.

---------------------------TASK 9---------------------------Designabandstopfilterwhichstopsthefrequenciesbetween/3and/2andallowstherest
offrequenciestopass.Designitfororder10and1000.

---------------------------TASK 10--------------------------MagnitudeofanidealhighpassfiltercanbeextractedfromanideallowpassfilterasHhp=1Hlp
and viceversa. Design a highpass filter with order 1000 and Wc=/4. Using the highpass

filtersfrequencyresponse,determinethefrequencyresponseofalowpassfilterwithWc=/4.
(Hint:usethevalues1abs(H)).

---------------------------TASK 11--------------------------MagnitudeofanidealbandstopfiltercanbeextractedfromabandpassfilterasHbs=1Hbpand
viceversa.Createabandpassfilterwithorder1000whichallowsonlythefrequenciesbetween
/6 and 2/3 to pass and blocks the rest of frequencies. Create a bandstop filter from this
bandpassfilter.

---------------------------TASK 12--------------------------(a)Designabandpassfilteroforder15thatallowsonlyabandoffrequenciesbetween/6
and /3 and suppresses all the other frequencies. Determine the gain of this system in the
range3to+3.
(b)Designthisbandpassfilterforanapproximationtoidealfiltering.

---------------------------TASK 13--------------------------Writeaprogramtofindtheimpulseresponseofa10pointrunningaveragefilter.

---------------------------TASK 14--------------------------Designahighpassfilterwith10coefficients.Thecutofffrequencyofthisfiltershouldbe/3.
Determinethefrequencyresponseofthefilterfrom4to+4.Plotthemagnitudeandphase
responseofthisfilter.

Potrebbero piacerti anche