You are on page 1of 14

MATLAB TUTORIAL INTRODUCTION TO MATLAB

Page 1 of 14

Matlab (Short for matrix laboratory) is a programming language based on a powerful set of matrix and vector processing algorithms. It is a high level language that can be used interactively to execute command line instructions or the instructions can conveniently be put into scripts using any ascii editor. Matlab also permits users to write and define there own functions. Collections of highly specialized functions called "toolboxes" have proliferated over the last few years. This permits users in specialized areas to have a large array of convenient functions available that can significant reduce the work needed to program computer solutions to difficult engineering problems. Matlab can handle very large arrays of data with ease. These arrays of data be manipulated or plotted using a large variety of formats. Matlab has a rich collection of complex graphics capabilities that are helpful to even the most sophisticated users. Matlab requires a very modest effort to learn and once the basic elements are understood, the user will find that very large and complex problems can be solved quickly. Because Matlab is also available for most workstations, it easy to transport code between Pentium-based PCs and many workstation platforms. Matlab is also available for MacIntosh and Apple power PCs although the percentage of users in this market is minuscule when compared with IBM clone users and it is not as well supported. GETTING STARTED: SIMPLE COMMANDS When you start Matlab you will get a command window in which to enter your commands. The newest versions of Matlab may add additional windows that may be tiled with the Matlab command window. Just simply use the mouse to close these. They will not be of any value in this tutorial and will just make your type smaller and harder to read. Once you have your command window up you are ready to try out Matlab commands. You will find that you will learn Matlab easily if you try it out on a computer. You will not learn Matlab by memorizing commands out of notes or a book! It helpful to remember that all data objects in Matlab are usually in vector (a single row or column) or matrix form. We will start by showing how to define variables that represent vectors or matrices. The names of variables in Matlab are case sensitive and can be named anything but only the first 19 symbols in a long name will be identify an object. All names must begin with a letter but other symbols (e.g. underscores and numbers) can be used after the first letter in a name. It is a good idea not to use standard Matlab function names or keywords this can create problems and has side effects. Function names and Matlab commands are case sensitive also (they must be lower case). Some users always make the first letter of a variable name upper case to avoid conflicts with functions. Matlab gives some variables default values. For example, i and j are considered to be the square root of -1 unless the user defines them otherwise. The variable pi is understood to be the transcendental number B (i.e. 3.14159 ...) unless redefined by the user. With these points in mind lets get on the computer and give Matlab a test drive. The prompt >> is your invitation to enter commands. Lets start out with a very simple addition command, type: 1+1 followed by an enter key. Matlab requires an enter key after all commands. Note that Matlab responds with

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL ans = 2

Page 2 of 14

This is of course the sum of 1 and 1. Matlab stores results of operations that are not stored as variables in the generic variable "ans". You may wish to try out other pairs of number (i.e. binary) operations at this point using other operators such as the - for subtraction, the * for multiplication and the slashes, / or \. for division. For example see what happens in the following cases: 5-8 2*3 6/2 6\2 Notice that the choice of the slash or backslash makes a difference. The slash divides the number on the right by the number on the left. The backslash reverses the order of the operation. The slashes also have special significance matrix operations as we shall see. Now lets consider using variables in our operations. Type: a=2 followed by an enter key. Notice that Matlab responds with: a= 2 Matlab has stored the value 2 in the variable "a". It indicates the result of the = command by printing the a = 2 result. Note that the generic variable "ans" is not part of the output. Since the equal sign makes the variable a the output. Matlab will always print some output unless you put a semicolon (i.e. ;) after the command to indicate that you don't want any output. To see how the semicolon works try: a = 2; After you type the enter key in this case nothing happens. The output has been suppressed. This comes in handy when you don't need to see intermediate results in long calculations.

Now lets try defining a row vector. Type: a = [ 2, 4 ,4 ,4,7,9] Now "a" has been redefined a row vector. The brackets let Matlab know that you are defining a Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 3 of 14

matrix. The elements in this matrix may be separated by commas or by spaces. Now lets make the row vector into a column vector. Type b = a' Note that the quote is an important little mark. It defines the transpose operation. In a transpose operation the rows and the columns of a matrix are interchanged. Note that Matlab responds with a matrix b that is now defined as a column vector. Now lets try a matrix operation. c=a*b Note that the answer c is single number the result of a matrix multiplication. This is, of course, the inner (or scalar) product. Now try reversing the order of the variables in the product: d=b*a Now the result is a matrix, the outer product. (If you dont know what an outer product is, it's time to dust off your algebra book and check it out!) Keeping Scripts and Exercises As you go through this tutorial you will be asked to carry out some exercises that will help you to understand some of the fine points. It is a good to save these exercises in Matlab scripts. A script is just a plain text file of Matlab commands. In order to make the file work as a script you just have to be sure that you name the file with an extension or suffix of "m". These script files are called mfiles in Matlab parlance. For example, a file named henry.m would be a valid m-file. You can make these scripts using the Matlab editor or any text editor. Whatever commands are typed in an m-file will be executed whenever the name of the m-file, without the m suffix, is typed in Mathlab. Therefore, a script becomes a kind of user-defined Matlab command. Matlab has to be able to locate the m-file so you must be sure that the m-file is in the Matlab path so that Matlab can find it. If you are new to Matlab and you are having path problems when you try to get your m-file to run you can always put your file in Matlabs working directory. You can find out what that directory is by simply typing the command pwd. ( This is short for present working directory). In the latest versions of Matlab the working directory is usually shown in the Matlab menu at the top of the command window. You can change your working directory with the cd command. (This is short for change directory). Just type the cd command followed by the path name of the directory you wish to make the working directory. You can also use the set path command under the file menu if you want to change your working directory or put directorys (i.e. folders) in Matlabs search path. The m-file scripts are ascii files and can be prepared using any ascii editor. However you will probably find it more convenient to use the Matlab editor. To start the Matlab editor, go to file on the Matlab command window menu then click on new and choose m-file. This will put you in the editor. You can type scripts in the editor and then test them by using the run command in the editor or you can save your script as an m-file and then run it by typing the name of the m-file without the .m on it. When writing scripts you type in the same commands and keystrokes that you would use when using Matlab interactively from the keyboard. It is also a good idea when writing scripts to include lots of comments to explain what you are doing. To put in a comment you use the % symbol. Any text following a % sign is ignored. When starting a script to turn in for a class assignments, you can use Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 4 of 14

comments to put your name, exercise number, etc. in your script. After you are through typing a script you should save it with a name that makes it easy to remember if you wish to use it again later. Usually you will find some bugs(mistakes) in your script and will have to edit the script to fix them. After you have prepared your first attempt at a script it is a good idea to run it while keeping the editor window open. Then you can jump back and forth between the editor and the command window and keep changing the script until you get it to run. Once you have saved a script file you can always change it later by using the open command under the file menu. One point to make is that in many scripts we only want output at certain places especially where large arrays are being handled. Just remember to use the semicolon to suppress output unless you really need to print or view the data. In regard to errors, probably the most common error that occurs is forgetting to put the % signs before comments. Almost as common is forgetting to use a transpose symbol. Remember Matlab operates on matrix objects. Be sure that you understand matrix operations before you use them. The use of square brackets [ ] and parentheses ( ) often gets confused and are often the source of some very frustrating errors. As you go through the exercises that follow. Be sure to pay special attention to where you use them. When scripts are to be turned in for homework exercises. It is often nice to show each command and the result of the command (Provided the result isn't an array with thousands of elements!) This is easy to do using the "echo" and the "diary" commands. Right before you issue the command to run a script type the commands: diary <filename> echo

The diary command starts making a record of all the screen output after the diary command is issued and stores it in a text file <filename> whose name you choose (e.g. ex_1_out.txt). The command echo shows each command that is executed from the script on the screen and shows the results of the command if it is not suppressed by a semicolon. Next run the script. After the script has run, type: diary off echo off Once you have a diary file you will have an ascii file that can be printed using any editor including Notepad or Wordpad. This will give you a very convenient way to print and save output from you scripts.

Exercise #1, Carry out the previous two matrix operations by hand. Then write a Matlab script that executes the previous matrix operations. Turn in both the calculations and the script. Now lets define another matrix e where e = [1, 2, 5, 6]' Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL Try calculating the product a*e

Page 5 of 14

and notice that Matlab announces that it has a problem. This is because the scalar product does not make sense since the matrix dimensions are not properly matched for this operation to be valid. Now try: e*a and you will get a matrix because this defines a proper outer product. The point is this. Matlab will not allow illegal operations, but will permit any legal operation. Of course, even if an operation is allowed it doesn't necessarily mean it's correct. Only the user can decide this! Remember the GIGO principle of programming: Garbage In = Garbage out. You may have noticed when typing commands that Matlab doesn't care about spaces in between operations or around equal signs. Feel free to use spaces to make things readable. Another useful point. If your line command becomes too long you can split it up by using three dots ... to indicate that a line is continued on the next line. CREATING MATRICES Now lets define a 3 X 3 matrix a which consists of the integers 1 through 9 in row order. Type: a = [ 1 2 3; 4 5 6; 7 8 9] When you type enter you will see that a is now a 3 X 3 matrix. Note that the semicolon is used to separate rows. One can also build matrices by putting other matrices together. For example, type: b = [ a a] This creates a 3 X 6 matrix by combining (side by side) two a matrices. Now type: c = [a;a] The semicolon "stacks" the matrices one on top of the other. Now type: d = [ b; [a,a]] This creates a 6 X 6 matrix. Matlab will permit you to create matrices by combining other matrices as long as the operations make sense. Type: e = [b;a] This generates an error since the matrices are not dimensional compatible in this arrangement. Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL THE COLON

Page 6 of 14

One of the most useful symbols in Matlab is the colon. It has several ways that it can be used. Type: a = [1:6] The colon is used to define a sequence of numbers from 1 through 6. We can also use 2 colons to sequence numbers with a fixed step between them. Type: b = [1:2:9] Notice that the numbers start at 1 and are incremented by 2. One can also increment backwards if a negative step is used. Type: c = [10:-2:0] Notice the numbers are reversed. Besides being useful for indexing sequences of numbers, the colon can be used in the indexing of matrix elements. To illustrate this lets create a matrix using a function called "magic". The function magic(n) creates an n X n matrix of integers with the interesting property that all the elements in a given row, column or diagonal sum to the same number. Magic matrices are handy when one wants to create a matrix of integers to experiment with. Type: a = magic(5) This produces a 5 X 5 magic matrix. Now we can use the colon notation to select out rows and columns in a matrix. Let us first learn to use index notation to identify a single element. Type: a(2,3) This defines the element that is in the 2nd row and the 3rd column. Type a(4,3) This defines the element in the fourth row and the 3rd column. Now we can use colon to identify more complex collections of matrix elements. Type: a(:,3) The colon in the left index position means all row indexes, with the right index fixed at 3, this notation results in column 3. Likewise if we type a(2,:) defines row 2. We can represent more complex situations by mixing in the colon sequence notation. Type:

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL a(2:4,:) This defines a matrix that consists of rows 2,3 and 4 of matrix a. Try a(:,1:2:5)

Page 7 of 14

This represents columns 1, 3, 5. The colon notation is very powerful. To make the point type a(5:-1:1,:) This reverses the rows of matrix a. Or try a(:,5:-1:1) There is another way to index elements in a matrix using a one dimensional index. Type: a(12) This represents the 12th element of the matrix if we count elements by counting down the columns. See if this is true by typing a and then count elements going columnwise until you reach the 13th element. Using this notation you can define column 2 of a another way. Type a(6:10) Now type a(:) This produces all the elements of a in a single column matrix. This can be useful for many tasks.

Exercise #2. Write a script that: (a) creates a 5X5 matrix called a using the "magic" function, (Type "help magic" to learn how to use the magic function.) (b) creates a column vector b that is equal to the 4th column of a, (c) creates a column vector c that is equal to the 3rd row of a, (d) creates a 10X1 column vector d made by stacking vector b on top of vector c.

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL MATRIX OPERATIONS Solving linear equations

Page 8 of 14

Matlab's strength is its powerful matrix calculation engine. It makes matrix operations easy and attractive. Many problems in engineering can be cast in matrix form. Consider the following problem of 3 equations and 3 unknowns:

This can be written in matrix form as:

where

This equation can be solved by

To solve in Matlab we can use the inv( ) function which inverts a matrix or the backslash, type A = [2 3 -1; 5 2 -2; 3 -3 2] u = [5 3 6]' To find the solution vector type: x = inv(A)*u or you can use the equivalent x = A\u

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL Exercise #3. Write a script to solve the following set of equations:

Page 9 of 14

Logic Functions You can also use logic functions with Matlab. Lets study this using our magic matrix a type: a This will give us a to look at, then type a > 12 This logic function tests each element of a and if the statement is true in puts a 1 in a matrix at a position that corresponds to the position of the element tested. If it is false it places a 0 there instead. Now try: a < 12 and a == 13 The == is the logical equal. Logical operations have many useful applications for tasks that involve searching out and selecting data points stored in a vector or a matrix. They are especially interesting in processing image data.

Matrix Multiplication and "Division" Now lets try some more matrix operations. Type: a*a This is the result of a matrix multiplication and the matrix a is squared. Try a slight change in the multiplication. Type a .* a

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 10 of 14

Notice the period before the multiplication. The period means that the operation that follows it should be done on an element by element basis using corresponding elements in the two matrices. It is quite different form the previous operation. In this case each element is squared not the matrix itself. Now try a /a which is equivalent to a*inv(a) and produces the identity matrix (i.e. a matrix with all ones along its diagonal, so does a\a which is equivalent to inv(a)*a. Now compare this with a ./ a Note again the effect of the period which leads to division of corresponding elements resulting in a matrix of all ones. Now try a .* (a >= 12) This sets all the elements in a less than 12 equal to 0. Note that >= is the logical symbol for "greater than or equal to" while <= is "less than or equal to". The FIND Function Another valuable function is find(A) where A is an arbitrary matrix. This function can find the indices of all the elements in matrix A that are non-zero. This can be useful for picking out or sorting elements in a matrix. Try using help to look up find. Type: help find This will give you a complete description of how to use find function. Note that find can be used to locate indices in the single index or the double index mode. To try this out type: ind = find(a>12) Then type a Study the matrix a and look at the index numbers from ind. The logical operation a > 12 created a matrix whose elements were 0 if they were greater than 1 and 0 otherwise. Therefore the find function found the indices of all the ones. Now type [indr,indc] = find(a>12) When used with two arguments on the left hand side, the find function produces row and column Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL indices. Again compare this with matrix a. Exercise #4. Write a script that does the following: (a) Create a 6X6 matrix a using magic.

Page 11 of 14

(b) Create a 6X6 matrix b from a that has a 1 where elements of a are greater then 15 and 0 elsewhere. (c) Create (6X6) matrix c by taking every element of matrix a that is less than or equal to 15 and replaces it with a 0, otherwise the element is unchanged. (d) Create a matrix d that puts all the non-zero elements of c in a single column matrix. Use any method you wish to do this except for directly typing the elements . Hint: this can be done easily with the "find" command and the use of colon notation. USING MATLAB FUNCTIONS Matlab has a large number of a useful mathematical functions. Please refer to the reference sheets that were handed out in class. We shall use quite a few of these functions in future exercises. To give a preview of some commonly use functions try out the following potpourri of statements: a = magic(4) sin(a) c = exp(a) d = cos(a) + cos(c) a+3 Note that Matlab functions work with matrices and in the cases above apply the operation to each statement. Note the very special effect of the addition function. It adds the single constant 3 to each element in "a". Normally addition will only add matrices of the same size. The constant is a special exception. CREATING USER FUNCTIONS Script files permit the user to collect a sequence of commands in a file. But it is also possible for users to create their own functions. Creating your own function is similar to creating a script in that it is an m-file (i.e. it has a m suffix in its name) but that is where the similarity ends. The function m-file is of the following form: function [u, v, x, y, z, ...] = fname(a,b,c,d, ...) [function program statements]

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 12 of 14

Note the use of the key word "function" to signal that a function is being defined. Here u, v, x, y, z, ... are output variables and a, b, c, d, ... are input variables. The function name is fname and it must also be the name of the m-file that stores your function (i.e. fname.m). All the input and output variables are "dummy variables" and any value of variable can be used for them. All calculations and variables used in the function program statements are local to the program and disappear after the function is called and its program statements are executed. Functions created by users are used just like any other function in Matlab. User created functions may also call other user created functions in their program statements. Go to an editor and type in the following simple function that finds the sum and difference of arguments. function [sum, diff] = sumdiff(a,b) %This function finds the sum and difference of its arguments a and b sum = a+b; diff = a-b; After you type the function in, save it in an m-file called sumdiff.m following statements in Matlab: q = [1 2 3; 4 5 6; 7 8 9]; r = magic(3); [s,d] = sumdiff(q,r) Now try it out using the

Notice that we used matrices as arguments and the function works just fine. As long as the dimensions of the matrices make sense the function will work. Try changing the function by rewriting it without the semicolons. Notice what this does to the output. Its important to use semicolons when you write functions to suppress output you don't want. If a function is generating output you don't want to see check your semicolons. Now try the command help sumdiff Notice that Matlab help will print out the comments that immediately follow the first line of the mfile with the "function" keyword. This lets user create help information for any function they create. PLOTTING FUNCTIONS The command "plot" is a very simple versatile function in Matlab. Type the following statements. t = 0:.2:3*pi; x = cos(t); y = sin(t); plot(t,x,t,y) This should give you a plot. You may have to click on Matlab's "Window" in the toolbar if it doesn't appear and click on the figure number. Notice that you get plots of the sin and cosine functions out Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 13 of 14

to 3B. Also note that Matlab handles the scaling and the colors of the plots and determines the type of plot (solid line, dashed line, symbols etc.) Type "help plot" to learn a little more about the plot function. You can choose the colors and type of plots if you wish. Type the following statement plot(t,x,'*y',t,y,'og) The quotes are used to identify character strings that tell Matlab the colors (y = yellow and g = green) and the line types (* = asterisks and o = open circles). If the linetypes aren't specified matlab always defaults to a solid line. It is easy to add a title to our plots. Notice that when you leave a plot you can either "kill" the window (in which case its gone) or you can jump back to the command window and the plot stays. If the plot is not killed you can add titles and other things to it. After you complete the command above click back into the command window without killing your plot and then try the following commands: title('PLOT OF A SIN AND A COSINE') xlabel('time') ylabel('amplitude') grid Note that the first three commands add character strings to the graph in the forms of titles and axes labels. The last command adds grid lines. Exercise #5. Create a function called chopper.m that takes any matrix A as an argument and uses it to creates a new matrix B that is the same as A but with its first and last rows removed. Assume that A has at least three rows. Turn in a copy of your function m-file and a short script that demonstrates the chopper function on two matrices: magic(3) and magic(6). Hint you may find the "size" function helpful. Look it up using help. It can be used to find the number of rows and column in a matrix.

Exercise #6. Create a script that plots a 10 Hz. sine wave with no phase shift. Plot the sinusoid from 0 to .15 seconds. Use 1500 evenly space samples of the signal. Assume the sinusoid peaks at 8 volts. Use xlabel and ylabel functions to label the axes in volts and seconds. Entitle the plot " This is a 10 Hz. Sinusoid" using the title function. Use the print function in the plot window to print a graph of the sinusoid to turn in with your script. PLOTTING GRAYSCALE IMAGES If the image processing toolbox is available one of the simplest methods for displaying images is the command imshow which is part of Matlabs image processing toolbox. For grayscale images the following description from the Matlab website is helpful:
imshow(I,[low high]) displays the grayscale image I, specifying the display range for I in [low high]. The value low (and any value less than low) displays as black; the value high (and any value greater than high) displays as white. Values in between are displayed as intermediate shades of gray, using the default number of gray levels. If you use an empty matrix ([]) for [low high], imshow uses [min(I(:)) max(I(:))]; that is, the minimum value in I is displayed as

black, and the maximum value is displayed as white. Jerome Knopp, CSEE Dept., University of Missouri-Kansas City

MATLAB TUTORIAL

Page 14 of 14

This function is quite useful for displaying images that are entered in a matrix as grayscale pixel values. Most students deal with images are not initially in this form but are typically in a standard format like jpeg, or tiff. Matlab can read most standard image formats using the imread command. A = IMREAD(FILENAME,FORMAT) This command reads the file (FILENAME) in the format (FORMAT) in the array A. This command permits most standard image formats to be read into Matlab as a two dimensional array but it typically requires that the image be converted to a double precision array of numbers to be manipulated or displayed. The following commands show how to load a tif image called Fig0911(a)(noisy_fingerprint).tif into Matlab and convert it to a double precision array A and then use imshow to display the image.
A = double(imread('Fig0911(a)(noisy_fingerprint).tif','tif')); imshow(A,[])

Note that you must put the image name in quotes as well as the image type 'tif' also in quotes following the image name. Once the array A is in double precision format, it is easy to use Matlab commands to do image manipulation. A double precision array can also be use saved in as grayscale image using the Matlab command imwrite: IMWRITE(A,FILENAME,FORMAT) This command takes the array A and puts into a file (FILENAME) in the designated format (FORMAT). Like the imread command, the filename and format in imwrite must be in quotes. The imread and imwrite commands are standard Matlab commands they are not toolbox commands. Exercise #7. Download a grayscale image from the internet in a known format. Then use Matlab to convert the image a double precision array and then display the image with imshow.

Jerome Knopp, CSEE Dept., University of Missouri-Kansas City