Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming data type specification not required No pointers Interpreted language - commands are executed interactively Superb graphics provide excellent data visualization Toolboxes provide application specific functionality Recent support for structured programming classes structures cells 1
1.2 Example Uses of Matlab A few examples of how MATLAB is used in industry Signal generation Modeling and analysis of Digital Signal Processing systems Communications systems Complex mathematical computation Control Systems Modeling RADAR/SONAR simulation Financial Engineering many, many others 1.3 The MATLAB Windows Three Main Windows (see Figure 1.1): Main Window Opens when you start Matlab Divided into three panes: Command Most important area on screen: type commands at the command prompt (>> ) Workspace shows currently defined variables; may also be used to display contents of working directory. History Recently entered commands. Editor Allows you to edit Matlab programs. Opened via File New M-file, or via File Open for editing existing files. Figure Shows plots. New windows are opened with the figure command The result of the plot or similar commands appear in the active Figure window. 2
] Figure 1.1: The main Matlab windows 3
1.4 Getting Help help Online help for MATLAB functions and M-files Accessed via help command To get help on function named func, you would type help func, Try help help or help plot or help : doc Starts the Matlab documentation viewer in a separate window. Invoked by typing doc or by choosing Help MATLAB Help from the menu bar. Online, in-depth reference manual to all of Matlabs features and functions. Contains many demos. lookfor Searches the help documentation for the keyword provided Try lookfor inverse to find all functions that perform some form of inverse operation. Warning: this may take a while and find many more functions tham you expected. 1.5 Interacting with the File System The following commands allow you to change directories, view directory listings, or display the contents of files with the command window. cd change working directory The command cd directory where directory is the name of a directory, changes the working directory to the indicated directory Important: For Matlab to be able to find your own programs and functions, they must be stored in the working directory. Changing directories is more conveniently accomplished via the file-system browser near the top of the main window. 4
The command cd by itself prints the name of the current directory. So does the command pwd. dir list contents of working directory The command dir lists the names of the files in the working directory. So does the command ls. dir may be invoked with the name of a directory, to list the contents of that directory. This functionality is also available by selcting the current Directory view in the top left pane of the main window. type display the contents of a file. 1.6 Quit The command type filename displays the contents of the file filename. For large files, it may be useful to use the command more on. This displays the contents of the file one screen at a time; use the space bar to advance to the next page and the Enter-key to advance by one line. Press q to stop paging and return to the command prompt. Use more off to turn of paging. Alternatively, consider examining files in the editor. quit -terminates MATLAB session The command window and all other windows will disappear at the execution of this command. No example. (Class isn t over yet.) Beware! Using quit will not save the current workspace. 5
1.7 The Percent Sign The percent sign (%) starts a comment Comments can start at the beginning of a line or after a command. All text or commands on that line will be ignored. Unlike some other languages, the comment symbol does not need to be repeated at the end of the comment. This implies that comments spanning several lines must all be preceded by %. 1.8 diary Save session transcript to a disk file Syntax: diary diary filename diary off diary on Description: The diary command creates a log of keyboard input and system responses. The output of diary is an ASCII file, suitable for printing or for inclusion in reports and other documents. diary by itself, toggles diary mode on and off. diary filename writes a copy of all subsequent keyboard input and most of the resulting output (but not graphs) to the named file. If the file already exists, output is appended to the end of the file. diary off suspends the diary function. The function form diary( filename ) is also permitted. 6
Limitation: You cannot put a diary into the files named off or on. Examples: >> diary Test1 >> X = 44 >> Y = [4; 5; 6] >> diary off >> dir % Test1 is now in your working subdirectory - notice that there % is no file name extension. If you open the file Test1 in the editor, you should see: X = 44 X = 44 Y = [4; 5; 6] Y = 4 5 6 diary off Now close Test1 in the editor and go back to the command window. Type: >> diary Test1 >> A = 15:-2:1 >> diary off 7
This will append the above commands and resulting output to the end of file Test1. The contents of test1 will be: X = 44 X = 44 Y = [4; 5; 6] Y = 4 5 6 diary off A = 15:-2:1 A = 15 13 11 9 7 5 3 1 diary off 1.9 Variables MATLAB does not require any type declarations or dimension statements. When a new variable name is encountered, MATLAB automatically creates the variable and allocates the appropriate amount of storage. 8
If the variable already exists, MATLAB changes its contents and, if necessary, allocates new storage. For example: >> Number_of_Students = 25; creates a scalar variable named Number of Students and stores the value 25 in it. Variable names consist of a letter, followed by any number of letters, underscores or digits. Strive to use variable names that are meaningful! MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. The variables names A and a do not refer to the same variable. 1.10 ans The special variable ans contains the most recent answer. It is the default variable name. The variable ans is created automatically when no variable name is specified. For example: >> 2+2 will return ans = 4 9
1.11 who and whos The command who lists all currently used variables. The command whos provides additional information about variables, including their sizes, and whether they are complex valued. 1.12 The semicolon In MATLAB, the semicolon ; serves multiple important purposes. The semicolon is used to mark the end rows in vectors or matrices (see below). The semicolon can also be used to separate statements on the same line such as: >> Num_of_Students=50; Num_of_Teachers=1; Perhaps most importantly, it is used to suppress displaying the contents of a variable. This is extremely useful if the variable stores a long vector or a large matrix. Example: Num_of_Students=50 will cause Num_of_Students = to be displayed. In contrast 50 Num_of_Students=50; creates no output; the value 50 is still stored in the variable named Num of Students. 10
1.13 Vectors and Matrices MATLAB uses vectors and matrices as their primary type of variables. Scalars are simply special cases of matrices (of size 1 1). Column Vectors: are m 1 matrices, i.e., they consist of m rows and 1 column. Row Vectors: are 1 m matrices, i.e., they consist of 1 row and m columns. Matrices: are two-dimensional rectangular array of real or complex numbers. Matrices has hundreds of built-in functions to operate on matrices and vectors. This includes all functions you learned about in linear algebra, including dot products, determinants, matrix inverses, etc. 1.14 Storing values in vectors or matrices There are many ways to store values in a matrix or vector, including Using square brackets: elements of a matrix are specified directly; for example >> v = [2 4 7] produces a row vector with 3 elements: v = 2 4 7 Instead of spaces, commas (,) may be used to separate elements. >> v=[2, 4, 7] yields the exact same result. Be careful with expressions like >> [1+2 2-2 3] and 11
>> [1 +2 2-2 3] The above two statements produce two different vectors! Why? Prefer to use commas to separate elements The statement >> [11 12 13; 21 22 23] produces a 2 3 matrix; the semicolon separates the rows of the matrix. Matrices can be assembled from smaller matrices using square brackets; for example: >> A = [1 2 3 4]; >> B = [5 6 7 8]; >> C = [9 8 7 6 5 4 3 2]; >> D = [A B; C] How many rows and columns does D have? Note that for constructions like the one above the numbers of rows and columns of the matrices involved must be compatible. Using built-in functions: Matlab has many built-in functions for creating vectors or matrices, including ones creates arrays or matrices of all 1s. Examples: >> ones(2) ans = 1 1 1 1 >> ones(3,1) ans = 1 1 1 zeros Creates arrays or matrices of all zeros. Syntax is very similar to that for ones. 12
Used frequently to pre-allocate storage for large arrays; more efficient that incremental allocation of storage. wavread You may have seen yy=wavread(fileanme) for reading in the samples from the soundclip stored in file filename. Many other functions: Try magic(5), hadamard(4), eye(5), rand(4), or many others. See also help elmat. Via the colon (:) operator: The colon operator is one of the most useful operators in MATLAB. Here we focus on creating vectors with equally spaced elements. The colon operator is also extremely useful for refering to specific elements of a vector or matrix (see below.) The following creates a vector of evenly spaced elements, starting at 1, ending at 2, the difference between consecutive elements is 0.1 xx = 1:0.1:2 xx = 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 The middle element (i.e., the increment) may be omitted; then the default increment of 1 is used: yy = 1:10 yy = 1 2 3 4 5 6 7 8 9 10 A very frequently used idiom in MATLAB is: fs = 8000; % number of samples per second tt = 0:1/fs:2; % define a time axis starting at 0 and ending at 2 % seconds xx = 2*cos(2*pi*500*tt + pi/2); % sinusoid, amplitude 2, frequency % 500~Hz, phase pi/2 13
1.15 Transpose and Single Quote Use the single quote ( ) after a variable to turn row vectors into column vectors and column vectors into row vectors. Works with matrices as well, columns become rows and rows become columns. >> A = [1 1 1 1; 2 2 2 2; 3 3 3 3; 4 4 4 4] A = 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 >> A ans = 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 In addition, the single quote is used to create strings. Single quotes on either side of text creates a string of the characters inside the quotes. 14
1.16 Parentheses As usual, parentheses can be used to indicate precedence in arithmetic expressions. Examples: >> B = (5+6) - (4-1) returns B = 8 >> C = 5+(6-4)-1 returns C = 6 They are also used to enclose arguments of functions; will be covered later. Parentheses are used to refer to individual elements of a matrix or vector. For example X(3) denotes the tird element of vector X. Let >> L = [16 2 3 13; 5 11 10 8; 9 7 6 12; 4 14 15 1] then L(4,2) is the element of L in the fourth row and the second column. Here L(4,2) is 14. Refering to elements that are outside a matrix produces an error: 15
>> T = L(4, 5) Index exceeds matrix dimensions Using the colon operator or square brackets, it is possible to refer to a range of elements in a matrix or vector. X([1 2 3]) creates a vector consisting of the first three elements of X. L(1,:) extracts the first row of the matrix L. Similarly, L(:,1:2) extracts the first two columns of L. 1.17 Array Dimensions The commands size and length can be used to find the number of elements of a matrix or vector. size(x) returns a vector containing the number of rows and columns in vector X. For vectors, the function length returns the number of elements in the vector. 16