Math 2250 Introduction to Matlab Fall 2011 This document is an introduction to Matlab for Math 2250/2280 students. You will be using Matlab in Math 2250/2280, in order to solve problems and do computer projects. You can think of Matlab as an extremely powerful programmable calculator with many incredibly useful features. Matlab will be used primarily to do numerical calculations as opposed to symbolic calculations. You will use Matlab to solve problems where the answer is a number, vector, or matrix, rather than a function. To solve symbolic problems, you will need to use a program called Maple. While Maple can also solve numerical problems, Matlab is much more efficient and well designed for this process. It is recommended that students understand how to use both programs. Your specific assignments and requirements will depend on your particular Math 2250/2280 instructor. Matlab is updated periodically, and the Mathematics Department is currently using version 7.9.0. There are some backwards compatibility problems with Matlab, so documents created with newer versions may not run as expected on older ones. However, this should not be a problems considering the simple commands we will use in this course. Student computers around campus (Engineering, Marriott, Math Department, Heritage Commons) have Matlab software installed, and in most places you can find both the earlier and later versions. As an enrolled student at the University of Utah, you are allowed to use Matlab on these computers for free. You can also purchase a student version of Matlab 7.9.0 online for $99, directly from the vendor, MathWorks. Any version of Matlab you use includes an extensive help menu with detailed explanations about each command. When you open Matlab you can find a series of demo videos by going to the "Help" menu and selecting "Demos". It is recommended that you watch the first three videos in this list to help you get started in Matlab. From then on, you will learn to use Matlab the same way you learned to use Microsoft Word, i.e. by using it, using the help features, and asking friends, lab assistants, TAs and teachers when you get stuck. The Math 2250/2280 projects can usually be done using Maple, Matlab, Mathematica or other math software. But, most Math Department support for these projects will assume you’re using Maple. ........................................................................................................................................... 1) Computer Labs on campus, and logging on/off: There are many labs on campus, follow the link http://www.it.utah.edu/services/connected/labs.html . Most of these labs have Matlab software, and in most of these labs you log on using your University ID and password, i.e. the same way you log on to register for courses, get transcripts, etc. For example, if you are using the MMC labs this is the way you log on to your computer. It is generally true that when you log off a student computer on campus, you should not turn off the computer. One important exception to the universality of your UID/password for logging on to campus computers is the Math Department computer system, http://www.math.utah.edu/ugrad/lab.html. All students taking Math courses are assigned a Math Department login name and initial password that are NOT the same as their UID and University password. The undergraduate walk−in computer lab is located in the Rushing Math Student Center, located underneath the plaza connecting JWB to LCB. There is also a computer classroom in LCB 115, where some introductory tutorials are held. Useful information about most aspects of the lab can be found by following links from the Math Department web pages like the one above, or the precursor directory http://www.math.utah.edu/ugrad . If you’re working on the Math Department system your login name will be of the form c−azbc, where ‘az’ is first letter− last letter of your last name, and ‘b’,‘c’ are your first, and middle initials, respectively. For example, if your name is Ulysses Attila Eratosthenes, your login name will be c−esua. (Many people have the same initials, so to ensure your login name is unique, a digit may be added after the initials, eg. c−esua1, c−esua2, ...). For people with more complex (eg. hyphenated names) only the first character of each name is used. Your initial password will be the letters as in the login name, followed by the last four digits of your University ID number (e.g., if your UID is 123456789 and your login name is c−esua, then your password is esua6789) or if the login name is c−esua2 the password is still esua6789). You should change your password if it’s still the default one. To do so, log in, open a terminal window using a mouse or icon selection (depending on the operating system you’ve logged on with), then type ‘‘passwd’’ (followed by RETURN/ENTER). Ask a lab assistant how to do this if you’re doing this tutorial on your own and are confused. If you previously took a math class and used our system then your old account may still be active, with the last password you used. If all your efforts to log on fail, ask a lab assistant for help. Don’t forget to log out when you’re done. Never turn off a Math Department computer. ........................................................................................................................................... 2) Opening Matlab Matlab may appear as icons on your computer desktop and perhaps the icon will contain a picture of the "MathWorks" logo. Alternately, you may open Matlab with a terminal window command or by searching directories. If you’re not sure how to find and open Matlab, ask a lab assistant. In Marriott if you can’t find a class software or applications directory with Matlab in it, ask at the help desk. ........................................................................................................................................... 3) Using Matlab If you are starting the tutorial at this point, we assume you have already opened Matlab. Matlab is partly just a very fancy calculator; it can do practically any undergraduate mathematics computation. Additionally, in Matlab you can write programs, create plots, save large amounts of data, customize how you want the program output to appear on your screen, and much more. Demo Videos for New Users When you open Matlab you can find a series of demo videos by going to the "Help" menu and selecting "Demos". It is recommended that you watch the first three videos in this list to help you get started in Matlab. This is a good way to learn generally about what Matlab can do. If you wish you can explore now, or you can continue with the Math 2250 notes below and come back to the demo videos later. Matlab Window On opening Matlab, you will notice that the window is broken up into several sections. On the left column, there is a Directory Section titled "Current Folder" which displays all the files and folders in the current directory, and just below that is a Description Section which gives further details about the file that is selected in the Directory Section. For the time being, we will ignore these two sections on the left hand side of the window. In the center of the window is the largest section titled "Command Window". This is the only section that we will be concerned with during this introductory tutorial. You will notice that in this window there may (or may not) be some text written at the top which gives some details about the version of Matlab you are using. Below this text is the command prompt, ">>", which is where you will type in the Matlab Commands described below. You should see your cursor blinking next to the command prompt. On the right column, there is a section titled "Workspace" which shows a list of all the variables that have been defined in the current Matlab session and gives some basic details about them. The section directly below this one is entitled "Command History" which shows, in reverse order, all previous commands entered into Matlab at the command prompt. For the time being, we will ignore these two sections on the right hand side of the window. Entering Matlab commands Focusing on the "Command Window", make sure that your cursor is blinking in front of the first command prompt, which is denoted with a ">>" symbol. After typing a command and pressing "Enter" on your keyboard, you should see the output of the command and then a new command prompt below, again denoted by the symbol ">>". If you wish to suppress the output after any command, simply make sure to type a semicolon after at the end of the command before pressing Enter. If you want to enter multiple commands at the same command prompt, hold down the "Shift" key and press "Enter" to change lines without executing any command. When you have finished entering all commands, press "Enter" to execute them all simultaneously. If you incorrectly align parentheses or brackets, or do something else which makes your command unexecutable you will get a ‘‘syntax error’’ message and Matlab will try to point out your mistake with the cursor and cryptic diagnostic phrases. These syntax error messages are always presented in text that is colored red. If everything was executed properly, any output from the command will be in text that is colored black. After a while you will become good at fixing mistakes but they can be annoying at first. Spaces are generally ignored in Matlab, so you may use them to make input easier to read. You can enter explanatory comments in a command line by inserting a ‘‘%’’ to the left of the comments; Matlab ignores any text after the % on a command line. You will also notice that any text after the "%" is colored green, to indicate that Matlab will ignore it. Inserting these comments may help you better understand what your Matlab code is doing so it is easier to find mistakes or make changes. Now, let’s try entering some commands. (You may try just the math commands, the comments were only added to explain what the particular commands are illustrating ! ) Check that you understand what each command is doing. >> 3 + 1 % % % % % % % Matlab will add 3 and 1. The output, "ans = 4", is displayed below the command prompt. Notice how the output is broken up into different lines, this is done to make larger data structures, such as vectors and matrices, more readable. For individual numbers it seems a little weird but it is easy to understand and get used to. >> 4 * 2 % Matlab will multiply 4 and 2. >> 10 / 5 % Matlab will divide 10 by 5. >> 2^3 Output is "ans = 2". % Matlab will raise 2 to the power of 3. % "ans = 8". >> (3+1)*(2-5)^4 >> pi Output is "ans = 8". % % % % % % % % % % % Output is Matlab will compute this expression using the order of operations, interpreting parenthesis as your calculator would. The output is "ans=324". Matlab has several internally defined variables. Matlab recognizes "pi" as the number that we are familiar with from geometry. The output should be "ans = 3.1416", which is pi rounded off to four decimal places. Matlab will not recognize "e" as the number we are accustomed to, but it will recognize "i" to be the imaginary unit. >> exp(3) % % % % % % Matlab does not recognize the number "e", so to evaluate the number e raised to a power you will use the exp() function. The line entered here will raise e to the power of 3. The output is "ans = 20.0855". Notice that once again the answer is rounded to the 4th decimal place. >> sin(0) % % % % % % % Matlab understands all of the basic trigonometric functions including sin(), cos(), tan(), sec(), csc(), and cot(). Matlab ALWAYS works in radians. If you are using degrees, you will first need to convert your angle to radians before using one of these function. The output for this line should be "ans = 0". >> asin(0)% % % % % % % % % Matlab also understands the inverse trigonometric functions including asin(), acos(), atan(), asec(), acsc(), and acot(). Since Matlab only works in radians then all the output for these functions will always be expressed in radians. It should also be pointed out that matlab understands all of the hyperbolic trignonometric functions including sinh(), cosh(), tanh(), sech(), csch(), and coth(). The output for this line of code is "ans = 0". >> log(1) % Matlab can take the log of numbers. Matlab always % interprets the log() function to mean natural log. % The output for this line is "ans = 0" >> sqrt(4)% Matlab can take the square root of a number using % the sqrt() command. The output for this line is % "ans = 2" >> nthroot(64,6) % % % % % % % % % % Matlab can take higher order radicals using the nthroot() command. Notice that there are two arguments of this function. The first is the radicand and the second is the index of the radical. This line calculates the 6th root of 64. When a function is set up to receive multiple arguments, those arguments need to be separated by commas. The output for this line is "ans = 2". >> [1 2 3] % % % % % Vectors are entered into Matlab in this way. Matlab will interpret this command as the row vector [1 2 3]. You would have gotten the same result had you separated each entry with a comma. >> [1 ; 2 ; 3] % Matlab interprets this command as a column % vector. The use of the semicolon tells matlab % to end the current row and start a new one. >> [1 0 ; 0 1] % % % % % % Matlab interprets this command as a the 2x2 identity matrix. The first row is entered, followed by a semicolon, which tells Matlab to start the second row, and then the second row is entered. In principle you can define any matrix of any size in Matlab in this way. >> x = 4 % % % % % % % In Matlab you can assign values to letters. This command sets the variable "x" to the value of 4. From now on (unless you restart Matlab or reassign the value of x), the letter x will be interpreted as the number 4. You can do any operation on x as you would with a regular number. The output for this command is "x = 4". >> x*3 % % % % This command will take the current value of "x" and multiply if by 3. Since in the previous line we set the value of x to 4, we expect the output of this command to be "ans = 12". >> A = [1 2 % % % % ; 3 4] In this command we have assigned the variable "A" to the 2x2 matrix with entries 1, 2, 3, 4. Notice the organized way in which the output is given. It is clear that A represents a matrix. >> b = [1 ; % % % 0] In this command we have assigned the variable "b" to the column vector with entries 1, 0. The output clearly shows b as a column vector. >> A*b Matlab is great at working with matrices and vectors, in fact, that is exactly what this program was designed for. In this line we have multiplied the matrix A by the vector b. The result is the column vector with entries 1, 3. % % % % % Saving files in Matlab In many situation, you may have a series of commands that you wish to use quiet often. Instead of having to enter these commands in the Command Window every time you start Matlab, it is possible to save these commands to a file, called an m-file. To create a new m-file go to the "File" menu, then go to "New" and select "Blank MFile". A new window will appear which looks like a blank text file. You will notice there are no command prompt symbols, ">>", in this file. Matlab will interpret each new line as its own command and run every line of the file in order when you execute it. We'll talk about how to execute the file in a minute. Type the following text into the window of the new file (you don't have to enter the comments, those are just for your own reference): A = [1 1 ; 0 1] b = [2 ; 3] A*b % This stores the matrix into A % This stores the column vector into b % This multiplies matrix A by vector b Next we will want to save this file. In the window of the new file you will see the menu bar on top (different from the menu bar in the main window for Matlab), go to the "File" menu and go to "Save". Matlab will automatically have you save the file in the same folder it is currently working in. For the purposes of this exercise, don't change folders, save the file in the folder that Matlab defaults to. Let's call this file "example.m". The .m extension is necessary to tell Matlab that this is an m-file. Click "Save" once you've named the file. If you return to the main window in Matlab, and look at the upper left section of the window called "Current Folder", you should see the "example.m" file. Executing files in Matlab To execute the commands saved in the file, example.m, go to the center part of the window called the "Command Window" and on the command prompt enter the name of the file, without the .m extension. In other words, you want to enter: >> example % This will run the commands in the file % example.m If everything works correctly, you should see the following output. >> example A = 1 0 b = 2 3 0 1 ans = 5 3 When seeing this output, you realize that it is unnecessary to display the way A and b have been defined, instead, you would only like for the product to be displayed. Go back to the example.m file window (if you already closed it, go to the part of the upper left part of the main Matlab window called "Current Folder" and double click the example.m file to open it). Change the text in this file so that it looks as follows (again, don't worry about the comments): A = [1 1 ; 0 1]; b = [2 ; 3]; A*b % This stores the matrix into A % This stores the column vector into b % This multiplies matrix A by vector b The only thing we have changed here is to add a semicolon to the end of the first and second lines. This will suppress the output for these two commands. Save the changes you made in this file by going to the "File" menu and clicking "Save". Now go back to the Command Window and enter the following command to run the commands in the example.m file: >> example This time you should see the following output: ans = 5 3 Notice that the result of the first two commands in the file were suppressed. In general, when creating these files to do a long calculation you will want to suppress everything but the final result (unless perhaps you're searching for mistakes in your code). Matlab Help File Matlab has a very extensive help file where you can find a lot of what you need. Go to the "Help" menu and select "Product Help". A new window will open and you will notice a searchbox where you can type in whatever you are looking for. There is much more that can be done in Matlab, this is just a brief introduction. On the course website I have posted other files that teach you more advanced techniques including how to create loops, functions, data structures, plots, and much more!