Courtesy of Thomas F Weiss. Used with permission. MASSACHUSETTS INSTITUTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science Signals and Systems --6.003 NTRODUCTION TO MATLAB- Fall 1999 Thomas f. Weiss H modification September 9, 1999
MASSACHUSETTS INSTITUTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science Signals and Systems — 6.003 INTRODUCTION TO MATLAB — Fall 1999 Thomas F. Weiss Last modification September 9, 1999 1 Courtesy of Thomas F. Weiss. Used with permission
Contents 1 Introduction 2 Getting Started 3 Getting Help from Within MATLAB 4 MATLAB Variables -Scalars, Vectors and Matrices 4.1 Complex number operations 4.2 Generating vectors 4.3 Accessing vector elements 5 Matrix Operations 5.1 Arithmetic matrix operations 334445556677 5.2 Relational operations 5.3 Flow control operations 5.4 Math functions 6 MATLAB Files 6.1 M-Files 6.1.1 Scripts 6.1.2 Functions 6.2 Mat-Files 8899 6.3 Postscript Files 6.4 Diary Files 7 Plotting 10 7.1 Simple plotting commands 11 7.2 Customization of plot 8 Signals and Systems Commands 8.1 Polynomials 8.2 Laplace and Z Transforms 8.3 Frequency responses 11233 8.4 Fourier transforms and filterin 9 Examples of Usage 13 9.1 Find pole-zero diagram, bode diagram, step response from system function. 13 9.1.1 Simple solution 9.1.2 Customized solution 9.2 Locus of roots of a polynomial 9.3 Response of an LTI system to an input 10 Acknowledgement 688
Contents 1 Introduction 3 2 Getting Started 3 3 Getting Help from Within MATLAB 4 4 MATLAB Variables — Scalars, Vectors, and Matrices 4 4.1 Complex number operations . . . ........................ 4 4.2 Generating vectors . . . ............................. 5 4.3 Accessing vector elements ............................ 5 5 Matrix Operations 5 5.1 Arithmetic matrix operations . . ........................ 6 5.2 Relational operations . . ............................. 6 5.3 Flow control operations . ............................. 7 5.4 Math functions . ................................. 7 6 MATLAB Files 7 6.1 M-Files . ..................................... 8 6.1.1 Scripts . . ................................. 8 6.1.2 Functions ................................. 8 6.2 Mat-Files ..................................... 9 6.3 Postscript Files . ................................. 9 6.4 Diary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 7 Plotting 10 7.1 Simple plotting commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 7.2 Customization of plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 8 Signals and Systems Commands 11 8.1 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 8.2 Laplace and Z Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 8.3 Frequency responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 8.4 Fourier transforms and filtering . . . . . . . . . . . . . . . . . . . . . . . . . 13 9 Examples of Usage 13 9.1 Find pole-zero diagram, bode diagram, step response from system function . 13 9.1.1 Simple solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 9.1.2 Customized solution . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 9.2 Locus of roots of a polynomial . . . . . . . . . . . . . . . . . . . . . . . . . . 16 9.3 Response of an LTI system to an input . . . . . . . . . . . . . . . . . . . . . 18 10 Acknowledgement 18 2
1 Introduction MATLAB is a programming language and data visualization software package which is es- pecially effective in signal processing and systems analysis. This document is a brief in- troduction to MAtLAB that focuses on those features that are of particular importance in 6.003. It is assumed that the reader is familiar with Project Athena, has an Athena account and has little or no experience with MATLAB. Other MATLAB help is available through Athena consulting which offers a number of more tutorial handouts and short courses(ext 3-4435 ), on-line consulting(type olc at the Athena prompt), and Athena on-line help(type help at the Athena prompt). There are a number of books available that describe MAT LAB. For example, Engineering Problem Solving with Matlab, by D. M. Etter, published by Prentice-Hall(1997) and Mastering MATLAB, by Hanselman and Littlefield, published by Prentice-Hall(1996). The paperback MATLAB Primer by K. Sigmon, published by CRC Press(1994)is a handy summary of MATLAB instructions. Further information about MATLAB can be found at the web page of the vendor(The Math Works, Inc ) whose URL ishttp://www.mathworks.com.FulldocumentationcanbepurchasedbycontactingThe Math Works 2 Getting Started On Project Athena, MATLAB can be accessed directly from the Dashboard(menu at the top of the screen after you login to Project Athena) by using the hierarchical menu and navigating as follows Numerical/ Math//Analysis and Plotting//MATLAB MATLAB will then open a command window which contains the MATLAB prompt>> MATLAB contains a number of useful commands that are similar to uniX commands g, 'ls,, 'pwd, and cd. These are handy for listing MATLAB's working directory, checking the path to the working directory, and changing the working directory. matlaB checks for MATLAB files in certain directories which are controlled by the command path. The command pathlists the directories in MATLAB's search path. A new directory can be appended or prepended to MATLAB's search path with the command path(path, p)or path(p, path) where p is some new directory, for example, containing functions written by the There is specially designed software available which can also be accessed from the project Athena Dashboard by navigating as follows Courseware//Electrical Engineering and Computer Science// 6.003 Signals and Systems //MATLAB These commands display a graphical user interface for exploring several important topics in 6.003. The same software is used in lecture demonstrations Revisions of this document will be posted on the 6.003 homepage on the web
1 Introduction MATLAB is a programming language and data visualization software package which is especially effective in signal processing and systems analysis. This document is a brief introduction to MATLAB that focuses on those features that are of particular importance in 6.003.1 It is assumed that the reader is familiar with Project Athena, has an Athena account, and has little or no experience with MATLAB. Other MATLAB help is available through Athena consulting which offers a number of more tutorial handouts and short courses (ext. 3-4435), on-line consulting (type olc at the Athena prompt), and Athena on-line help (type help at the Athena prompt). There are a number of books available that describe MATLAB. For example, Engineering Problem Solving with Matlab, by D. M. Etter, published by Prentice-Hall (1997) and Mastering MATLAB, by Hanselman and Littlefield, published by Prentice-Hall (1996). The paperback MATLAB Primer by K. Sigmon, published by CRC Press (1994) is a handy summary of MATLAB instructions. Further information about MATLAB can be found at the web page of the vendor (The MathWorks, Inc.) whose URL is http://www.mathworks.com. Full documentation can be purchased by contacting The MathWorks. 2 Getting Started On Project Athena, MATLAB can be accessed directly from the Dashboard (menu at the top of the screen after you login to Project Athena) by using the hierarchical menu and navigating as follows: Numerical/Math//Analysis and Plotting//MATLAB. MATLAB will then open a command window which contains the MATLAB prompt ‘>>’. MATLAB contains a number of useful commands that are similar to UNIX commands, e.g., ‘ls’, ‘pwd’, and ‘cd’. These are handy for listing MATLAB’s working directory, checking the path to the working directory, and changing the working directory. MATLAB checks for MATLAB files in certain directories which are controlled by the command ‘path’. The command ‘path’ lists the directories in MATLAB’s search path. A new directory can be appended or prepended to MATLAB’s search path with the command path(path,p) or path(p,path) where p is some new directory, for example, containing functions written by the user. There is specially designed software available which can also be accessed from the Project Athena Dashboard by navigating as follows: Courseware//Electrical Engineering and Computer Science// 6.003 Signals and Systems//MATLAB. These commands display a graphical user interface for exploring several important topics in 6.003. The same software is used in lecture demonstrations. 1Revisions of this document will be posted on the 6.003 homepage on the web. 3
3 Getting Help from Within MATLAB If you know the name of a function which you would like to learn how to use, use the help command > help functionname This command displays a description of the function and generally also includes a list of related functions. If you cannot remember the name of the function, use the lookfor' command and the name of some keyword associated with the function > lookfor keyword This command will display a list of functions that include the keyword in their descriptions Other help commands that you may find useful are ' info, what, andwhich. descrip- tions of these commands can be found by using the help command. MATLAB also contains a variety of demos that can be with the 'demo'command 4 MATLAB Variables- Scalars. Vectors, and matri ces MATLAB Stores variables in the form of matrices which are mxn where m is the number of rows and n the number of columns. a 1 x1 matrix is a scalar: a 1xn matrix is a row vector, and M xl matrix is a column vector. All elements of a matrix can be real or complex numbers;v-I can be written as either"i'orj' provided they are not redefined 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 >>x=5 Complex scalar >>x=5+10j(or >>x=5+101) [123]( Column vector >>x= [1; 2: 3] 3 matrix>>x=[123;456;789 There are a few notes of caution. Complex elements of a matrix should not be typed with spaces, i.e., -1+2j is fine 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 4.1 Complex number operations Some of the important operations on complex numbers are illustrated below
3 Getting Help from Within MATLAB If you know the name of a function which you would like to learn how to use, use the ‘help’ command: >> help functionname This command displays a description of the function and generally also includes a list of related functions. If you cannot remember the name of the function, use the ‘lookfor’ command and the name of some keyword associated with the function: >> lookfor keyword This command will display a list of functions that include the keyword in their descriptions. Other help commands that you may find useful are ‘info’, ‘what’, and ‘which’. Descriptions of these commands can be found by using the help command. MATLAB also contains a variety of demos that can be with the ‘demo’ command. 4 MATLAB Variables — Scalars, Vectors, and Matrices 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 M ×1 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 redefined 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 >> x = 5 Complex scalar >> x = 5+10j (or >> x = 5+10i) Row vector >> x = [1 2 3] (or x = [1, 2, 3]) Column vector >> x = [1; 2; 3] 3 × 3 matrix >> 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 fine 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’. 4.1 Complex number operations Some of the important operations on complex numbers are illustrated below 4
omp >>x=3+4 maginary part of IT > imag(x)=4 Magnitude of ar >>abs(x) →5 Angle of >> angle(x)=→0.9273 plex conjugate of >> conj(x) →3-4i 4.2 Generating vectors Vectors can be generated using the command. For example, to generate a vector a that takes on the values 0 to 10 in increments of 0.5, type the following which generates a 1 x 21 matrix Other ways to generate vectors include the commands: "linspace' which generates a vector by specifying the first and last number and the number of equally spaced entries between the first and last number, and"logspace' which is the same except that entries are spaced logarithmically between the first and last entry 4.3 Accessing vector ele ts Elements of a matrix are accessed by specifying the row and column. For example, in matrix specified by A=[1 2 3;456:789], the element in the first row and third column can be accessed by writing > x=A(1, 3)which yields 3 The entire second row can be accessed with 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 specified by >>z=A(1:2,1:3) which yields[123;456 5 Matrix Operations MATLAB contains a number of arithmetic, relational, and logical operations on matrices
Complex scalar >> x = 3+4j Real part of x >> real(x) =⇒ 3 Imaginary part of x >> imag(x) =⇒ 4 Magnitude of x >> abs(x) =⇒ 5 Angle of x >> angle(x) =⇒ 0.9273 Complex conjugate of x >> conj(x) =⇒ 3 - 4i 4.2 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 1 × 21 matrix >> x = [0:0.5:10]; Other ways to generate vectors include the commands: ‘linspace’ which generates a vector by specifying the first and last number and the number of equally spaced entries between the first and last number, and ‘logspace’ which is the same except that entries are spaced logarithmically between the first and last entry. 4.3 Accessing vector elements Elements of a matrix are accessed by specifying the row and column. For example, in the matrix specified by A = [1 2 3; 4 5 6; 7 8 9], the element in the first 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 specified by >> z = A(1:2,1:3) which yields [1 2 3; 4 5 6] 5 Matrix Operations MATLAB contains a number of arithmetic, relational, and logical operations on matrices. 5
5.1 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 An error message occurs if the sizes of matrices are incompatible for the operation. Division is defined as follows: The solution to A*r=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 mu tiplication and division do not. However, matlaB provides for element-by-element opera tions as well by prepending a. before the operator as follows multiplication right division left division exponentiation (power transpose(unconjugated) The difference between matrix multiplication and element-by-element multiplication is seen in the following example >>A=[12;34] 2 4 >>B=A*A 5.2 Relational operations The following relational operations are defined
5.1 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 An error message occurs if the sizes of matrices are incompatible for the operation. Division is defined 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 difference between matrix multiplication and element-by-element multiplication is seen in the following example >>A = [1 2; 3 4] A = 1 2 3 4 >>B=A*A B = 7 10 15 22 >>C=A.*A C = 1 4 9 16 5.2 Relational operations The following relational operations are defined: 6
less than = greater than or equal to not equal t 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==' 5.3 Flow control operations MATLAB contains the usual set of flow control structures, e.g., for, while, and if, plus the logical operators, e. g, &(and), I(or), and-(not) 5.4 Math functions MATLAB comes with a large number of built-in functions that operate on matrices on an element-by element basis. These include Sn coS tan Inverse sine atan inverse tangent exp exponential g natural logarithm log10 common logarith sart square root absolute value SIgn signum 6 MATLAB Files There are several types of MATLAB files including files that contain scripts of MATLAB commands, files that define user-created MATLAB functions that act just like built-in Mat LAB functions, files that include numerical results or plots
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 ‘==’. 5.3 Flow control operations MATLAB contains the usual set of flow control structures, e.g., for, while, and if, plus the logical operators, e.g., & (and), | (or), and ~ (not). 5.4 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 sine cos cosine tan tangent asin inverse sine acos inverse cosine atan inverse tangent exp exponential log natural logarithm log10 common logarithm sqrt square root abs absolute value sign signum 6 MATLAB Files There are several types of MATLAB files including files that contain scripts of MATLAB commands, files that define user-created MATLAB functions that act just like built-in MATLAB functions, files that include numerical results or plots. 7
6.1 M-Files MATLAB is an interpretive language, i.e., commands typed at the matlab prompt are interpreted within the scope of the current MATLAB session. However, it is tedious to type in long sequences of commands each time MATLAB is used to perform a task. There are two means of extending MATLAB's power -scripts and functions. Both make use of m-files (named because they have a. m extension and they are therefore also called dot-m files created with a text editor like emacs. The advantage of m-files is that commands are saved and can be easily modified without retyping the entire list of commands 6.1.1 Scripts MATLAB script files are sequences of commands typed with an editor and saved in an m-file To create an m-file using emacs, you can type from Athena prompt athena emacs filename. m or from within matlaB > emacs filename. m Note that"!' allows execution of UNIX commands directly. In the emacs editor, type MATLAB commands in the order of execution. The instructions are executed by typing the file name in the command window at the MATLAB prompt, i. e, the m-file filename.m executed by typing > filename Execution of the m-file is equivalent to typing the entire list of commands in the command window at the MATLAB prompt. All the variables used in the m-file are placed in MAT- LABs workspace. The workspace, which is empty when maTlab is initiated. contains al the variables defined in the matlab session 6.1.2 Functions A second type of m-file is a function file which is generated with an editor exactly as the script file but it has the following general form function Output 1, output 2]= functionname (input1, input2 % l Output 1, output 2]= functionname(input1, input2)Functionname Some comments that explain what the function does go here
6.1 M-Files MATLAB is an interpretive language, i.e., commands typed at the MATLAB prompt are interpreted within the scope of the current MATLAB session. However, it is tedious to type in long sequences of commands each time MATLAB is used to perform a task. There are two means of extending MATLAB’s power — scripts and functions. Both make use of m-files (named because they have a .m extension and they are therefore also called dot-m files) created with a text editor like emacs. The advantage of m-files is that commands are saved and can be easily modified without retyping the entire list of commands. 6.1.1 Scripts MATLAB script files are sequences of commands typed with an editor and saved in an m-file. To create an m-file using emacs, you can type from Athena prompt athena% emacs filename.m & or from within MATLAB >> ! emacs filename.m & Note that ‘!’ allows execution of UNIX commands directly. In the emacs editor, type MATLAB commands in the order of execution. The instructions are executed by typing the file name in the command window at the MATLAB prompt, i.e., the m-file filename.m is executed by typing >> filename Execution of the m-file is equivalent to typing the entire list of commands in the command window at the MATLAB prompt. All the variables used in the m-file are placed in MATLAB’s workspace. The workspace, which is empty when MATLAB is initiated, contains all the variables defined in the MATLAB session. 6.1.2 Functions A second type of m-file is a function file which is generated with an editor exactly as the script file but it has the following general form: function [output 1, output 2] = functionname(input1, input2) % %[output 1, output 2] = functionname(input1, input2) Functionname % % Some comments that explain what the function does go here. % 8
Matlab command 1 matlab command 2 Matlab command 3 The name of the m-file for this function is functionname. m and it is called from the MATLAB command line or from another m-file by the following command > Loutput1, output2]= functionname(input1, input2) Note that any text after the is ignored by matlab and can be used for comments Output typing is suppressed by terminating a line with;', a line can be extended by typing n at the end of the line and continuing the instructions to the next line 6.2 Mat-Files Mat-files(named because they have a. mat extension and they are therefore also called dot mat files) are compressed binary files used to store numerical results. These files can b used to save results that have been generated by a sequence of MATLAB instructions. For example, to save the values of the two variables, variable and variable2 in the file named filename. mat, type > save filename. mat variable1 variable2 Saving all the current variables in that file is achieved by typing > save filename, mat A mat-file can be loaded into MATLAB at some later time by typing > load filename(or load filename. mat) 6.3 Postscript Files Plots generated in MATLAB can be saved to a postscript file so that they can be printed at a later time(for example, by the standard UNIX ' lprcommand). For example, to save the current plot type int -dps filename. ps The plot can also be printed directly from within MATLAB by typing > print -Pp
MATLAB command 1; MATLAB command 2; MATLAB command 3; The name of the m-file for this function is functionname.m and it is called from the MATLAB command line or from another m-file by the following command >> [output1, output2] = functionname(input1, input2) Note that any text after the ‘%’ is ignored by MATLAB and can be used for comments. Output typing is suppressed by terminating a line with ‘;’, a line can be extended by typing ‘...’ at the end of the line and continuing the instructions to the next line. 6.2 Mat-Files Mat-files (named because they have a .mat extension and they are therefore also called dotmat files) are compressed binary files used to store numerical results. These files can be used to save results that have been generated by a sequence of MATLAB instructions. For example, to save the values of the two variables, variable1 and variable2 in the file named filename.mat, type >> save filename.mat variable1 variable2 Saving all the current variables in that file is achieved by typing >> save filename.mat A mat-file can be loaded into MATLAB at some later time by typing >> load filename (or load filename.mat) 6.3 Postscript Files Plots generated in MATLAB can be saved to a postscript file so that they can be printed at a later time (for example, by the standard UNIX ‘lpr’ command). For example, to save the current plot type >> print -dps filename.ps The plot can also be printed directly from within MATLAB by typing >> print -Pprintername 9
Figure 1: Example of the plotting of the function s(t)=te- cos(2T 4t) Type help print' to see additional options 6.4 Diary Files A written record of a MATLAB session can be kept with the diary command and saved in a diary file. To start recording a diary file during a matlab session and to save it in filename, ty > diary filename o end the recording of information and to close the file type > diary off 7 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); 7Define a vector of times from o to 8 s with 401 x= t *exp(-t)*cos(2*pi*4*t); 7Define a vector of x values plot(t, x) %Plot x1abel(Time(s)’); ZLabel time axis label('Amplitude) ZLabel amplitude axis This script yields the plot shown in Figure 1
Amplitude 0.4 0.3 0.2 0.1 0 Figure 1: Example of the plotting of the function x(t) = te−t -0.1 cos(2π4t). -0.2 -0.3 -0.4 0 1 2 3 4 5 6 7 8 Time (s) Type ‘help print’ to see additional options. 6.4 Diary Files A written record of a MATLAB session can be kept with the diary command and saved in a diary file. To start recording a diary file during a MATLAB session and to save it in filename, type >> diary filename To end the recording of information and to close the file type >> diary off 7 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 times from ... 0 to 8 s with 401 points x = t.*exp(-t).*cos(2*pi*4*t); %Define a vector of x values plot(t,x); %Plot x vs t xlabel(’Time (s)’); %Label time axis ylabel(’Amplitude’); %Label amplitude axis This script yields the plot shown in Figure 1. 10