EE 350L: Signals and Transforms Lab Spring 2007 Lab #1 - Introduction to MATLAB Lab Handout Matlab Software: Matlab will be the analytical tool used in the signals lab. The laboratory has network licenses for all students. However, it is recommended that if you have a laptop, have a valid licensed copy of Matlab, and wish to bring it to class this is acceptable. The network can be a little slow with all the users on at the same time. NOTE: Data will be lost if the network connection is lost. Therefore, it is recommended that you SAVE OFTEN. Matlab GUI Interface: Three windows appear when Matlab starts; workspace, command, and command history. Additionally, the current directory path is displayed. NOTE: If you try to execute an M-File (discussed later) that you know exists and it cannot find it, check to make sure the path is correct. Workspace Window: The workspace window displays all variables that are currently stored in memory. These variables can be created by reading in a file, created at the command line, or from within an M-File. The size of the variable is displayed and can come in handy when you get a data size mismatch. (This generally occurs by starting at index 0 rather than 1). In order to view or directly edit the contents of a variable, you can double click on the variable and it will open into a spreadsheet for manipulation. Most editing however, will be performed at the command prompt in the command window. Command Window: This window is where most user interaction occurs. It provides the means to execute single lines of instructions, execute M-File scripts, view variable data, etc. Command History Window: This window simply keeps a listing of the most recent commands. It is helpful to see what has been executed to identify the next line of code to execute, and also helps if syntax is a problem. Data Manipulation: Variable assignment: 1 1; [5 7] Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window. Does the same as above, but does not print the matrix aaa. In general, the semicolon at the end of a line causes the printing of the left hand side variable to the command window to be suppressed. Creates a 1 X 2 matrix with a value of 5 in the column 1, row 1 position and a value of 7 in the column 2, row 1 position (and prints it to the command window since there is no semicolon at the end of the line). Note that if the assignment 1 was followed by the assignment [5 7], the original scalar would be written over and lost. [1] This is the same as the first example ( 1). [5; 7] Creates a 2 X 1 matrix with a value of 5 in the column 1, row 1 position and a value of 7 in the column 1, row 2 position. A semicolon between square brackets tells MATLAB to start a new row in the matrix. The semicolon here does not suppress printing to the command window since it is not at the end of the line. bbb = [1 2 3; 4 5 6] Creates a 2 X 3 matrix. MATLAB will print the created matrix to the command window in the following format:
1 2 3 4 5 6 1:10 1:2:10 Creates a 1 X 10 matrix with 1 in the first column, 2 in the second column,, 10 in the tenth column. Creates a 1 X 5 matrix with elements starting at 1, increasing by 2 each step, and with final element less that or equal to 10: 1 3 5 7 9 1:1:10 This is the same as 1:10. 3:-1:1 Creates a 1 X 3 matrix as follows: 3 2 1 Complex numbers: j = sqrt(-1) a = 3 + 2*j Creates a matrix j which is a scalar equal to the square root of minus one. This command is not really necessary since j is defined as the square root of minus one on startup (although you could subsequently set it to something else if you wanted). The matrix i is also set to sqrt(-1) on startup. Creates a matrix a which is a scalar which has a complex value (i. e., has a nonzero imaginary part). b = [4-2*j 3-2*j] Creates a 1 X 2 matrix b whose two elements are both complex. Note that you should not have any spaces in the definition of any one element or MATLAB will interpret the definition as more than one element (i. e., do not put any spaces in 4-2*j). c = a * b Creates a 1 X 2 matrix c whose elements are as below. Note that a and the second element of b are complex conjugates and therefore multiply to a real value. c = 16+2*j 13 Matrix operations: aaa.' aaa' (1:3).' Transposes the matrix aaa (i. e., puts the value from the nth row and m th column of the original matrix into the m th row and n th column of the new matrix). Takes the complex conjugate transpose of the matrix aaa (i. e., transposes the matrix as above, but also multiplies the imaginary part of each element by minus one). Note that if all of the elements of the matrix are real, it does not matter whether you put the dot before the quote character or not. However, it is good programming practice to use the dot if you want a simple transpose and not a complex conjugate transpose, even if you expect all the elements to be real. Creates a 3 X 1 matrix as follows: 1 2 3
1:3.' size(aaa) length(aaa) aaa(2) bbb(2,1) Creates a 1 X 3 matrix. In this case the scalar 3 has been transposed, not the 1 X 3 matrix. Since the transpose of any scalar is itself, the net effect is the same as if the dot and quote character had been omitted. Query MATLAB about the number of rows and columns in the specified variable. Query MATLAB about the length of a vector. This is designed for vectors not matrices. For a matrix it will return the number of rows in the specified variable. accesses the second element in the array accesses the element of the matrix that is in the second row, first column. Math functions: t = 1:3 y = t.^2 t = 1:3 y = t.*t t = 1:3 y = t * t.' t = 0:0.1:8 y = sin(t) Creates a 1X 3 matrix y, where each element is the square of the corresponding element of the matrix t (i. e., the elements of y are 1, 4, 9). The dot before a mathematical operator means to do the scalar operation (element-by-element). Excluding the dot means to do the matrix operation. In this example, excluding the dot would be an error, since MATLAB would try to take the product of the matrix t with the matrix t (which is not possible since t is not a square matrix). Creates a 1 X 3 matrix y which is identical to the matrix in the preceding example. This is an element-by-element multiplication because of the dot before the star. Creates a scalar y which is the inner product of the vector t with itself. In this example the value of the scalar will be 14. This is a matrix multiplication because there is no dot before the star. Creates a 1 X41 matrix y, where the elements contain slightly more than one cycle of a sine function. Note that trig functions are expressed in radians by default in MATLAB. Displaying Data: Plotting (Single Window): In this section, assume that the matrix t has already been using t = 0:0.1:8 and that the matrix y has already been created using y = sin(t). plot(t,y, r: ) Generates a plot of the values in the matrix y versus the values in the matrix t. The t values will appear on the horizontal axis and the y values on the vertical axis. This plot will appear in its own window. Generates the same plot as above, except that the curve will be a red dotted line. title( Sine Wave Plot ) xlabel( Time (sec) ) Causes the title Sine Wave Plot to be printed above the plot. Causes the label Time (sec) to be printed below the horizontal axis of the plot. title( this is a greek letter pi: \pi ) title( my plot x_{10}^2 ) You can use Subscripts, superscripts and Greek letters in your titles & labels by using the LaTex character formats. See http://www.giss.nasa.gov/latex/ltx-405.html for examples figure Creates a new plot window figure(3) Creates or activates plot window #3.
print figure(2) plot(t,y, r: ) print Sends a copy of the plot to the printer. Note that this plot will not have any title or x-axis label since there is no title or xlabel command between the plot and print command. A new plot command resets all the attributes like title and xlabel to the defaults (i.e. none). Generates a plot using default color and line type (solid blue line) in the default plot window (called figure 1). Generates a plot with a red dotted curve in a second plot window (called figure 2). Prints the plot with the dotted red line. The fig(2) command sets the active plot window to be the figure 2 plot window. All subsequent plot commands affect the figure 2 plot window until another fig( ) command is given. Other commands: matrix1 = pi save lab1.mat load lab1.mat Creates a scalar matrix with value 3.141592.. Creates a machine readable file called lab1.mat with the values of all the currently defined matrices. By default this file appears in the work directory. Creates matrices will values the same as those saved in the file lab1.mat. This is useful if you must leave the computer in the middle of an assignment and do not want to type the data back into all the matrices when you start again. [4-2*j 3-2*j] bbb = exp(aaa) [4-2*j 3-2*j] bbb = abs(aaa) [0.5 3.2] bbb = atan(aaa) [-0.5 3.2] bbb = [-1 1] ccc = atan2(aaa,bbb) stem(t,y) Creates a 1 X 2 matrix bbb with each element equal to the complex exponential of the corresponding element of aaa. Creates a 1 X 2 matrix bbb with each element equal to the magnitude of the corresponding complex element of aaa. The first element of bbb would be equal to the square root of 20 in this example. Creates a 1 X 2 matrix bbb with each element equal to the arctangent of the corresponding element of aaa. The value returned is in radians and is always between minus pi/2 and pi/2. Creates a 1 X 2 matrix ccc with each element equal to the arctangent of the corresponding element of aaa divided by bbb. In this example, the second element of ccc is identical to the second element of bbb in the example above. However, the first element of ccc is in the third quadrant, whereas the first element in the previous example was in the first quadrant. The values returned by atan2 can be anywhere between minus pi and pi. Works just like the plot command except that the plot created will have a vertical line at each value rather than a smooth curve. This is useful if you have discrete time data. [4-2*j 3-2*j] Creates a 1 X 2 matrix bbb with each element a real value corresponding to the bbb = real(aaa) real part of the value in matrix aaa. In this example, the first element of bbb is 4. [4-2*j 3-2*j] Creates a 1 X 2 matrix bbb with each element a real value corresponding to the bbb = imag(aaa) imaginary part of the value in matrix aaa. In this example, the first element of bbb is 2. [5 6 7 8] bbb= (aaa>6.5) Creates a 1 X 2 matrix bbb with ones where the statement is true and zeros elsewhere. In this example, the values would be: bbb = 0 0 1 1 bbb = find(aaa > 6.5) Returns the array indices where the argument is true bbb = 3 4
aaa(bbb) accesses the locations returned in the previous find command ans = 7 8 clear HOME format short format long Clear variables and functions from memory. HOME moves the cursor to the upper left corner of the Command Window and clears the visible portion of the window. You can use the scroll bar to see what was on the screen previously. sets numeric display to five digits sets numeric display to 16 digits addpath (directoryname) prepends the path to the Matlab search path. NOTE: We have not covered every possible command. As you encounter a new command and need to know its functionality and syntax you can access that information directly from Matlab. help Gives online help for a list of topics. help plot Gives help for the plot command. Other commands you might want to investigate with the help command: flipup, fliplr, ones, zeros, roots, angle, bode, grid, legend, subplot, axis, hold, clear, clf Functions: Functions are a special type of m-file. They can take an input and return an output. Variables manipulated inside the function are not available outside the function. Functions may be written using any text editor in a file with extension m (e. g., lab1func.m). The prefix to the filename should match the function name. The first line of a function should be a comment and therefore should begin with %. If you type help lab1func, you will get the text after the % in the first line (and any following lines that start with % until a line not starting with a % is reached). The first non-comment line of the file should read something like: function y = lab1func(x) Subsequent lines can do any valid MATLAB commands, but should at some point assign a value to y. Once the function file has been written, it can be called with syntax such as matrix1 = lab1func(5). In this case the function was passed a 1 X 1 matrix with element 5 and the function will return a matrix called matrix1 with the same value as computed for y in the function file. Functions can contain if then clauses, for example: Demos: % find the absolute value of a scalar function y = lab1func(x) y = x; if x < 0 y = -x; end
demo returns a list of demonstration programs. Explore some of the demo programs to see the power of Matlab. Creating an Executable Script M-files or Scripts: Scripts are text files that contain a list of MATLAB commands you wish to execute. You can create m-file scripts using any word processor so long as you save the file with the file name filename.m and save it in text format. MATLAB comes with a convenient m-file editor which you can access by pressing the blank sheet of paper icon on the MATLAB toolbar. This brings up an editor which color codes reserved words and other program elements. The content of an m-file script would be the same set of MATLAB commands you would type at the MATLAB prompt, but they would get executed only when you type the script filename (without the.m) at the MATLAB prompt. Scripts are particularly useful if you want to be able to edit a sequence of steps and run them again without typing the whole list again. You can add comments to a script by beginning the line with %. Any text after a % will show up in the m-file but will not be executed. To run the m-file, you need to add its directory to the working path. You can do this in two ways: addpath( c:/my documents/my directory ) adds the given directory to your path cd c:/my documents/my directory changes the working directory and this becomes the first place MATLAB will look for a file Saving a MATLAB session to a file: diary lab1.txt diary off All subsequent commands and command window output will be also written to the file lab1.txt which may latter be printed. By default, this file will be put in the work directory under the MATLAB directory (the MATLAB directory may not be called matlab ). You should change directories before calling diary. Stops writing to the file. NOTE: Diary files will not be accepted for weekly lab write-ups.
Plot the following for t from 0 to 10 in 0.1 steps y1=5sin(2t) y2=2cos(t+π/4) EE 350L: Signals and Transforms Lab Spring 2006 Introduction to MATLAB Quiz on the same set of axis with different colors and marker types. Label all axis and add a title to include your initials. Submit this via email in text form only. SOLUTION: t=0:0.1:10; y1 =5*cos(2*t); y2 =2*cos(t-pi/4); figure(1); plot(t,y1); plot(t,y2); title('solution: y1 = 5*cos(2*t) and y2 = 2*cos(t+\pi/4 ) xlabel('time'); ylabel('magnitude')