Lab 1: Introduction to MATLAB (Part I)∗ EE299 Winter 2008 Due: In lab, on or before 17 January 2008. You will need: a pair of headphones for listening to sound signals. Objective The purpose of this lab is to teach you some of the basics of using MATLAB, a popular software package that is used in many engineering courses and that we will be using for the EE299 labs. It is NOT a comprehensive or general introduction to MATLAB—there are plenty of good references for that (see the class web page for links to a few). We will focus on how to use MATLAB for manipulating and modifying sounds and images. The four sections of the lab cover: • Getting started with MATLAB, using it interactively; • The concept of a variable, including vector and matrix array variables and how to create, modify and access elements of the arrays; • Representing sound signals as vectors, including loading, plotting and playing them; and • Representing images as matrices, including loading, modifying and displaying them. We will cover more MATLAB basics in Lab 1, including writing functions and scripts. Throughout this lab are short exercises that check your understanding of the material. Take notes as you go – your TA will go over the questions and demonstrations with you at the end of the lab. PreLab Review the document “Using MATLAB for EE students” for information about using MATLAB in the EE computer labs, creating and saving files and folders, and cleaning up. See the link on the class webpage or go to: http://ssli.ee.washington.edu/courses/ee299/EEUsingMATLAB.html. Learn two ways to get help in MATLAB: 1) via the ’help’ menu at the top of the window (organized by topic), and 2) by typing >> help command when you know the name of a particular command and want to look up how to use it or details about what it does. (Note that >> is the prompt in MATLAB, and this font is used to indicate something specific that you type to MATLAB.) Familiarize yourself the following sections from the “Getting Started” pages of the MathWorks Online MATLAB Tutorial: Introduction, Matrices and Arrays, and Graphics. Again, you can use the link on the class webpage, or go to: http://www.mathworks.com/access/helpdesk/help/techdoc/learn matlab/, or just use the MATLAB help function. You don’t need to know all of the material covered here – the point is to get a sense of what you can do with MATLAB and to know where to look for more information when you are ready for it. ∗Portions of this document have been adapted from the 2006 HKN Matlab tutorial. 1 1 Using MATLAB Open MATLAB. On a windows machine in the EE computer lab, click on: Start > EE programs > MATLAB # where # is the release number (e.g. 7.1). Figure 1 shows what your screen should look like when MATLAB is first opened. The primary areas of interest are described briefly below. Figure 1: This is what it should look like when you first open it. Current Directory: This area shows you all files and folders in the “current” folder/directory seen by MATLAB. When you make your own MATLAB files, it’s a good idea to make sure they are in the current directory. If you keep them in a different folder MATLAB may not be able to find them when you try to run them. You can always change the current directory using the directory pull-down menu. This is described more in the “Using MATLAB for EE Students” document. Workspace: This area (which you can access by clicking the tab located under the “Current Directory” area) shows you a list of all variables being used. We discuss variables in the next section. 2 Command Window: This area allows you to enter commands which will be executed immediately af- ter pressing ENTER. A command is basically an instruction to MATLAB telling it what you want it to do. Each command is automatically proceeded with a >> (or in the Student Edition, a EDU>). Try typing 4+4 and press ENTER—you should see ans=8. The Command History window will show the list of commands you typed into the Command Win- dow during this session. You can re-enter previous commands by using the “up” key. Try typing clc. This gives you a blank command window but doesn’t clear your history. In the next three sections we will work with MATLAB by entering commands in the Command Window. Each command is done (executed) by MATLAB as soon as you hit ENTER. (Another way to use MATLAB, which we’ll cover in Lab 1, is to save all your commands in an M-file and have MATLAB run them in sequence as in a computer program.) 2 Variables A variable is like a named storage container. Variables can store numbers, set of numbers, and other things like vectors and matrices, which we’ll learn about later. The following command creates a variable called “bob” and stores in it (or assigns it) the value 3: >> bob=3 A variable in MATLAB can have any name you want, made up of letters, numbers, and underscore ( ), as long as it starts with a letter. Variables are a general programming concept. If you are familiar with other programming languages like C or Java, you know you need to “declare” variables before assigning values to them, but in MATLAB you do not. As soon as you type bob=3, the variable bob gets created with the value 3. You can later re-assign to bob a different value, in which case the previous value gets overwritten. Type the command: a=bob+4. MATLAB will print: a=7. The statement a=bob+4 does two things: (1) performs the calculation bob+4, which in this case is 3+4 (2) creates the variable a (if it does not yet exist) and assigns to it the result of 3+4 You can store a new value in the variable a just by assigning it again. Exercise 1: After the command a=bob+4, type the command >> a=a+2 What value does the variable a have now? Why? As you start to work on more interesting problems, you will be using many variables. You can view your list of variables (names, current values, and classes) in the Workspace, or by typing >> whos. Some good things to know about variables in MATLAB: • When you enter a value but do not assign it to anything, MATLAB assigns it to a “default” variable called ans. This is why >> 4+4 results in MATLAB printing ans=8. • Certain values are already assigned (“built-in”) to MATLAB—for example, a truncated version of pi is contained in the variable pi. • When you quit MATLAB, all variable assignments go away. If you want to clear the values while you are still in MATLAB, type clear. If you want to clear only certain ones, types clear variable names. 3 2.1 Arrays, Vectors, and Matrices In the above example, we just used the variable bob to store a single value. However, in MATLAB every variable is actually viewed as an array—a table of values. An array can have any number of dimensions–see Figure 2 for some illustrations. In these examples, there are three variables (A, B, and C) which are storing arrays of 1, 2, and 3 dimensions respectively. Each single number in an array is called an element of the array. We will be representing signals with two kinds of arrays: vectors and matrices: • A vector is a 1-dimensional array, so it is basically a list of numbers. The length of the vector tells you how many elements it has. In the example in Figure 2, A is a vector of length 8. • A matrix is a 2-dimensional array, so it is a rectangular arrangement of numbers. It can have any number of rows and columns; in Figure 2, B is a 5-by-5 matrix. 6 7 14.2 3 100 -1 -0.2 9 6 6 6 6 100 100 100 14.2 14.2 14.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 3 33 3 3 3 3 0 09 di m en si on 1 dimension 1 di m en si on 1 dimension 2 dimension 2 dime nsion 3 Figure 2: Some examples of MATLAB arrays. Variable A stores a vector, a 1-dimensional array. Variable B stores a matrix, a 2-dimensional array (note that a matrix does NOT need to have the same number of rows and columns). Variable C stores a 3-dimensional array. Specific elements of the array are accessed by indicating the subscript in parentheses, as shown. As shown in the figure, you can access individual elements using the variable name followed by the particular element’s subscript, in parentheses. You can think of a subscript as the “address” for an element in the array. The subscript is a series of numbers, one for each dimension, separated by commas. Note that unlike in some other programming languages, in MATLAB the first element of an array has index 1, not 0 (and the top left element of a matrix has subscript (1,1), not (0,0)). You can access multiple elements by including a list (via the : operator) in the location for a particular dimension, e.g. B(1:5,3) gives the third column of B and B(1,2:3) gives the second and third elements of the first row. 4 A vector is a special case of a matrix with only 1 row or column, e.g. the vector A in Figure 2 is a 1-by-7 matrix. So, you can use matrix functions and subscripts on vectors, but it is more convenient to use a single index, so A(7) gives the same answer as A(1,7) for the vector in Figure 2. 2.2 Creating Vectors and Matrices Type the following to create two vectors and a matrix stored in the variables vect1, vect2 and a: >> vect1=[1 4 3 -2 1] = [1, 4, 3, -2, 1] >> vect2=[6; 7; 8; 9; 10] >> a=[1,2,1; 2,3,4; 2,1,2] The semicolon is used to indicate the end of a row, and either a space or a comma can be used to separate elements in a row. Note that vect1 is a row vector because the numbers are arranged in a row, whereas vect2 is a column vector because the numbers are arranged in a column. You can use length to get the length of a vector (row or column), and size to get the dimension of an array. You can convert a row vector to a column vector and visa versa using the transpose operation (.’). Try typing >> vect1=vect1.’ to make vect1 into a column vector. The transpose operation is useful because certain functions require vectors to be column (or row) vectors. For example, the function for playing sound- files, sound, requires a column vector. Transpose also works for matrices. Exercise 2: Explain the results you get when you type the commands: >> vect1(2)=vect1(3) >> size(vect2) 2.3 Arithmetic with Arrays If you have two arrays of the same size, you can add them element-by-element. For example, make the matrix a above again if you have cleared or reassigned it, and add this to a new matrix b >> b=[0.5, -0.5, 0.5; 1 -1 1; 0.5, -0.5, 0.5] >> c=a+b Observe that each element in c is the sum of the corresponding elements in a and b. (Note that a row and column vector of the same length do not have the same array size, so they can’t be added without transposing one of them.) You can also perform other element-by-element operations between two arrays of the same size, such as: subtraction: a-b multiplication: a.*b division: a./b powers: a.^b Note that it is important to use the . (e.g. .* instead of *) for element-by-element operations; otherwise, it is interpreted differently (as a matrix operation, which we’ll learn about later). You can also do all of the above operations with a scalar and an array, in which case the scalar operates separately on every element of the array. Exercise 3: Write the (one line) commands to do the following: (a) Create a 5-element column vector sumvect whose elements are the sums of the elements in [1 1 0 -1 3] and vect2 (b) Create a 3-by-3 matrix a2 formed by adding 2 to each element in a. 5 3 Sounds You can represent a digital mono sound signal in MATLAB using a vector. (For a stereo sound signal, you need two vectors, one for each side). You can edit and modify the vector in order to change the sound. The vectors in the example above were really short—only 5 elements. However, even a really short sound signal requires a very long vector. For example, suppose we wanted to represent a 3-second recording of a sound by sampling the sound (recording a value) once every 2 ms (you will learn more about sampling in week 2). This means we are recording 500 numbers every second, so if we did it for 3 seconds we would need a vector of length 1,500 to represent all the numbers in MATLAB. Fortunately, MATLAB can handle fairly big vectors. MATLAB has some sound signals already built in, which we will use for this lab. You will need your headphones for this part. To load and play one of these sounds (a clip from Handel’s Messiah), type >> load handel >> sound(y,Fs) The command loads a variable y, which contains a vector of 73,113 elements. This song is about 9 seconds long, with 8192 samples each second (the sampling rate is stored in the variable Fs1.) Recall that you can specify a part of a vector using a range of indices with the colon operator. Play the first 1/3 of the recording by typing: >> L=length(y) >> sound(y(1:L/3),Fs) The first line assigns to the variable L the length of the vector y, and y(1:L/3) is a vector containing elements from the first third of the vector y. (Note that you could do this in one line with sound(y(1:length(y)/3),Fs).) Exercise 4: Play the last half of the recording. Show your TA the command that you used to do this. You can plot the signal with: plot(y). This plots the values of the elements in the vector y on the vertical axis, and the index of elements on the horizontal axis. Note from the plot that the signal ranges between about ±0.8. You can modify the plot using the tools at the top of the plot figure, or by using various commands in MATLAB (see help plot if you want to learn about these commands.) You can zoom in on parts of the signal using the magnifying glass tool, and you can also add titles and axis labels to the plot under the “Insert” pull-down menu. You’ll get more comfortable working with plots as the course goes on. Exercise 5: Add a title to the plot, using either the “Insert” pull-down menu or the command title(‘your title’). Print out the plot. 4 Images A digital image is composed of a grid of tiny squares, called pixels, where each square gets displayed as one color. To store an image you must store the color of each pixel. In MATLAB there are three ways that images are represented, all using matrices: 1. A black-and-white image (of size l-by-w) can be represented by a l-by-w matrix, where the value of each element in the matrix represents the intensity (gray level) of the corresponding image pixel. 2. A color image (or black-and-white) can be represented by a l-by-w matrix, where the value of each element in the matrix is an index that indicates the color (or gray level) in association with a color map. For example, if element (3,4) has value 1, and the first color listed in the colormap is orange, then pixel (3,4) will be displayed as orange. 1The sampling rate is necessary to play the samples back. We’ll discuss sampling more in the sound modification lab. 6 3. A color image can be represented by an array of size l-by-w-by-3, composed of 3 l-by-w “color planes” for red, green and blue components. We will talk more about color later on in the course. In this lab, we will work with black-and-white images. MATLAB has some images built in; we will use one of these for these section. Load and view the image (a digital version of a painting by Durer) with: >> load durer >> colormap(‘gray’) >> imagesc(X) The image is automatically stored in the variable X. The second command sets the “map” that tells MAT- LAB what color goes with each value in the matrix. The ‘gray’ map will cause MATLAB to display the image in black-and-white. You can check the size of the image by typing size(X). Exercise 7: You can pull out part of the images by specifying the range of rows and the range of columns. Create a new variable Y that holds rows 410 through 530 and columns 80 through 160 of the Durer image. Describe which object in the original image is in the subimage Y. Once you start doing operations on large vectors and matrices (as we will for soundfiles and images), you will want to take advantage of the mechanism for suppressing the MATLAB output to the command window: use a semicolon (‘;’) after each command. For example, >> a=4+4; would still assign the value 8 to the variable a, but it would not print a=8 in the Command Window (you can see the value of ‘a’ by typing a, or by looking in your Workspace). We will make use of this in the example and exercise to follow. As described in Section 2.3, MATLAB makes it very easy to modify all the elements in an array at once. For example, assuming X contains the Durer image you loaded previously, we can create and view an inverted version of the image by forming a new matrix as follows: >> Z=-X; >> figure >> colormap(‘gray’) >> imagesc(Z) The figure command pops up a new window so you can keep the original image on the screen and view them side-by-side. Since it is a new window, you need to specify the colormap again or you will get an unexpected result! Exercise 8: Create and display two new images based on the Durer image, with modifications to a small part of the image only: >> Z=X; W=X; >> Z(410:530,80:160)=X(410:530,80:160)-50; >> W(410:530,80:160)=2.*X(410:530,80:160); Describe the effect of these operations on the image. 7