EE 361 Introduction to DSP Laboratory...

55
EE 361 Introduction to DSP Laboratory Handout Hüseyin Büyükeşmeli, Anıl Özdemirli and Cem Ünsalan 12.09.2014

Transcript of EE 361 Introduction to DSP Laboratory...

EE 361 Introduction to DSP

Laboratory Handout

Hüseyin Büyükeşmeli, Anıl Özdemirli and

Cem Ünsalan

12.09.2014

2

This handout aims to help EE 361 laboratory sessions.

3

Table of Contents

BEFORE GETTING STARTED .............................................................................................................. 5

1. INTRODUCTION TO MATLAB ........................................................................................................ 6

1.1 STARTUP ......................................................................................................................................... 6

1.2 COMMAND WINDOW ........................................................................................................................ 6

1.3 COMMAND HISTORY.......................................................................................................................... 7

1.4 WORKSPACE BROWSER ...................................................................................................................... 7

1.5 VARIABLE EDITOR .............................................................................................................................. 8

1.6 EDITOR ........................................................................................................................................... 9

1.7 GETTING HELP .................................................................................................................................. 9

1.8 WRITING AN M FILE .......................................................................................................................... 9

1.9 SETTING THE MATLAB SEARCH PATH AND CURRENT FOLDER ................................................................. 10

1.10 VARIABLES ................................................................................................................................... 11

1.11 OPERATORS ................................................................................................................................. 11

1.12 FUNCTIONS .................................................................................................................................. 12

1.13 VECTORS AND MATRICES ................................................................................................................ 12

1.14 LOOPS ........................................................................................................................................ 13

1.14.1 The for Loop ...................................................................................................................... 13

1.14.2 The while Loop .................................................................................................................. 14

1.15 THE IF STATEMENT ........................................................................................................................ 14

1.16 PLOTS ......................................................................................................................................... 15

1.17 USER DEFINED FUNCTION ............................................................................................................... 17

1.18 SIMULINK .................................................................................................................................... 18

1.19 EXTRAS ....................................................................................................................................... 21

1.19.1 Who and Whos Commands .............................................................................................. 21

1.19.2 Importing Audio Signals into MATLAB Workspace ........................................................... 21

1.19.3 Importing Images into MATLAB Workspace ..................................................................... 23

1.19.4 Importing a Multimedia File to Simulink .......................................................................... 25

1.19.5 Some Useful Functions and Commands ............................................................................ 26

1.20 HOMEWORK 1.............................................................................................................................. 28

1.21 HOMEWORK 2.............................................................................................................................. 29

2. SINUSOIDS ................................................................................................................................. 31

2.1 PRELIMINARY WORK........................................................................................................................ 31

2.2 GENERATING SINUSOIDS IN MATLAB ................................................................................................. 32

2.3 EXPERIMENTAL PROCEDURE .............................................................................................................. 32

2.3 REPORT ......................................................................................................................................... 32

3. FOURIER SERIES EXPANSION (DEMO) ......................................................................................... 33

3.1 PRELIMINARY WORK........................................................................................................................ 33

3.2 FOURIER SERIES EXPANSION .............................................................................................................. 33

3.3 PROCEDURE ................................................................................................................................... 36

3.4 REPORT ......................................................................................................................................... 36

4. FUNCTIONS UNDER MATLAB (DEMO) ........................................................................................ 37

4.1 M-FILE SCRIPTS .............................................................................................................................. 37

4.2 M-FILE FUNCTIONS ......................................................................................................................... 38

4

4.3 PROCEDURE ................................................................................................................................... 40

5. DIGITAL SIGNALS: AUDIO AND IMAGE........................................................................................ 41

5.1 PRELIMINARY WORK........................................................................................................................ 41

5.2 EXPERIMENTAL PROCEDURE .............................................................................................................. 43

5.2.1 Reading an Audio Signal in MATLAB .................................................................................. 43

5.2.2 Reading an Image in MATLAB ............................................................................................ 43

5.3 REPORT ......................................................................................................................................... 43

6. DISCRETE CONVOLUTION ........................................................................................................... 44

6.1 PRELIMINARY WORK........................................................................................................................ 44

6.2 EXPERIMENTAL PROCEDURE .............................................................................................................. 45

6.3 REPORT ......................................................................................................................................... 46

7. Z-TRANSFORM ........................................................................................................................... 47

7.1 PRELIMINARY WORK........................................................................................................................ 47

7.2 Z-TRANSFORM ............................................................................................................................... 47

7.3 EXPERIMENTAL PROCEDURE .............................................................................................................. 48

7.3 REPORT ......................................................................................................................................... 49

8. FDATOOL (DEMO) ...................................................................................................................... 50

9. DISCRETE-TIME FREQUENCY RESPONSE ..................................................................................... 52

9.1 PRELIMINARY WORK........................................................................................................................ 52

9.2 EXPERIMENTAL PROCEDURE .............................................................................................................. 52

9.2.1 Frequency Response of FIR and IIR Filters........................................................................... 52

9.2.2 Frequency Response in Z-Domain ....................................................................................... 52

9.3 REPORT ......................................................................................................................................... 53

10. FOURIER TRANSFORM .............................................................................................................. 54

10.1 PRELIMINARY WORK...................................................................................................................... 54

10.2 DISCRETE FOURIER TRANSFORM UNDER MATLAB .............................................................................. 54

10.3 EXPERIMENTAL PROCEDURE ............................................................................................................ 54

10.3 REPORT ....................................................................................................................................... 55

5

Before Getting Started

There are couples of things that you should keep in mind before getting started;

You can only achieve good skills in Matlab by practicing as much as you can. Just like in any other programming language.

Matlab can be considered as a gigantic calculator. In order to solve a question or a problem you have to know; how to solve the problem. Matlab does only the calculations for you. It does not suggest or show any solving method for a given problem. If you want to be successful in this lab, a well understanding of the concepts that has been covered in course is a prerequisite. Knowing how to use Matlab without knowing how to solve the problem is like knowing how to use a pencil without knowing reading-writing.

Digging more into your problem is a big part of your learning process. Please don’t be lazy about debugging your code when you encountered with an error or wrong results.

Please don’t forget; thousands of students had been in your situation and walked the way that you are in now. There is a great knowledge interchange platform under your hand: Internet! Googling should be the first thing that you do when you encountered an error.

It is impossible to solve your all problems by yourself. Please don’t hesitate to ask questions.

6

1. Introduction to MATLAB

We will use MATLAB throughout the following chapters. Therefore, understanding this chapter is important.

1.1 Startup When MATLAB starts, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with it. The following illustration shows the default desktop. You can customize this arrangement to suit your needs.

1.2 Command Window Use the Command Window to enter variables and run MATLAB functions and scripts. MATLAB displays the result in the command window.

7

You can press the up arrow key ↑ to recall a statement you previously typed. You can edit this statement and then press Enter to run it again.

1.3 Command History Statements you enter in the Command Window are logged with a timestamp in the Command History. From this window, you can view and search for previously run statements. You can also create a file from the selected statements.

1.4 Workspace Browser The MATLAB workspace consists of the set of variables built during a MATLAB session and stored in the memory. You can add variables to the workspace by using functions, running function and script files, or loading saved workspaces. To view the workspace and information about each variable, use the Workspace browser, or use the who or whos commands.

8

To delete variables from the workspace, select the variables, and then select Edit > Delete. Alternatively, you can use the clearvars or clear commands. The workspace is not saved after you end the MATLAB session. To save the workspace to a file that can be read during a later MATLAB session, select File > Save, or use the save command. Saving preserves the workspace in a binary file called a MAT-file, having an .mat extension. You can use options to save in different formats. To read a MAT-file, select File > Import Data, or use the load command.

1.5 Variable Editor Double-click a variable in the Workspace browser, or use openvar variable_name, to see it in the Variable Editor. Use the Variable Editor to view and edit a variable in the workspace.

9

1.6 Editor Use the Editor to create and debug programs (you have written for running multiple MATLAB functions or commands). The Editor provides a graphical user interface for editing and debugging the MATLAB code. To create or edit a file select File > New or File > Open or use the edit command.

1.7 Getting Help MATLAB provides extensive documentation, in both printable and HTML format, to help you learn about and use all of its features. To use it, type help command_name for more information on any given command. To view the online documentation, select Help > Product Help in MATLAB. Online help appears in the Help browser, providing task-oriented and reference information about MATLAB features.

1.8 Writing an M file There are two types of m-files as: script and function. Script files do not take any input arguments or return any output arguments. Only the commands or functions in them are executed sequentially. On the other hand, function files may take input arguments or return output arguments. Below is an example of a small script file: % Script file firstgraph.

x = pi/100:pi/100:10*pi;

10

y = sin(x)./x;

plot(x,y)

grid

To generate an m-file, click on File. Select New and click on M-File from the pull-down menu. You will be directed to the MATLAB Editor/Debugger screen. Here you can type your code in an m-file or make changes on an existing m-file. Once you are done with typing, click on File in the MATLAB Editor/Debugger screen and select Save As… . Choose a name for your file, (e.g. firstgraph.m) and click on Save. Make sure that your file is saved in the directory that is in MATLAB's search path.

1.9 Setting the MATLAB Search Path and Current Folder MATLAB uses a search path to locate M-files and other related files (organized in directories on your file system). By default, the files supplied with MATLAB and MathWorks products are included in the search path. Any file you want to run or debug in MATLAB must reside in a directory that is on the search path, or in the current directory. If you create any MATLAB related files, add the directories containing the files to the MATLAB search path.

If you try to run or debug a file that is in a directory not on the path, the action fails. When this occurs in the Command Window, MATLAB gives an error. In the Editor/Debugger, a dialog box prompts you to:

Change Directory — Makes the directory containing the file you want to run become the current directory

Add to Path — Adds the directory containing the file to the top of the search path

Use the Set Path dialog box to view and modify the MATLAB search path. Equivalent functions are documented for each feature of the Set Path dialog box. Select Set Path from the File menu, or type pathtool at the Command Window prompt to open the Set Path dialog box.

11

The principal Desktop tool for working with files and folders is the Current Folder browser. The Current Folder browser displays details about files in your current folder and within the hierarchy of the folders it contains. The Current Folder browser

always displays your current folder, as well as its subfolders.

Let's you access operating system file management features from within MATLAB.

is similar to file browsers provided with operating systems, but also includes features unique to MATLAB. For example, you can add folders to the search path from the Current Folder browser.

Before working with MATLAB, specify a suitable current folder in which you will keep your work.

1.10 Variables MATLAB does not require any type declarations or dimension statements for variables. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate memory space for it. If the variable already exists, MATLAB changes its contents and, if necessary, allocates new memory space. For example, ">>num_students = 25;" generates a new variable with value 25.

1.11 Operators MATLAB use below expressions and arithmetic operators. + Addition - Subtraction * Multiplication / Division \ Left division ^ Power ' Complex conjugate transpose

12

( ) Specify evaluation order

1.12 Functions MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. For a list of the elementary mathematical functions, type >> help elfun Commonly used constants such as pi, and i or j (for the square root of -1) are also predefined in MATLAB. For example >> sin(pi/4)

ans =

0.7071

>> sqrt(-1)

ans =

0 + 1.0000i

>> (2+3i)*(3+4i)

ans =

-6.0000 +17.0000i

1.13 Vectors and Matrices Almost all MATLAB's basic commands can directly be used for vector operations. A vector is defined by placing a sequence of numbers within square braces as >> v = [3 1];

v =

3 1

This creates a row vector which has the label 'v'. The first entry in the vector is 3 and the second entry is 1. Note that MATLAB printed out a copy of the vector after you hit the enter key. If you do not want to print out the result, put a semi-colon at the end of the line as >> v = [3 1];

>>

If you want to create a column vector you need to take the transpose of the row vector. The transpose is defined using an apostrophe ( ' ): >> v = [3 1 7 -21 5]'

v =

3

1

7

-21

5

13

To define a vector that starts with 2 and ends in 4 with steps of 0.25, use the following code >> v = [2 : 0.25 : 4]

v =

Columns 1 through 7

2.0000 2.2500 2.5000 2.7500 3.0000 3.2500

3.5000

Columns 8 through 9

3.7500 4.0000

You can view the individual entries in this vector. For example, to view the first entry just type >> v(1)

ans =

2

Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row vectors. An example is below. >> A = [ 1 2 3; 3 4 5; 6 7 8]

A =

1 2 3

3 4 5

6 7 8

You can also define the matrix like a row of column vectors as below. >> B = [ [1 2 3]' [2 4 7]' [3 5 8]']

B =

1 2 3

2 4 5

3 7 8

1.14 Loops You can benefit from the for and while loops under MATLAB. We will explore them next.

1.14.1 The for Loop In the for loop, you must define where to start and stop. Basically, give a vector in the "for" statement and MATLAB will loop through for each value in the vector. In the below example, the j variable will have three values in the loop. >> for j=1:3

j

end

This code creates the following output.

j =

1

j =

2

14

j =

3

>>

1.14.2 The while Loop The while loop is similar to the for loop. Unlike it, the iteration number is set based on a condition. Below is a simple example. n = 1

while (n < 3)

n = n+1

end

This code creates the following output. n =

1

n =

2

n =

3

1.15 The If Statement The structure for an "if" statement is as follows. if (condition statement) (MATLAB commands) end In using the if statement, more complicated structures are also possible. Below is an example. if (condition statement) (MATLAB commands) elseif (condition statement) (MATLAB commands) elseif (condition statement) (MATLAB commands) . . . else (MATLAB commands) end The conditions should be Boolean statements. Also, standard comparisons can be made. Valid comparisons include "<" (less than), ">" (greater than), "<=" (less than or equal), ">=" (greater than or equal), "==" (equal - this is two equal signs with no spaces between them), and "˜=" (not equal). For example, the following code will set the variable j to -1. a = 2;

15

b = 3;

if (a<b)

j = -1;

end

Additional statements can be added for more refined decision making. The following code sets the variable j to 2. a = 4;

b = 3;

if (a<b)

j = -1;

elseif (a>b)

j = 2;

end

1.16 Plots

One of the most important commands in MATLAB is the plot. To use the plot function in MATLAB, you should first make sure that the matrices/vectors you are trying to use are of equal dimensions. For example, if you wanted to plot vector X = [3 9 27] over time, your vector for time would also need to be a 1x3 vector (i.e. t = [1 2 3]). Syntax: plot(x,y)

This command will plot the elements of vector y with respect to vector x on a figure. Each time the plot command is issued, the current figure will be erased. We will discuss how to plot two or more plots on the same figure below. If we want to plot a simple, linear equation like y=3x, we can create an m-file with the following code. x = 0:0.1:100;

y = 3*x;

plot(x,y)

This m file will generate the following plot.

16

Additional Properties: You can put a title to your graph by writing the following command: title('write your title here')

You may want to label x and y axes with following command:

xlabel('name of x axis')

ylabel('name of y axis')

Also you can define range of x and y coordinates that will be plotted.

xlim([XMIN XMAX])

ylim([YMIN YMAX])

You can enable or disable grids with following command.

grid on

grid off

Format can be adjusted according to followings;

Color can be any of 'b' blue, 'g' green, 'r' red, 'c' cyan, 'm' magenta, 'y' yellow, 'k' black.

Shape can be any of 'o' circle, 'x' x-mark, '+' plus, '*' star, 's' square, 'd' diamond, 'v' triangle (down), '^' triangle (up), '<' triangle (left), '>' triangle (right), 'p' pentagram, 'h' hexagram.

Linespec can be any of '-' solid, ':' dotted, '-.'dashdot, '--' dashed, (non) no line.

Color can be adjusted typing the name of color.

plot(x,y,'blue')

If you want to use more than format specs at once you should combine at one instance. For example:

plot(x,y,'gs-')

This command will produce a green solid line with squares at every data point or,

plot(x,y,'gs-')

This command will produce a set of red “+” symbols at every data point. In order to plot more than one plot on same graph hold on command can be used. Enter the hold on command after plotting one graph and use plot command for second graph same way the first one. One thing to keep in mind when using the plot command is that the vectors x and y must be of the same length.

17

Subplot command allows plotting more than one graphics in same window. subplot(3,2,1) ; plot(x1,y1)

subplot(3,2,2) ; plot(x2,y2)

.

.

.

subplot(3,2,6) ; plot(x6,y6)

The first argument in the parenthesis declares the number of rows, the second argument declares the number of columns and the third argument identifies the number of plot which will be plotted. Numbering of plots is row wise. With the plot command after the semicolon; any signal can be plotted to the selected subplot.

In order to plot more than one plot on same graph hold on command can be used. Enter the hold on command after plotting one graph and use plot command for second graph same way the first one.

1.17 User Defined Function MATLAB allows creating user defined functions. In order to declare a function, the function

command must be type into the first executable line of an M-file with its inputs and

outputs. The commands in function block have to be executable in MATLAB command line.

In this block, any MATLAB function or any other user defined function can be used and also

special commands such as if, for, while are available too. All variables that are defined in

function block are local. In order to call the function, M-file has to be saved in current

directory of MATLAB and its name must be same with function. The example of a function

which calculates mean and standard deviation of a vector is given below.

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

18

Example:

function [mean,stdev] = stat(x)

n = length(x);

mean = sum(x)/n;

stdev = sqrt(sum((x-mean).^2/n));

end

1.18 Simulink Simulink is an environment for simulation and Model-Based Design for dynamic and embedded systems. It provides an interactive graphical environment and a customizable set of block libraries that let you design, simulate, implement, and test a variety of time-varying systems, including communications, controls, signal processing, video processing, and image processing. To open the Simulink Library Browser, first you need the MATLAB running. Start MATLAB, and then in the MATLAB Command Window, enter ‘simulink’. Then, the Simulink Library Browser opens. You can also open the Simulink Library Browser by

• clicking the Simulink icon on the MATLAB toolbar. • clicking the Start button on the MATLAB task bar, pointing to Simulink, and then

selecting the Library Browser.

The Simulink Library Browser displays the block libraries installed on your computer. You can start building models by copying blocks from a library into a Simulink editor window.

19

To create a new Simulink model;

• from the Simulink Library Browser menu, select File > New > Model. An empty model opens in the Simulink editor window.

• select File > Save. • in the Save As dialog box, enter a name for your model, and then click Save.

Simulink saves your model with the file extension .mdl .

The Simulink editor window contains a block diagram of your model. You can build models in the editor by dragging blocks from the Simulink Library Browser window, arranging the blocks logically, connecting the blocks with signal lines, and then setting the parameters for each block. The Simulink editor window also allows you to:

• set configuration parameters for the model, including the start and stop time, type of solver to use, and data import/export settings.

20

• start and stop a simulation of the model. • save the model. • print the block diagram.

Before you simulate a model, you have to set simulation options. Specify options, such as the stop time and solver, using the Configuration Parameters dialog box. In the Simulink editor window, select Simulation > Configuration Parameters. The Configuration Parameters dialog box opens to the Solver pane.

After entering your configuration parameters, you are ready to simulate the simple model and visualize the simulation results. In the Simulink editor window, select Simulation > Start from the menu. The simulation runs, and then stops when it reaches the stop time specified in the Configuration Parameters dialog box. Alternatively, you can control a simulation by clicking the Start simulation button and Stop simulation button on the editor window toolbar.

21

1.19 Extras In this section, you can find some information about functions blocks etc. that may help you

in future chapters.

1.19.1 Who and Whos Commands The who command displays the variables which are defined currently in workspace. The

whos command can be used for more information about variables. This command prints

the all variables and their detailed information on command window.

>> who

Your variables are:

a ans b

>> whos

Name Size Bytes Class Attributes

a 1x1 8 double

ans 1x1000 8000 double

b 500x465 1860000 double

1.19.2 Importing Audio Signals into MATLAB Workspace In this session, WAV encoded audio signals will be investigated. Firstly, a good

understanding of creation of digital audio signal is necessary. The sound to be recorded is

converted to analog electrical signal by microphone. By ADC and some other digital blocks,

the signal is sampled, quantized and saved into a memory unit. For listening, this saved

signal passes through same path in the reverse direction. Finally, an analog signal for the

speaker is obtained.

The number of samples taken in one second is defined as Sampling Frequency (Fs). With

that information, one can analyze that 1/Fs would give the time between two samples.

22

Therefore, if the sample number is multiplied by Fs, the result will be equal to the duration

of the audio signal.

In computers, the conversion between analog and digital signals is performed by sound

cards. Most of the time, we will deal with digitalized signals during the laboratory sessions.

When you import a WAV file into MATLAB, the audio signal will be represented as an array.

Each element of the array corresponds to one sample of the audio signal. (We may note

that MP3 format is different from WAV format. MP3 uses a compression algorithm to

reduce file size but WAV formatted files do not have any compression process. Therefore

there is a huge file size difference between WAW and MP3 formatted files.)

Difference Between Mono and Stereo

Most of the audio devices have two speakers such as headphones, laptop speakers, TV

speakers etc. In general, the signals, driving these speakers are slightly different from each

other for better listening experience. This is called stereo. If the signals are same for both

speakers, we call this signal as mono. You may notice that in most songs; basses and trebles

are emphasized in different speakers. This is done by recording the same song with

differently placed two separate microphones. This is how to create a stereo signal. (There

are some algorithms that derive a stereo signal from a mono signal but this is not our

concern right now.)

When you import an audio signal into MATLAB array, its dimension will be different if the

signal is stereo or mono. As mentioned earlier, there two channels for each speaker

meaning that, there have to be two different data sets for each channel in stereo signals.

Therefore, the array size will be Mx2 for stereo audio signals. First column of the array

corresponds to the signal that drives the left speaker and second column corresponds to

the signal for right speaker. For mono signals, the second column is unnecessary since both

speakers are driven with same data. Therefore the array size will be Mx1 for mono signals.

M corresponds to the length of the vector which may differ from signal to signal by its

sampling rate and duration.

The following example shows how to import an audio signal and how you can perform

various operations on it.

[audio,fs]=wavread('name_of_wav_file.wav'); % transfers .wav file into array

“audio” and sampling frequency to “fs”

With wavread function, you can import any WAVE formatted audio signal. As you can see, the signal data is assigned to variable audio. For proper playback and other filtering operations, we need to know its sampling rate. As you can see, value of sampling rate of the audio signal is assigned to variable fs. It is important to note that, wavread function does not provide any duration or time data. The user has to calculate these values by using sampling frequency. x = audio ( : , 1 ); % assign left channel data to x

y = audio ( : , 2 ); % assign right channel data to y

23

The commands given above, show how to assign right and left channel data to different variables. The reader is invited to pay attention to usage of colon sign (:). This usage is very handful and commonly used. First command implies that whole elements of first column of array audio will be assigned to variable x. Second command assigns second column to y. Assume that the imported signal is stereo; the variable audio’s size will be Mx2. If the signal is mono then audio’s size will be Mx1. If you use second command for mono signal, you will get an error message since second column of audio array does not exist. time=(1/fs)*length(x); % Calculates the duration of .wav file

t=linspace(0,time,length(x)); % Interpolates ‘t’ from 0 to ‘time’ so creates

a time vector

plot (t,audio)

As mentioned above, wavread function does not provide any information about duration or time vector. The user should compute the duration and time vector by using sampling rate. First command given above calculates the duration of audio signal by multiplying the duration between two sample and number of samples. In order to plot that audio signal for observing the variation with time, a time vector is necessary. Second command serves for this purpose. It creates an array, from zero to the duration of audio signal, while having the same number of elements with audio. With plot function the audio signal as a function of time can be observed. sound(audio,fs) % Plays the array audio with a sampling rate fs

As a last topic in this chapter, the command sound is used to listen the audio signal. It is

important to remember to specify fs for this function. Its default value is 8000. If your

sampling rate is different than this value it will cause to hear weird sounds. The reader is

invited to try playing the audio signal for different sampling rates for observing its effect.

1.19.3 Importing Images into MATLAB Workspace In this section, image files will be also covered. Images consist of pixels. The number of pixel

determines the resolution of the image and its size. When you import an image file into

MATLAB, the image data is kept as a matrix. Every element of the matrix carries the

information about one pixel of the image file. Different from audio signals, no time vector is

necessary, since no time dependent variable for image files. But, images are two

dimensional files. We have to keep in mind that while manipulating the image files.

Gray Scaled Images

For gray scaled images, tones between black and white are discretized by the number of

bits that we use to define our image file. In this laboratory we will use 8 bits to define

colors, meaning that, a gray scaled image can have 255 different tones between black and

white. The image given below consists of examples of gray tones.

24

The figure given above demonstrates image and its corresponding matrix in MATLAB. Image

has 255 pixels in vertical axis and 128 pixels in horizontal axis. Therefore, matrix size will be

255x128. Value of each element of the matrix tells which tone of gray will be for that pixel.

RGB Colored Images

We can obtain any color with combination of red, green blue. Based on this idea RGB color

model is built which is commonly used color model for today. (There are also CMYK and

YCbCr color models, for detailed information, please visit http://bit.ly/1aTN2ft and

http://bit.ly/1aTN8DU .) For colored images, the information of tones of red, green and

blue is necessary. In gray scale images, there is only one is needed, since there is only one

single color tone. Likewise, in RGB colored images, we need three separate matrices to hold

three colors tone’s information.

Illustration given below shows the examples of RGB color matrices. Image has 210 pixel in

vertical axis and 128 pixels in horizontal axis. Therefore RED, GREEN and BLUE matrices are

210 by 128 matrices. However when you import this image to MATLAB, all R-G-B matrices

are kept in a single variable. Therefore size of the variable will be 210x128x3.

255

255

:

200

200

:

150

150

:

100

100

:

0

0

:

255...

255...

:

200...

200...

:

150...

150...

:

100...

100...

:

0 ...

0 ...

:

237

:

255

:

255

:

34

:

0

:

63

:

163

:

...

...

...

...

...

...

...

28

:

127

:

242

:

177

:

162

:

72

:

73

:

...

...

...

...

...

...

...

36

:

39

:

0

:

76

:

232

:

204

:

164

:

...

...

...

...

...

...

...

RED GREEN BLUE

25

Example:

img=imread('peppers.png');

gray=rgb2gray(img);

imshow(gray);

The code given above imports image file named peppers.png into MATLAB and assigns it to

variable img. You can observe the variable size as MxNx3 because it is RGB colored. M is the

number of rows and N is the number of columns. Second command converts the image

RGB colored to grayscale and assigns it to variable gray. You can observe that variable

gray’s size will be MxN. Third command displays the gray scaled image on screen.

r=img(:,:,1);

g=img(:,:,2);

b=img(:,:,3);

As shown above, we can assign red, green, blue matrices to separate variables r, g and b

respectively. By separating matrices we can change the intensities of the colors separately.

Following code doubles the red color intensity, increases the green color density by 30 and

decreases the blue color intensity by 50%. Finally it combines three matrices in a single

variable by using cat function.

r=2*r;

g=g+30;

b=0.5*b;

img_changed=cat(3,r,g,b);

Original and modified images are presented below.

1.19.4 Importing a Multimedia File to Simulink In Simulink library, there is a specific block to read multimedia files named as From Multimedia File. Any sound or image data supported by MATLAB can be imported into Simulink model by using this block. Loaded audio file can be listened with the block named To Audio Device. If the loaded multimedia file is image or video, the Video Viewer block should be used.

Original Modified

26

1.19.5 Some Useful Functions and Commands + : Addition or unary plus. A+B adds A and B. A and B must have the same size, unless one is

a scalar. A scalar can be added to a matrix of any size.

- : Subtraction or unary minus. A-B subtracts B from A. A and B must have the same size,

unless one is a scalar. A scalar can be subtracted from a matrix of any size.

* : Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. For

nonscalar A and B, the number of columns of A must equal the number of rows of B. A

scalar can multiply a matrix of any size.

.* : Array multiplication. A.*B is the element-by-element product of the arrays A and B. A

and B must have the same size, unless one of them is a scalar.

/ : Slash or matrix right division. B/A is roughly the same as B*inv(A).

./ : Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the

same size, unless one of them is a scalar.

^ : Matrix power. X^p is X to the power p, if p is a scalar.

.^ : Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must

have the same size, unless one of them is a scalar.

27

size: Returns the two-element row vector containing the number of rows and columns.

length: Returns the number of elements along the largest dimension of an array.

max: Returns the largest element of an array.

min: Returns the smallest element of an array.

sum: Returns sums along different dimensions of an array.

mean: Returns the mean values of the elements along different dimensions of an array.

abs: Returns absolute value and complex magnitude.

exp: returns the exponential, ex.

28

1.20 Homework 1 1) Create an array with randomly-selected 1000 elements between -50 and 50.

Find the minimum number in the array. Calculate its absolute value. Calculate modulus of absolute value after divided by 7 and equate this value to a variable named “number1” Find the maximum number of the array. Take its absolute value. Take modulus of absolute value after divided by 13 and equate this value to a variable named “number2” Compare “number1” and “number2”. Create a variable “result” such that; If number1 is greater than or equal to number2, result is half of the length of the array. If number1 is less than number2, result is 2 times of the length of the array. Write the corresponding code for the question. (May the force be with you...)

2) Create an array with randomly-selected 1000 elements between -50 and 50. Compare each element of the array such that; If the element is greater than 30; change it as 30. If the element is less than -30; change it as -30. If the element is between -30 and 30; the element keeps its value. Write the corresponding code for the question.

3)

Define a 1001-by-8 matrix, named “A”, whose elements selected randomly.

Define an 8-by-1001 matrix, named “B”, whose elements selected randomly.

Define a variable “C” as the multiplication of matrices “A” and “B”.

Define a variable “D” as the mean value of the first column of “C”.

Write the necessary code in script format. 4) Assume that you have a data set of voltage and current values of a circuit element.

Voltage and current values are stored in separate arrays v and i. These values are measured with respect to time data created in section a. a) Generate a time vector t that starts from 0 to 10 sec with 0.01 sec increments. Shift

this vector +2 and -2 sec. b) Create a new variable named x, and equate it to the size of time vector, defined in

section a by using the size function. c) Create voltage and current vectors with rand function that are same sized with the

time vector defined in section a. d) Plot time versus voltage and time versus current graphs. e) Define a function that takes the voltage, and current as input and gives the

instantaneous power as output. f) Calculate and the instantaneous power. g) Calculate average power.

29

1.21 Homework 2

1) Build the Simulink block as seen in figure. Change the value of constant with the last digit of your student number. Observe the output by double-clicking the scope after running the simulation.

2) Build the Simulink block as seen in figure. Change the value of gain with the last digit of your student number. Observe the output by double-clicking the scope after running the simulation.

3) Construct a Simulink model that reads an audio signal. Pass it through Slider Gain block. Change slider position and listen the result.

4) Read a stereo audio (.wav) file such that its length is greater than 10 seconds. a) Print its size on command window. Listen it by the appropriate command. b) What is the sampling frequency (Fs)? c) Calculate the duration of the audio data and create the time vector. d) Plot the audio signal. Pay attention to its dimensions. e) Find its maximum and minimum values. f) Determine a threshold value between 0 and 1 and repeat Homework 1 Question 2

for audio data array. Plot and listen the result. g) Assign the first 10 seconds part of the audio data to new array.

5) “Pop art is an art movement that emerged in the mid-1950s in Britain and in the

late 1950s in the United States. Pop art presented a challenge to traditions of

fine art by including imagery from popular culture such as advertising, news, etc.

In pop art, material is sometimes visually removed from its known context,

isolated, and/or combined with unrelated material.” (en.wikipedia.org/wiki/Pop_art) We expect from you to create a simple Pop Art example.

Read the RGB colored image named “marlyn.jpg”.

30

As mentioned in the section 1.19.3, a colored image consists of MxNx3 matrix

where M is height and N is width of the image. The number “3” comes from the

number of base colors, Red, Green and Blue. Modify your image so that, in each

new image, change the sequence of the R-G-B layers and store as a new variable.

(R-G-B , R-B-G, G-B-R, etc.)

Combine 6 combinations of modified images and append as a single image and

print on screen. In the end, your image should be seen similar to figure below.

6) Write a question that needs the usage of following;

MATLAB functions such as; min, max, abs, length, size etc…

Statements such as; if, for etc… Question may require importing audio or image files. Simulink blocks may also be

involved. Provide its solution. Your question should have a scenario. It has to be clearly understandable. If you need

to use additional function that are not mentioned in handout a hint has to be given. Owner of the best question with correct solution will get double credit from

homework. Bonus (25%): Run the GUI Layout Editor by typing the guide in command line. Make a few changes in offered templates. Generate its m-file. Bonus(25%): With the mcc command (you should learn its usage), generate an executable file (.exe) of your GUI or any other function.

31

2. Sinusoids

In this chapter, we will examine the characteristics of sinusoids using MATLAB. We will use the sin command to generate the sinusoids and the plot command to plot the generated signals.

2.1 Preliminary Work

Build the circuits given below. Create a new Simulink Model and build the circuits given

below. Open “Configuration Parameters” from “Simulation” tab. Set “stop time” as “2/f”

where “f” is the last 2 digits of your student number. Set solver options as “Fixed-Step” and

set “Fixed-Step size” as “1e-5”. Run the simulation for 1 second.

1. Open block parameters of sine wave by double-clicking to the icon. Set the

frequency as “2*pi*f” where again “f” is the last 2 digits of your student number.

Run the simulation and observe the output by double-clicking to “scope”.

2. Set “Phase” of “Sine Wave 2” as “-pi/2”. Run the simulation and observe the

output. Double-click onto “Scope” and set “number of axes” as “2” from the

“parameters” tab.

3. Set gain as “-1”. Run the simulation and obverse the output. Calculate the phase

shift.

4. Change the frequency of “Sine Wave 6” as “2*pi*f*100” where f is the last 2 digits

of student number. Run the simulation, observe the outputs.

32

2.2 Generating Sinusoids in MATLAB To generate and plot the sinusoid sin(2πt) the following script is used:

t=-1:0.001:1; %time interval x=cos(2*pi*t); plot(t,x);grid;

2.3 Experimental Procedure Define these variables:

f = "Last Two Numbers of Your Student ID"

t = [-1/f : 0.000001 : 1/ f]

1) Generate a sinusoid s1=A1sin(2πft+φ) where A1=5. Plot s1 for φ=0 and φ=π/2 on the same graph. Calculate the time shift between these two sinusoids.

2) Plot s1 and -s1 on the same graph. Calculate the phase shift between these two sinusoids.

3) Generate a sinusoid s2=A2cos(2πf(t-t1)) where A2=7. Plot s2 for t1=0 and t1=0.05 on same graph. Calculate the phase shift.

4) In AM modulation, the carrier signal's amplitude is modulated by the message signal. The simplest way to do this is multiplying message and carrier signals. In this chapter, the message signal is defined as m=sin(2πft). The carrier signal is defined as c=sin(2π100ft). For f and t, use the values defined above. Plot m, c, m*c and (m+1)*c in the same window using the subplot command.

2.3 Report Write a report including all your MATLAB codes and plots. Comment on the results.

-1 -0.5 0 0.5 1-1

-0.5

0

0.5

1

33

3. Fourier Series Expansion (Demo)

Fourier series provides to represent a periodic function in terms of an infinite sum of sines

and cosines. Fourier series make use of the orthogonality relationships of the sine and

cosine functions.

In this demo, we first examine the fseriesdemo.m (will be provided) then calculate the

Fourier coefficient of a square wave and regenerate it.

3.1 Preliminary Work

1) Run fseriesdemo.m. Observe the signals for different signal and different coefficients.

2) Define a time vector as t=0:0.001:1. Write a script or function that generates triangular signal defined in below.

15.01

5.00)(

tt

tttf

3.2 Fourier Series Expansion

After installing the necessary files to MATLAB current directory, you can run fseriesdemo.m with the command fseriesdemo. In pop-up window, you can observe 3 graphs on left panel. First one demonstrates the original and synthesized signal. Second and third demonstrate the magnitude and the phase diagrams of the coefficients. You can specify the original signal from listed tab on right panel. You can also determine the period of the original signal with the slider in a range 5 seconds to 15 seconds. Order of Fourier Series coefficients which will be synthesized can be arranged with second slider on the right panel.

34

Consider the signal defined as below. It has a period of 1 second and its pulse width is half of its period. In discrete time, it is represented by 1000 samples.

1

f(x)

0.5 10 t

Two functions are defined below. With the first one, Fourier series coefficients of any periodic signal can be obtained. Second function can be used for synthesizing the Fourier series coefficients which are obtained with firs function.

%function to find coefficients of fse function y=fsc(r,order,mr)

a(1)=sum(r)/(mr); t=1:mr; t=t/mr*2*pi;

b(1)=0;

for count=1:order a(count+1)=sum(r.*cos(count*t))/(mr/2);

35

b(count+1)=sum(r.*sin(count*t))/(mr/2); end;

y=[a;b]; end

Where r is the vector which contains the data of f(x), order is the number that determines the how many coefficients will be calculated and mr is the length of r. It returns Fourier coefficients and in a matrix.

%Fourier series expansion of given coefficients function y=fse(coef,order,mr);

t=1:mr; t=t/mr*2*pi;

re=zeros(1,mr);

a=coef(1,:); b=coef(2,:);

for count=1:order re=re+a(count)*cos((count-1)*t)+b(count)*sin((count-1)*t); end; y=re; end

After defining functions fsc and fse functions properly, using following commands a squarewave can be defined, Fourier coefficients and result of sum of series expansion can be calculated. t=0:0.001:1;

s=zeros(size(t)); for i=1:length(t) if (t(i)<0.5) s(i)=1; else s(i)=0; end end c=fsc(s,n, length(s)); s2=fse(c,n,length(s));

Where s is the square wave signal. Results for different order of expansion are illustrated

below.

36

3.3 Procedure

1) Define fsc and fse functions. 2) Define triangular signal as vector. 3) Obtain Fourier coefficient of triangular signal using “fsc” function. 4) Regenerate triangular signal with different orders of Fourier series coefficients using

“fse” function.

3.4 Report Write a report including all your MATLAB codes and plots. Comment on the results.

37

4. Functions Under Matlab (Demo)

Execution of commands that are entered in the command line can’t be saved. In order to

re-execute such commands, one needs to re-type all the commands which is very

impractical in programming. Therefore, MATLAB provides an option for evaluation of

commands repeatedly. To do that, one needs to create an “.m file” which contains all the

commands needed for his/her special purpose. After creating an “.m file”, saving it to a

proper folder enables it to be run repeatedly while having an opportunity of making

necessary modifications for future work. The created “.m file”s can be classifed as two main

groups which are:

M-file scripts

M-file functions

4.1 M-file Scripts A script file is an external file, consist of a series of commands. This files simply executes the

commands that are entered inside them. To create an m-file script, click “File > New >

Script”. As an example script, you can write the following commands that calculates the

inverse of a matrix, which is the multiplication of the matrices.

123

614

274

,

458

425

311

BA :

A=[1 1 3;5 2 4;8 5 4];

B=[4 7 2;4 1 6;3 2 1];

C=A*B;

D=inv(C)

After writing the commands above, save the file as “test.m” to your current folder and go

back to the command window. When you write the following command into command

window, you will evaluate the file that you have just created:

>> test

D =

0.2639 0.0341 -0.0758

-0.1944 0.0845 -0.0012

-0.0694 -0.1603 0.1186

38

When you execute “test.m”, you can observe that, the variables written in your text are

created in MATLAB workspace. This may have undesirable effects, because:

Variables already existing in the workspace may be overwritten.

The execution of the script can be affected by the state variables in the workspace.

To prevent from those issues, it will be useful to make such evaluations by using M-file

functions.

4.2 M-file Functions Functions are programs that accept inputs, and creates outputs upon the characteristic

properties of the code. Each M-file function has its own area of workspace, separated from

the MATLAB base workspace. To create an m-file function, click “File > New > Function”.

When you do that, a new window is opened, and the following screen appears:

function [ output_args ] = Untitled( input_args )

%UNTITLED Summary of this function goes here

% Detailed explanation goes here

end

This blank page, defines the structure of m-file function. To create an example function, that converts the temperature from Celsius to Fahrenheit, just write the following code: function [ fahrenheit ] = temperature_conversion( celcius )

%UNTITLED Summary of this function goes here

% Detailed explanation goes here

fahrenheit=(1.8*celcius)+32;

end

When saving m-file function, make sure that, name of the function and name of the m-file must be same!! Otherwise, your function will not work. Therefore, the name of the m-file should be “temperature_conversion.m” After saving the m-file function, write the following

command to convert C0100 into appropriate Fahrenheit value: >> temperature_conversion(100)

ans =

212

As you can see, when you write the name of the function, and enter the desired input,

MATLAB creates a variable named “ans” automatically. This may be, however, impractical

use for the functions, since it may have multiple outputs. To prevent that, the following

command will be more useful, while working with functions:

>> f_temp=temperature_conversion(100)

f_temp =

39

212

As seen above, a new variable named “f_temp” is created equated to the output of the

function. This enables user to control the output variables which may be used as an input

for another functions.

The table below summarizes the basic differences, between scripts and functions.

SCRIPTS FUNCTIONS

Do not accept input arguments or return output arguments

Store variables in a workspace that is shared with other scripts

Useful for automating a series of commands

Can accept input arguments and return output arguments

Store variables in a workspace internal to the function

Are useful for extending the MATLAB language for your application.

The general form of functions in MATLAB, look like the following:

function [outputs] = function_name(inputs)

The functions can have none, one or several output arguments. The table below shows

some examples of function protoypes:

function C = FtoC(F) Name of function: “FtoC”

Input: “F” One input

Output: “C” One output

function distance = dist_calc(v,t) Name of function: “dist_calc”

Input: “v,t” Two inputs

Output: “distance” One output

function [Id Vov] = MOSFET(Vgs,W,L) Name of function: “MOSFET”

Input: “Vgs, W, L” Three inputs

Output: “Id, Vov” Two outputs

40

4.3 Procedure

1) Beginner: Write a function that calculates your Body-mass-index (BMI) using the

following formula: 2)(

)(

mheight

kgmassBMI

After writing the function, calculate your body-mass-index by using your function in the command window.

2) Easy: Write a function that calculates the factorial of the input number.

3) Moderate: Write a function that shows the “n” Fibonacci numbers using the following formula:

)2()1()(

1)1(

1)0(

nfnfnf

f

f

4) Audio Chopping (Hard):

Hint: The command “x( indice1 : indice2 )” returns the values of x from indice1 to

indice2 as a vector.

Read a mono - wav file.

Using the hint above, write a function that accepts two inputs which are the audio

vector and sampling frequency, and generates one output vector whose elements

are the first 3 seconds of input audio signal.

41

5. Digital Signals: Audio and Image

In this chapter, we will perform the basic processing operations of digital signals, which are imported to MATLAB.

5.1 Preliminary Work

1) Construct a new Simulink model that includes ‘From Multimedia File’ and ‘To Audio Device’ blocks as follows:

Make necessary arrangements in the ‘From Multimedia File’ block for your audio signal.

Run the Simulink model and listen the audio signal.

2) Insert the ‘downsample’ block to your model as shown in the following figure:

Run the model for different downsampling factors that you select. Explain how the quality

of the audio signal changes while the downsampling factor increases.

3) Repeat second procedure 1 with the upsample block. Explain how the quality of the audio signal changes while the upsampling factor increases. Explain the encountered errors.

42

4) Build the Simulink model to generate the echo effect as given below.

5) Build the Simulink model to generate the reverb effect as given below.

6) Build the Simulink model to generate the distortion effect. Set the Audio Output Data Type of From Multimedia File block to single. Change the upper limit and lower limit values of the Saturation block as given below.

43

5.2 Experimental Procedure

5.2.1 Reading an Audio Signal in MATLAB We will read the digital audio signal from the .wav file. We will transfer it into an array in the MATLAB workspace. 1) Read a .wav file. See the value of fs and size of audio. 2) Plot the right and left channel data (using a subplot or on same graph) and listen them

separately. 3) Apply the echo effect to the audio signal and listen it. 4) Apply the reverb effect to the audio signal and listen it. 5) Apply the distortion effect to the audio signal and listen it.

5.2.2 Reading an Image in MATLAB 1) Read a digital color image. 2) Display the read image using an appropriate command. 3) Convert the color image to grayscale. 4) Display the grayscale image. Get the number of rows and columns of the grayscale

image.

5.3 Report Write a report including all your MATLAB codes, Simulink models, and plots. Comment on

the results.

44

6. Discrete Convolution

In this experiment, we will learn how to implement digital FIR filters in MATLAB and Simulink by using two different MATLAB built-in functions. With these, we will perform discrete convolution implementation in MATLAB and Simulink. We will apply the filtering operations and compare the original and filtered signals.

6.1 Preliminary Work 1) Construct the following Simulink model to implement discrete FIR filtering in Simulink.

Make necessary arrangements in ‘From Multimedia File’ block for your audio signal. The

numerator of ‘Discrete FIR Filter’ block includes the filter coefficients. Use the coefficients

b=[0.04, 0.2, 0.4, 0.2, 0.04]. Run the model, listen to the filtered audio signal, observe the

output from the scope and compare the filtered and unfiltered audio signals.

2) Now add noise to audio signal as shown below. Listen to original and filtered signals.

45

1) Construct the following Simulink model to implement discrete convolution.

Make necessary arrangements in the ‘From Multimedia File’ block for your audio signal.

The ‘Constant’ block includes filter coefficients. Make sure that the output data types of

‘From Multimedia File’ and ‘Constant’ blocks are double. Run the model, listen to the

filtered audio signal, observe the output from the scope and compare the filtered and

unfiltered audio signals.

6.2 Experimental Procedure We can use the following command for FIR filtering of a one dimensional (audio) signal.

y= filter(b, 1, x);

Where x is the input signal, b is the vector of the filter coefficients and y is the filtered

output signal. If the signal is two dimensional (image), the following command is used for

FIR filtering.

y= filter2(b, image);

1) Read an audio signal and apply a low pass FIR filter to it (left channel or right channel data) using the filter coefficients b=[0.2491 0.0034 0.0034 0.0034 0.0034

0.2491]. Listen to the filtered audio signal. Compare it with the original signal by plotting both in the same figure.

2) Apply a low pass FIR filter to the digital audio signal obtained in procedure 1 using discrete convolution with the “conv()” function. Use the same filter coefficients in procedure 1. Listen to the filtered audio signal and compare it with the original signal.

3) Generate a noise signal with the following command.

noise=0.05*rand(size(audio));

Add this to the audio signal. Filter the resulting signal by an FIR filter with coefficients b=[0.2491 0.0034 0.0034 0.0034 0.0034 0.2491]. Repeat procedure 1 and 2. Listen to the original, noise added, and the filtered signals. Compare all by plotting them in the same figure.

46

4) The following command calculates and plots the impulse response of a given system.

impz(b)

Evaluate the impulse response of filters b1 = [0.04, 0.2, 0.4, 0.2, 0.04] and b2= [0.01, -0.2, 0.5, -0.2, 0.01]. Calculate the serial connected and parallel connected impulse response of these filters.

5) Read a digital color image, convert it to grayscale and apply a high pass FIR filter to the grayscale intensity image using “filter2()” function with filter coefficients b = [-1 -1 -1; -1 8 -1; -1 -1 -1].

Show the filtered image and compare it with the original image.

6) Repeat procedure 5 using two dimensional discrete convolution with same filter coefficients above, by using following command:

conv2(double(name_of_the_grayscale_image),b);

Show the filtered image and compare it with the original image.

7) Add noise to an image. Use the FIR filter with coefficients b=1/9*ones(3,3). Again, filter it with the two dimensional median filter. Write a report including all your MATLAB codes, Simulink models, and plots. Comment on the results.

6.3 Report Write a report including all your MATLAB codes, Simulink models, and plots. Comment on the results.

47

7. Z-Transform

In this experiment we will examine the z-transform in MATLAB.

7.1 Preliminary Work

1) Learn the usage of functions sym, syms, ztrans and iztrans. 2) Define a symbolic function p . Find its roots with the solve

function. 3) Prepare the IIR filter codes for the experiment.

7.2 Z-Transform General form of Z-transform is given below.

[ ] ∑ [ ] [ ]

↔ [ ] ∑ [ ]

for a given input sequence x[n], in the form [ ] ∑ [ ] [ ]

A symbolic function can be defined in MATLAB. First you must declare your variables as symbolic with command sym or syms. syms z n Then you can define any function of z and n. xn=3*dirac(n)-2*dirac(n-1)

You can calculate the symbolic form of the Z-transform of xn with the command ztrans. Xz=ztrans(xn)

This command returns Xz = 3*ztrans(dirac(n), n, z) - (2*ztrans(dirac(n), n, z))/z

As can be seen, the returned function is in term of ztrans(dirac(n), n, z). The equivalent of [ ] is 1 in Z-domain. Therefore, ztrans(dirac(n), n, z)) can be substituted with 1 with following command. Xz=subs(Xz, ztrans(dirac(n), n, z),1)

which yields Xz = 3 - 2/z

48

Inverse Z-transform can be calculated with function iztrans. The resultant function will be a function of kroneckerDelta(n, 0). This seems confusing, but its functionality is same as [ ]. The values of array x[n] can be obtained with the subs function. xn=iztrans(Xz)

returns xn= 3*kroneckerDelta(n, 0) - 2*kroneckerDelta(n - 1, 0)

The following command returns the values of x[n] for values of n from 0 to 10. x=subs(xn,n,0:10)

x = [ 3, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The transfer function of an IIR filter can be defined as:

7.3 Experimental Procedure

1) For a given LTI system given below;

H(z)

x[n] y[n]

where [ ] [ ] [ ] [ ] [ ] [ ] [ ]

calculate y[n].

Show that [ ] [ ] [ ] corresponds to

2) Calculate y1[n] and y2[n] for x[n] and H(z) defined in procedure 1.

49

3) Write a function that realizes the IIR filter having coefficients;

a =

1.000000000000000e+000

-9.453549054680797e+000

4.023055814712089e+001

-1.014903354465407e+002

1.680782073345783e+002

-1.909359522948873e+002

1.506765261550268e+002

-8.156212209921239e+001

2.898280457424895e+001

-6.105005561783935e+000

5.788682461462072e-001

b =

1.557977204073596e-014

1.557977204073596e-013

7.010897418331182e-013

1.869572644888315e-012

3.271752128554552e-012

3.926102554265462e-012

3.271752128554552e-012

1.869572644888315e-012

7.010897418331181e-013

1.557977204073596e-013

1.557977204073596e-014

Apply this filter to an audio signal and compare it with the filter function. filter(b,a,audio)

7.3 Report Write a report including all your MATLAB codes, Simulink models, and plots. Comment on the results.

50

8. FDATool (Demo)

FDATool is a Graphical User Interface that allows you to design or import, and analyze FIR

or IIR filters, provided by MATLAB. You can run it with the command fdatool in

command window.

>> fdatool

After this command a pop-up window will appear as below.

The GUI has three main regions:

The Current Filter Information region

The Filter Display region and

The Design panel

The upper half of the GUI displays information on filter specifications and responses for the

current filter. The Current Filter Information region, in the upper left, displays filter

properties, namely the filter structure, order, number of sections used and whether the

filter is stable or not. The Filter Display region, in the upper right, displays various filter

responses, such as, magnitude response, group delay and filter coefficients.

51

The lower half of the GUI is the interactive portion of FDATool. The Design Panel, in the

lower half is where you define your filter specifications. It controls what is displayed in the

other two upper regions. Other panels can be displayed in the lower half by using the

sidebar buttons.

Once you have designed the filter, you can view the following filter analyses in the display

window by clicking any of the buttons on the toolbar:

In order from left to right, the buttons are;

Magnitude response

Phase response

Magnitude and Phase responses

Group delay response

Phase delay response

Impulse response

Step response

Pole-zero plot

Filter Coefficients

Filter Information

You can export your filter to the following destinations:

MATLAB workspace

MAT-file

Text-file

Select Export from the File menu.

If exporting to the MATLAB workspace, you can export as coefficients or as an object by selecting from

the Export from the pulldown menu.

52

9. Discrete-Time Frequency Response

In this experiment, we will examine the frequency response of FIR and IIR filters in MATLAB.

9.1 Preliminary Work

1) Learn the usage of functions abs and angle. 2) Design a 63th order low pass FIR filter. Export the filter coefficients to MATLAB

workspace. 3) Design a 63th order low pass IIR filter. Convert its structure to Direct Form I and

single section. Export the filter coefficients to MATLAB workspace.

9.2 Experimental Procedure

9.2.1 Frequency Response of FIR and IIR Filters

1) To observe the frequency response of a filter, we can use the following command: freqz(b);

where b is the filter coefficient vector. Using the command above, show the frequency response of the FIR filters implemented in Chapter 4 and designed in the preliminary work.

2) The function freqz can also be used for calculating frequency response of IIR filter as follows.

freqz(b,a);

Where a and b are the filter coefficient vectors. Using the command above, show the frequency response of the IIR filter implemented in Chapter 6 and designed in the preliminary work.

9.2.2 Frequency Response in Z-Domain

1) Define the system given below;

Now define as . Sweep from -π to π. Calculate the magnitude of frequency response

of the system with abs function and phase response with angle function. Plot them.

53

2) For the given system below;

H1(z)

x[n] y[n]

H2(z)

a. Calculate the frequency response of the first block. b. Calculate the frequency response of the second block. c. Calculate the frequency response of the whole system.

9.3 Report Write a report including all your MATLAB codes, and plots. Comment on the results.

54

10. Fourier Transform

In this experiment, we will examine the frequency response of FIR filters. We will also learn the implementation of Discrete Fourier Transform in MATLAB.

10.1 Preliminary Work

1) Run cltidemo.m and observe the frequency response of different filter types. 2) Read an audio file. Apply Fourier Transform with fft function. Plot the absolute

values of the result for each channel.

10.2 Discrete Fourier Transform under MATLAB

The following command is used to evaluate the n-point Discrete Fourier Transform of a signal in MATLAB: X = fft(x,n);

where n is the length of the vector x. The following command rearranges the output of fft by moving the zero-frequency component to the center of the array. It is useful for visualizing a Fourier transform with the zero-frequency component in the middle of the spectrum. X = fftshift(X/n);

The following commands define the frequency axis and show the magnitude response. F=(-(n-1)/2:n/2)*(fs/n);

plot(F,abs(X));grid;

The following command evaluates the inverse fft. x = ifft(X,n);

10.3 Experimental Procedure

1) Plot the frequency spectrum of all signals defined in Chapter 2. To do so, define the sampling frequency fs as 44100 and the time vector as t=[0:1/fs:1].

2) Define a sinusoid s which is a sum of 100 Hz and 10 kHz sinusoids. a. Evaluate an n (which is equal to the length of s) point FFT. Plot its magnitude and

angle. b. Find the FFT of the FIR filter which is defined with coefficients given below. Again this

should be an n point FFT.

55

b= [0.058314410978206 0.060284242199075

0.082066666909259

0.100830178780903

0.113534654382583

0.118060205483520

0.113534654382583

0.100830178780903

0.082066666909259

0.060284242199075

0.058314410978206]

c. Multiply the results obtained in parts a and b. Plot the magnitude response of the

multiplication. Compare it with the magnitude response of s. Evaluate the inverse FFT of the multiplication. Plot the resultant vector and compare it with s.

3) Design three different 127th order FIR filters with FDATool for given frequencies below. Low pass filter: fpass = 500 Hz, fstop = 1000 Hz Band pass filter: fstop1 = 1000 Hz, fpass1 = 1500 Hz, fpass2 = 6500 Hz, fstop2 = 7000 Hz High pass filter: fstop = 7000 Hz, fpass = 7500 Hz Import the filter coefficient to workspace. Find the FFT of each filter. Do NOT use fftshift command. Read an audio signal, perform Fourier transform on audio signal (do not use fftshift command). Multiply audio signal and FIR filter in frequency domain for each filter separately. Take the inverse Fourier transform of resultant vectors and listen them. Compare the result with convolution of audio signal and FIR filters.

10.3 Report Write a report including all your MATLAB codes and plots. Comment on the results.