Вы находитесь на странице: 1из 27

# DIGITAL SIGNAL PROCESSING

Lab Contents: Introduction to MATLAB, Getting started (Reading Assignment), Vectors, Scalars and Matrices, Basic Arithmetic operations, Mathematic functions, and Plotting.

2/21/2011

## DIGITAL SIGNAL PROCESSING

WHAT IS MATLAB:
MATLAB is a high-level language and interactive environment that enables you to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran. The MATLAB high-performance language for technical computing integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include

Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. It allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar no interactive language such as C or Fortran. The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix computation. MATLAB has evolved over a period of years with input from many users. In university environments, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for highproductivity research, development, and analysis. MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. You can add on toolboxes for signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many other areas.

2/21/2011

## Overview of Starting the MATLAB Program

The way you start the MATLAB program depends on the platform you use:

On Microsoft Windows platforms, start MATLAB by double-clicking the MATLAB R2009a shortcut on your Windows desktop.

When you start MATLAB, all the product software from The MathWorks that you are licensed to use, is available. You do not have to start each product separately. There are alternative ways to start MATLAB, and you can customize startup. For example, you can change the directory in which MATLAB starts or automatically execute MATLAB statements upon startup.

## Starting the MATLAB Program from the Windows Desktop

To start the MATLAB program on a Microsoft Windows platform, select Start > Programs > MATLAB > R2009a > MATLAB R2009a, or double-click the shortcut icon for MATLAB R2009a on your Windows desktop. The shortcut was automatically created when you installed MATLAB. To start MATLAB from a DOS window, cd to the directory in which you want to start MATLAB and type matlab at the DOS prompt. After starting MATLAB, the desktop opens. Desktop components that were open when you last shut down MATLAB will be opened on startup.

Starting the MATLAB Program from an M-File or Other File Type on Windows Platforms
On Windows platforms, you can start MATLAB from the Windows Explorer tool by doubleclicking a file with one of these extensions: .fig, .m, .mat, and .mdl. MATLAB starts and opens in an appropriate tool. If MATLAB is already running, the file opens in an appropriate tool in the existing session. This startup feature is based on your file type associations for the Windows operating system. When you installed MATLAB for Windows platforms, you specified the file types to associate with MATLAB. For example, if you accepted the default options, double-clicking an M-file in the Windows Explorer tool opens the file in the MATLAB Editor. The default option also associates MEX-files and P-files with MATLAB in the Windows Explorer tool, which assigns the file types an icon for MATLAB. However, double-clicking a file with a .mex (.mexw32 or .mexw64), or .p extension does not run or open the file in MATLAB.

## File Type and Resulting Action

2/21/2011

File Type Result FIG-file M-file Opens file in figure window Opens file in Editor

MAT-file Opens Import Wizard to load the data into the MATLAB workspace MDL-file Opens file in a Simulink model window MEX-file Displays icon for MATLAB in Windows Explorer tool P-file Displays icon for MATLAB in Windows Explorer tool

If you double-click a FIG-file, M-file, MAT-file, or MDL-file and it does not open in , and you want it to, try this: 1. In the Windows Explorer tool, right-click a file that has one of the extensions for MATLAB, for example, myfile.mat. 2. From the context menu, select Open With. If MATLAB is one of the choices, select it to open myfile.mat in MATLAB.

2/21/2011

But If MATLAB is not one of the choices, you will need to associate the file type with MATLAB using one of these techniques:

Utility to Change File Associations for Windows Platforms Changing File Associations for the MATLAB Program from the Windows Environment

3. File associations for the Windows Explorer tool do not affect what happens when you open one of these file types from within MATLAB. MATLAB acts on the file using the MATLAB tool associated with that file type. For example, even if you associate .mat files with the Access application, when you open a MAT-file from within MATLAB, it opens the Import Wizard to load the data.

## Startup Directory for the MATLAB Program

What Is the Startup Directory?
The startup directory is the current directory in the MATLAB application when it starts. It is convenient if you make the current directory upon startup be a directory that you frequently use. On Windows and Apple Macintosh platforms, a directory called userpath is added automatically to the search path upon startup, and is the default startup directory. The default value for userpath is, for example, Documents/MATLAB on Microsoft Windows Vista platforms. You can specify a different default value for userpath, or specify a different startup directory. Accepting the default value for userpath and using it as the startup directory offers these benefits:

You can store the MATLAB files you work with in one, appropriately-named location, such as Documents/MATLAB. Your MATLAB files are readily available upon startup, because the current directory is always the same, for example, Documents/MATLAB. You can always run your files because MATLAB automatically adds the userpath subdirectory to the top of the search path upon startup. The first time you run a new version of MATLAB, MATLAB automatically creates the userpath subdirectory if it does not exist. When you upgrade to a newer version of MATLAB, MATLAB automatically continues to use the same MATLAB subdirectory and your existing files, with all of its other benefits. The default userpath also utilizes the benefits provided by the standard location in the Windows and Macintosh environments for storing personal files. Files in the Documents/MATLAB subdirectory (or My Documents/MATLAB on Windows platforms other than Windows Vista) are available to you when you use other machines. Because each user has their own Documents/MATLAB subdirectory, other users, even those using your machine, cannot access files in your Documents/MATLAB subdirectory.

2/21/2011

## WAYS TO QUIT THE MATLAB PROGRAM

To quit the MATLAB program at any time, do one of the following:

Click the Close box in the MATLAB desktop. Select Exit MATLAB from the desktop File menu. Type quit at the Command Window prompt.

## MATLAB closes after

Prompting you to confirm quitting, if that preference is specified. Prompting you to save any unsaved files. Running the finish.m script, if it exists in the current directory or on the search path.

## Confirm Quitting the MATLAB Program

To set a preference that displays a confirmation dialog box when you quit MATLAB, select File > Preferences > General > Confirmation Dialogs, select the Confirm before quitting check box, and click OK. MATLAB then displays the following dialog box when you quit.

You can also display your own quitting confirmation dialog box using a finish.m script, as described in the following section.

## Recovering Data After an Abnormal Termination

If MATLAB terminates unexpectedly, you might lose information. After you start MATLAB again, you can try these suggestions to recover some of the information. Use the Command History or the file on which it is based, history.m, to run statements from the previous session. You might be able to approximately recreate data as it was prior to the termination. For more information, see Overview of the Command History Window. If you used the diary function or -logfile startup option for the session in which MATLAB terminated unexpectedly, you might be able to recover output.

2/21/2011

Some of the above suggestions refer to actions you might have needed to take during the session when MATLAB terminated. If you did not take those actions, consider regularly performing them to help you recover from any future abnormal terminations you might experience.

DESKTOP
Desktop Overview

In general, when you start the MATLAB program, it displays the MATLAB desktop, a set of tools (graphical user interfaces or GUIs) for managing files, variables, and applications associated with MATLAB. You can change the desktop arrangement to meet your needs, including resizing, moving, and closing tools. The desktop manages tools differently from documents. The Command History and Editor are examples of tools, and an M-file is an example of a document, which appears in the Editor tool. The first time you start MATLAB, the desktop appears with the default layout, as shown in the following illustration.

2/21/2011

## Summary of Desktop Tools

The following tools are managed by the MATLAB desktop, although not all of them appear by default when you first start. If you prefer a command-line interface, you can often use equivalent functions to accomplish the same results. To perform the equivalent of the GUI tasks in M-files, you must use the equivalent functions. Instructions for using equivalent functions to perform the task are provided with the documentation for each tool and are typically labeled as Function Alternatives. Desktop Tool Command History Command Window Current Description View a log of or search for the statements you entered in the Command Window, copy them, execute them, and more. Run MATLAB language statements.

Directory View files, perform file operations such as open, find files and file

2/21/2011

## Desktop Tool Browser Editor Figures

Description content, and manage and tune your files. Create, edit, debug, and analyze M-files (files containing MATLAB language statements). Create, modify, view, and print figures generated with MATLAB.

File and Directory View line-by-line differences between two files. Comparisons Help Browser Profiler Start Button Variable Editor Web Browser Workspace Browser View and search the documentation and demos for all your MathWorks products. Improve the performance of your M-files. Run tools and access documentation for all your MathWorks products, and create and use shortcuts for MATLAB. View array contents in a table format and edit the values. View HTML and related files produced by MATLAB. View and make changes to the contents of the workspace.

## Keyboard Shortcuts (Accelerators or Hot Keys) and Mnemonics

2/21/2011

tool is selected to see the mnemonics on the menus and buttons. Use the Windows Control Panel to set preferences for underlining keyboard shortcuts. See the Windows documentation for details. Following are some general shortcuts that are not listed on menu items. Key Enter Result The equivalent of double-clicking, Enter performs the default action for a selection. For example, press Enter while a statement in the Command History window is selected to run that statement in the Command Window. For buttons in tools and dialog boxes, Enter executes the default button (the button with a border around it). If there is no default button, press the space bar to execute the active button (the button with a dotted outline inside it). See Default Button and Active Button (Button with Focus) for an illustration. Esc (escape) Cancels the current action. For example, if you select the Edit menu, the menu items display. Pressing Esc retracts the menu items. Pressing Esc in a dialog box is the same as selecting the Cancel button. Advances to the next button or field in a tool or dialog box. In the Command Window, completes a statement if the tab completion preference is selected. Space bar For buttons in tools and dialog boxes, activates the active button. See Default Button and Active Button (Button with Focus) for an illustration of selecting default and active buttons using keys.

Tab

+ or - or * on Use these keys on the numeric keypad to expand and collapse items in numeric keypad tree views. The Help browser Help Navigator pane and the Command History window use tree views. Use + to expand the selected item, use to collapse the selected item, and use * to recursively expand it, meaning open all items contained in the selected item. Alt+S Alt+Y Ctrl+Tab Ctrl+Shift+Tab Ctrl+Page Down Ctrl+Page Up Displays the Start button menu (except on Macintosh platforms). Provides access to the current directory field in the toolbar (except on Macintosh platforms). Moves to the next open tool in the desktop, or to the next open group of tools tabbed together. Moves to the previous open tool or group of tabbed tools in the desktop. Moves to the next tool within a group of tools tabbed together. In a group of documents, moves to next document. Moves to the previous tool within a group of tools tabbed together. In a

2/21/2011

Key

## Result group of documents, moves to previous document.

Ctrl+F6 Alt+F4

Moves to the next tool or document (only for Windows and Sun Microsystems Solaris platforms). Closes the desktop and consequently, shuts down the MATLAB program. Or outside the desktop, closes the active window (except on Macintosh platforms)

MATLAB HELP
You have to highly rely on MATLAB help throughout and its a good habit to use MATLAB help instead of wandering out on internet and searching for answers. Here are some steps on how you can access and use MATLAB help.

10

2/21/2011

As you can see in the figure above there is a lot of helping material available on each and every topic, so no need to panic if you face any sort of problem just refer to MATLAB help.

11

2/21/2011

You can also search for commands, codes, examples etc by clicking on help >> Index >> Enter Index term>> (Enter the desired term youneed to search). Enter the keyword as shown in the preceding figure and you will get a lot of results, select the appropriate one and you will have all the help in front of you on that specific topic. For example, the trigonometric function cos (cosine) was searched here and all the available topics regarding cos were listed after selecting the desired option the relevant data appeared on screen.

## MATLAB VARIABLES SCALARS, VECTORS, AND MATRICES

12

2/21/2011

MATLAB stores variables in the form of matrices which are M N, where M is the number of rows and N the number of columns. A 1 1 matrix is a scalar; a 1 N matrix is a row vector, and M1 matrix is a column vector. All elements of a matrix can be real or complex numbers; 1 can be written as either i or j provided they are not redened by the user. A matrix is written with a square bracket [] with spaces separating adjacent columns and semicolons separating adjacent rows. For example, consider the following assignments of the variable x Real scalar Complex scalar Row vector Column vector 3 3 matrix >> x = 5 >> x = 5+10j (or >> x = 5+10i) >> x = [1 2 3] (or x = [1, 2, 3]) >> x = [1; 2; 3] >> x = [1 2 3; 4 5 6; 7 8 9]

There are a few notes of caution. Complex elements of a matrix should not be typed with spaces, i.e., -1+2j is ne as a matrix element, -1 + 2j is not. Also, -1+2j is interpreted correctly whereas -1+j2 is not (MATLAB interprets the j2 as the name of a variable. You can always write -1+j*2.

## Complex number operations

Some of the important operations on complex numbers are illustrated below. Complex scalar Real part of x Imaginary part of x Magnitude of x Angle of x Complex conjugate of x >> x = 3+4j >> real(x) = 3 >> imag(x) = 4 >> abs(x) = 5 >> angle(x) = 0.9273 >> conj(x) = 3 - 4i

Generating vectors
Vectors can be generated using the : command. For example, to generate a vector x that takes on the values 0 to 10 in increments of 0.5, type the following which generates a 121 matrix

13

2/21/2011

>> x = [0:0.5:10]; Other ways to generate vectors include the commands: linspace which generates a vector by specifying the rst and last number and the number of equally spaced entries between the rst and last number, and logspace which is the same except that entries are spaced logarithmically between the rst and last entry.

## Accessing vector elements

Elements of a matrix are accessed by specifying the row and column. For example, in the matrix specied by A = [1 2 3; 4 5 6; 7 8 9], the element in the rst row and third column can be accessed by writing >> x = A(1,3) which yields 3 The entire second row can be accessed with >> y = A(2,:) which yields [4 5 6]

where the : here means take all the entries in the column. A submatrix of A consisting of rows 1 and 2 and all three columns is specied by >> z = A(1:2,1:3) which yields [1 2 3; 4 5 6]

MATRIX OPERATIONS
MATLAB contains a number of arithmetic, relational, and logical operations on matrices.

## Arithmetic matrix operations

The basic arithmetic operations on matrices (and of course scalars which are special cases of matrices) are: + * / \ ^ addition subtraction multiplication right division left division exponentiation (power) conjugate transpose

14

2/21/2011

An error message occurs if the sizes of matrices are incompatible for the operation. Division is dened as follows: The solution to A x = b is x = A\b and the solution to x A = b is x = b/A provided A is invertible and all the matrices are compatible. Addition and subtraction involve element-by-element arithmetic operations; matrix multiplication and division do not. However, MATLAB provides for element-by-element operations as well by prepending a . before the operator as follows: .* ./ .\ .^ . multiplication right division left division exponentiation (power) transpose (unconjugated)

The dierence between matrix multiplication and element-by-element multiplication is seen in the following example >>A = [1 2; 3 4] A= 1 3 >>B=A*A B= 7 15 >>C=A.*A C= 1 9 4 16 10 22 2 4

Relational operations
The following relational operations are dened:

15

2/21/2011

## < <= > >= == ~=

less than less than or equal to greater than greater than or equal to equal to not equal to

These are element-be-element operations which return a matrix of ones (1 = true) and zeros (0 = false). Be careful of the distinction between = and ==.

## Flow control operations

MATLAB contains the usual set of ow control structures, e.g., for, while, and if, plus the logical operators, e.g., & (and), | (or), and ~ (not).

Math functions
MATLAB comes with a large number of built-in functions that operate on matrices on an element-by element basis. These include: sin cos tan asin acos atan exp log log10 sqrt abs round sine cosine tangent inverse sine inverse cosine inverse tangent exponential natural logarithm common logarithm square root absolute value (magnitude of a number) round towards nearest integer.

16

2/21/2011

ceil floor

## round towards plus infinity. round towards minus infinity.

PLOTTING
MATLAB contains numerous commands for creating two- and three-dimensional plots. The most basic of these commands is plot which can have multiple optional arguments. A simple example of this command is to plot a function of time. t = linspace(0, 8, 401); %Define a vector of time from ... 0 to 8 s with 401 points x = t.*exp(-t).*cos(2*pi*4*t); plot(t,x); xlabel(Time (s)); ylabel(Amplitude); %Define a vector of x values %Plot x vs t %Label time axis %Label amplitude axis

## Simple plotting commands

The simple 2D plotting commands include plot stem Plot in linear coordinates as a continuous function Plot in linear coordinates as discrete samples

loglog Logarithmic x and y axes semilogx semilogy bar errorbar hist polar Linear y and logarithmic x axes Linear x and logarithmic y axes Bar graph Error bar graph Histogram Polar coordinates

17

2/21/2011

Customization of plots
There are many commands used to customize plots by annotations, titles, axes labels, etc. A few of the most frequently used commands are xlabel ylabel title grid axis figure hold on hold off close(n) Labels x-axis Labels y-axis Puts a title on the plot Adds a grid to the plot Allows changing the x and y axes Create a gure for plotting Allows multiple plots to be superimposed on the same axes Release hold on current plot Close gure number n

subplot(a,b,c) Create an a b matrix of plots with c the current gure orient Specify orientation of a gure.

GENERAL INFORMATION
MATLAB is case sensitive so "a" and "A" are two different names. Comment statements are preceded by a "%". You can make a keyword search by using the help command. The number of digits displayed is not related to the accuracy. To change the format of the display, type format short e for scientific notation with 5 decimal places, format long e for scientific notation with 15 significant decimal places and format bank for placing two significant digits to the right of the decimal. The commands who and whos give the names of the variables that have been defined in the workspace. The command length(x) returns the length of a vector x and size(x) returns the dimension of the matrix x.

18

2/21/2011

## COMPLEX NUMBERS AND MATRIX MANIPULATION

INTRODUCTION
Informally the terms matrix & array are often used interchangeably. Matrix is the two dimensional array of real & complex numbers. MATLAB contain many functions that create different type of matrices.

Creating a 1 1 >> A= 1 2 1 3

Matrix: 1 3 6

## Creating a Symmetric Matrix:

For a symmetric matrix A the matrix A and its transpose
A = A ' A'

## are equal i.e.

1 1 1 A= 1 2 3 1 3 6 1 1 1 A'= 1 2 3 1 3 6
Note: from above we can easily say that A & matrix.
A'

## are equal. So matrix A is symmetric

In MATLAB we can use the command Pascal to create symmetric matrix; PASCAL (N) is the Pascal matrix of order N: a symmetric positive definite matrix with integer entries, made up from Pascal's triangle. Its inverse has integer entries. >> A=pascal(3) A= 1 1 1 1 2 3 1 3 6

19

2/21/2011

## Creating a Non Symmetric Matrix

If A
A'

Then matrix is non-symmetric: We use magic command in MATLAB to create such type of matrix. MAGIC (N) is an N-by-N matrix constructed from the integers 1 through N^2 with equal row, column, and diagonal sums.Produces valid magic squares for all N > 0 except N = 2. >> B=magic(3)

8 B = 3 4 8 B' = 1 6
Since here B
B'

1 6 5 7 9 2 3 4 5 9 7 2

## Creating matrix with Random integer

Type the following command in MATLAB and read carefully the whole help. >>help rand: >> help fix FIX Round towards zero.

FIX(X) rounds the elements of X to the nearest integers towards zero. See also FLOOR, ROUND, CEIL. Now type >> C=fix (10*rand (3, 2))

9 4 C = 2 8 6 7
Here C is the generated matrix with 3 rows and 2 columns.

20

2/21/2011

Matrix Addition and Multiplication is done element by element. This means that both matrices should have same number of rows and columns, so they can be added and subtracted. >> d= [1+2j 3; 7 5j] >> c= [2+3j 5+5j; 0 1-8j]

## 1+2j 3 d = 5j 7 2 + 3 j 5+5j c= 1-8j 0

>>f=d+c

3+5j f= 0

8+5j 1-3j

Here also real part is added to real one and imaginary part with the imaginary part.

## Calculating complex Conjugate

We use conj command to calculate the complex conjugate of each complex element in the matrix. Type >>help conj % for more information about conj command

## >> h=conj (g)

1+2j g = 3+4j 1 2 j h= 3 4 j

Matrix Powers
Let suppose you want to multiply a matrix A with itself P times. Then write the following command in matlab. >>A = [1 2 3; 4 5 6; 7 8 9];

21

## 2/21/2011 >>P=2; >>B=A^P

1 2 A = 4 5 7 8 30 B = 66 102

3 6 9 36 42 81 96 126 150

* Note you can also multiply matrix and also vector element by element. >>A = [1 2 3; 4 5 6; 7 8 9]; >>P=2; >>C=A. ^P

1 2 3 A = 4 5 6 7 8 9 1 4 9 C = 16 25 36 49 64 81

## Extracting Real & Imaginary Part From Complex Number

Let Z=A+Bj; Then Z (real) =real (A); And Z (imaginary) = imag (A);

## Accessing elements in Vectors/Matrices

Accessing the element from inside a vector or matrix is the most powerful advantage of the MATLAB over any other computer language. Lets see how this is done by MATLAB. >> K=10:10:100;

22

2/21/2011

K= [10 20 30 40 50 60 70 80 90 100] >>K1=K (1:5) K1= [10 20 30 40 50] >>K2=K (3:8) K2= [30 40 50 60 70 80] >>P=Pascal (3)

1 1 1 P= 1 2 3 1 3 6
>> P1 =P(:, 2)

1 P1= 2 3
>>P2=P(1,:) P2= [1 1 1] M=[1:5; 2:2:10; 3:3:15]

1 2 3 4 5 M = 2 4 6 8 10 3 6 9 12 15
>>M1=M (2:3, 2:4)

4 6 8 M1 = 6 7 12
>>M (:) % this command will convert the matrix into vectors such that columns are taken first. Try it yourself & also below given commands. >>K=1:2:10 >>f=5:5:50;

23

2/21/2011

Evaluating Complex Variables & Expressions Consider the following two expressions that we want to write in matlab. M=ej11/4 M1= (1-j) 10 Now if we want to solve these expressions by using the matlab, then we use these commands are techniques. >> M=j*exp (j*11*pi/4)% Here pi is the predefined variable in Matlab. If we want to change its value to 3, then we can use the command >>pi=3; Now if we want to restore the default value then type >> clear pi; >>M1= (1-j) ^10; j (cos+jsin)

## Plotting Complex value functions in MATLAB

Plots in MATLAB are generated using the plot function. Try the below command. >> help plot Now as we already know from our previous knowledge that complex numbers corresponds to x = a+bj So MATLAB provides the real & imag function to separate the real &imaginary parts of a complex number. For more clearance of mind try to absorb the following example. >> x=2+7j; >> xr=real(x); >> xi=imag(x); >> Plot (xr, xi,'x'); % Here x defines the shape of the data point.

## Generating Complex Functions

Generating complex function can be explained from the following example.

24

2/21/2011

f (t) =3ei3t For t=0 1 with 0.001 increments We could use t=0:0.001:1; f=3*exp (j*3*pi*t);

LAB ASSIGNMENT 01
Q.1. Create a symmetric matrix m with five rows and five columns. Calculate its transpose and verify that the matrix is symmetric by observing that m=m. Q.2. Create a random matrix with 3 rows and 5 columns. The matrix values should be integer b/w (0100), than change its all 2 rows values by 7. Hint: Use commands fix & rand Q.3. Use your knowledge to define a vector by incrementing and also cascade more than one vector to form a matrix try to make a matrix with the following properties. (1) Matrix should contain 2 rows. (2) First row of matrix should contain even number b/w (010) (3) Second row of matrix should contain odd number b/w (1120) Q.4.

and calculate

## (a) c=d+e (b) c=d-e (c) c=d*e (d) c=d/e

Note: multiplication and division should be done element by element. Q.5. Plot the function

25

2/21/2011

## y=3*exp (3*pi*t); Choose t from (0---150) with increment of 0.001

Hard copy of the Lab Assignment has to be submitted in the coming Lab next week. The report should be up to standards in terms of the formatting i.e. properly aligned, justified, proper paragraph/line spacing, font size and font color. Use a standard Front page uploaded on cuonline.

26