MATLAB Course Notes and Assignments Engineering 161 Joe Mixsell MATLAB (Matrix Laboratory) is a powerful computer software application program for solving engineering problems. It is applicable for all engineering disciplines and many natural sciences as well. MATLAB is rich with many functions that are provided to solve engineering problems. MATLAB has been updated and extended to cover essentially all the engineering fields. By learning how to use MATLAB and having access to MATLAB, you will be able to use this software through out your engineering education and most likely in your professional career. At a minimum, it is possible to use MATLAB as a glorified calculator, but the real value of learning how to use this powerful software is in solving complex engineering problems using a few MATLAB statements. MATLAB is set up to be extremely flexible and based upon using vectors and matrices in one’s solutions. Many engineering problems can be set up in this way and then solved using MATLAB. An alternative to MATLAB is to write a dedicate program using Visual Basic or C or Fortran. Programs written to solve engineering problems using high level languages such as one of these will run faster than MATLAB but as well it will take much longer to write and debug. One way of thinking of MATLAB is as a powerful desktop scratch pad for solving engineering problems. We will learn how to use MATLAB and write simple sequences of commands that can solve complex problems. In so doing, we will only scratch the surface in Engineering 161, but you will gain the confidence and knowledge to continue to use MATLAB and learn additional capabilities. Our text will lead us through the basics. Other books that you might be interested in to obtain can be found on the www.mathworks.com website. Mathworks is the company responsible for MATLAB. Their website lists many books and sources of information regarding MATLAB. A couple books in addition to our text that you might want to look at are; Mastering MATLAB 7 by Hanselman and Littlefield, published by Prentice Hall. MATLAB Tutor: Learning MATLAB Superfast by Daku, published by Wiley. Our text is MATLAB for Engineers by Holly Moore, Third Edition, and published by Prentice Hall. All of these books are introductory in nature, but they all will give you training in the MATLAB basics and help you develop a firm foundation in using MATLAB. Student outcomes, from learning about MATLAB in Engineering 161, upon completion of this course include; 1 1. Students should be able to apply computer methods for solving a wide range of engineering problems. 2. Students should be able to use computer engineering software to solve and present problem solutions in a technical format. 3. Students should be able to utilize computer skills to enhance learning and performance in other engineering and science courses. 4. And finally, students should be able to demonstrate professionalism in interactions with colleagues, faculty, and staff. MATLAB for Engineers Contents 1. About MATLAB 2. MATLAB Environment 3. Built In MATLAB Functions 4. Manipulating MATLAB Matrices 5. Plotting 6. User-Defined Functions 7. User-Controlled Input and Output 8. Logical Functions and Control Structures 9. Matrix Algebra 10. Other Kinds of Arrays (not included in our Engr 161 course.) 11. Symbolic Mathematics 12. Numerical Techniques (selected topics from text on curve fitting.) 13. Advanced Graphics (not included in the Engr 161course.) The only way to become proficient with a new language like MATLAB is to use it by doing the exercises. A number of exercises will be assigned. You will be expected to go to the computer lab and solve the problem using MATLAB and hand in your results. Additionally, several exams will be scheduled that will require you to use MATLAB. So it makes a lot of sense to start out slowly and build up your knowledge and capabilities. And the best way to do this is to use the computer lab, enter commands and observe what happens, do the exercises in the text even when you can see the results in the text, and then the assigned problems. On a couple of the assignments, you will be asked to use Powerpoint to create a presentation of your engineering work. Powerpoint presentations are often used in engineering to document and communicate results. Since MATLAB can export command sequence files and results, i.e., tables and charts, to applications like Powepoint and Word, it is convenient to use those software applications to document and communicate engineering work. In each of the following sections, we will outline the key concepts that you need to become proficient with as well as we will practice these concepts before you go to the lab and do it for yourself. 2 List of Assignments to be completed and turned in follows. You may work ahead at your own pace and complete assignments early if you wish. To show that you have completed the work, print the Command Window and/or Graphics Window, add your name and turn in the assignment. Using MATLAB comments add your name and identify your assignment by Chapter and problem number at the beginning of each assignment. We’ll discuss these MATLAB features shortly. A list of assignments will be provide in class for each semester. See your instructor for the list of assignments and special projects. 1. Introduction to Engineering Problem Solving An Engineering Problem-Solving Methodology Problem solving is a key part of engineering courses as well as other courses in computer science, mathematics, physics, and chemistry. Hence it is important to have a consistent approach to solving problems. The process or methodology for problem solving has five steps: a. State the problem clearly and succinctly. b. Describe the input and output information, i.e., what is given to solve the problem and what is expected as the results. c. Work the problem by hand with a calculator for a simple set of the input data. d. Develop the MATLAB solution using the process you followed in c. e. Test the solution with a variety of data. This approach is universal and applicable to all problems and all engineering disciplines. It is a structured approach to solving engineering problems. Let’s review the highlights of each. a. State the problem clearly and succinctly. For the example that we are going to pursue, we can state the problem in the following way; Compute the average of a set of temperatures. b. For our problem we will be given a set of time values and the corresponding temperatures, (the inputs) and we are asked to compute the average temperature and plot the time and temperature values. c. Sketch your solution and work the solution by hand, so for example, suppose there are three times 0.0, 0.5, 1.0 minutes and for each value of time we have temperatures 105, 136, 119. We compute by hand that the average temperature is (105 + 126 + 119)/3 or 116.6667 degrees F. 3 d. The next step is to develop the MATLAB solution which is a step by step sequence of commands that you will enter into MATLAB to compute the average temperature for any arbitrary set of temperatures. Suppose we are entering these commands into MATLAB in the Command Window. (We will learn more about the Command Window and the MATLAB environment in the next few sessions.) >> %Name: Joe Mixsell % In MATLAB, anything following a % >> %Assignment #2.1 % is a comment and ignored by MATLAB. >> % Compute average temperature and plot the >> % temperature data. % >> time = [0.0, 0.5, 1.0]; >> temps = [105, 126, 119]; >>average = mean (temps) average = 116.6667 >> plot (time, temps), title(‘Temperature Measurements’), >> xlabel (‘Time, minutes’), >> ylabel (‘Temperature, degrees F’), grid on This sequence of MATLAB commands entered into the Command Window will compute the average temperature of the three temperatures, i.e., average = 116.6667 and plot a graph of time versus temps in the Graphics Window called Figure 1. 4 Some key observations. MATLAB echoes each line as it entered and executed unless the line is followed by a semicolon. In this case the command will be executed but not echoed. When one is initially writing and testing a sequence of MATLAB commands it is often useful to suppress the semicolon to check your intermediate results. Then once the script is tested, one normally inserts the semicolons and used the script to compute several sets of inputs. The symbol % is used to delineate a comment that you want to insert to remind yourself what your program or sequence of commands do. They can be inserted anywhere you want to place them and it is good practice to comment well your programs. MATLAB ignores anything that follows a %. e. Testing. The final step is to check the results versus the hand example to see that the program is functioning as you expect. Once you are confident that the program is correct you can use it to solve more general sets of data. Exercise: Using the lab computers, start the MATLAB software, enter the commands into the Command Window of MATLAB from page 14 of the text, one line at a time. Be 5 careful to copy each line including all the punctuation carefully. Upon completion of the last line, hit enter and see the result for the average temperature and the graph that appears in the Graphics Window. Print your results. When you finish your assignment, enter the following commands in the Command Window, >> clc >> clear to clear the Command Window and the Workspace Window for the next student. Then exit MATLAB by entering the command >> exit (or click on File and click on Exit) 2. MATLAB Environment This section will introduce you to many of the key concepts in MATLAB and many of the notions that you will want to master to use the software effectively. We start by learning how MATLAB is structured, the various Windows used by MATLAB, how matrices are established, scalar operations, matrix operations, precedence among the operators, etc. First it is essential to know how MATLAB is structured. When you start MATLAB a screen will appear made up of several independent windows all linked or docked together, these windows include the Command Window, the Command History Window, the Workspace Window, the Current Directory Window, a Document Window, a Graphics Window, and finally the Edit Window. The initial view when MATLAB starts will show you the Command Window, the Command History Window, and let you toggle between the Workspace and Current Directory Window. The Edit Window appears if you enter the edit command in the Command Window, >> edit Or if you click on File, then New, then m-file. This window is very useful allowing you to write sequences of commands, edit them, store them for future use and to run them in the Command Window. This will be discussed in a moment. The Graphics Window appears when you use one of the plot commands to plot a function, i.e., >> plot (x,y) Where x is a row vector of some number of values and y is also a row vector specified by some relationship of x. 6 Let’s discuss each of these windows in some more detail. Command Window Think of the Command Window as a scratch pad for doing calculations. Enter a valid MATLAB command, it is executed and the result is shown unless you placed a semicolon at the end of the command line. In any case the command you entered is remembered in the Command History Window and the various variables that you used in the command are remembered in the Workspace Window. The operations you perform in the Command Window are very similar to using a scientific calculator. So for example, if you enter the following at the Command Window prompt and hit enter; >> 5^2 ans = 25 >> cos(pi) ans = -1 >> x = 5, y = 6; >> z = x + y ans = 11 >> MATLAB uses standard algebraic rules for the order of the operations. Note that a semicolon was placed after the command assigning values to x and y. The presences of the semicolon caused MATLAB to not echo the values of x and y. Similarly, no semicolon after the command z=x+y caused MATLAB to provide the answer. Also note that multiple commands can be placed on a single command line if they are separated by a comma. The commands that you enter into the Command Window are remembered sequentially in the Command History Window and the values assigned or computed for the various variables that you create are stored in the Workspace Window. These windows become more useful for more complicated computations as we will see as we go along. 7 When you start a MATLAB session you may find that the Command Window and Command History and the Workspace Windows are not empty, i.e., some one previously who used MATLAB did not clear their information before exiting MATLAB. To start with a clean set of windows and to avoid confusion between variable names and values, you should always clear these windows if they have not been cleared. >> clc >> clear % Clears the Command Window % Clears the Workspace Window You can clear the Command History Window by clicking on the Toolbar Edit and then clicking on the Clear Command History Window. You can also clear the Command Window and the Workspace Window in the same manner. Command History Window Recall that we said that as commands are entered into the Command Window, they are remembered sequentially in the Command History Window. This window allows you to review your session and it allows you to move previous commands back to the Command Window and re-execute them. To do so you can do one of the following two things; 1. Point and click (with the left mouse button) on a particular command in the Command History Window and drag it back to the Command History Window. Releasing the button will place the command but not execute it. Hit enter to execute the command. 2. Or, just double click on the command in the Command History Window. The command is automatically placed in the Command Window and executed. Workspace Window This window keeps track of all the variables that you create in your session. You can see how the variables are stored, their current values, the size of the array used to store the variables, and the variables class, i.e., single or double precision, complex number, etc. Two commands issued in the Command Window are useful to periodically check on your variables, >> who % List all your current variables by name >> whos % List all the variables and gives their sizes and class. If at any time you forget what a particular command does or how to use it, enter the command, for example, >> help who MATLAB returns with an explanation of the command and how to use it. By typing 8 >> help clc MATLAB would return the information that the clc command clears the Command Window. Now suppose you want to change the value of a variable. You can edit the value of a variable in the Workspace Window by double clicking on it. MATLAB causes the Document Window to appear which lets you edit a particular value. Document Window When you double clicked on a particular variable in the Workspace Window, MATLAB caused the Document Window to appear. Edit the variable, change its value or even define a new variable are all possible in the Document Window. Close the Document Window and the modified or new variable that you created will appear in the Workspace Window. Any reference to this modified or new variable in a future command will use the updated or new value. Edit Window This is one of the most useful and powerful windows that you will use. It allows you to write a sequence of MATLAB commands, edit them, save them and run them as a program. The Edit Window appears if you type >> edit % Causes the Edit Window to appear or click on File, New, M-file. Once your have created your program, when you save it you will be prompted to give it a filename and MATLAB will attach an .m (for M-file) to your filename. Then from the Command Window you can cause the sequence of commands to be executed simply by entering the filename at the MATLAB prompt, >> filename % Causes MATLAB to execute my sequence of commands % that I created in the Edit Window. We will learn later how to write these programs so that they allow us to interact with them, i.e., the program will ask us for input and pause. We can then enter the input from the keyboard and cause the program to continue. This affords us great flexibility in writing our programs using them for general solutions. MATLAB has a special name for these kinds of sequences of commands created in the Edit Window, they are called Script M-files. It is possible to create these scripts using a different editor than the one provided in MATLAB, but you must remember to save the contents that you have created with the different editor using the ASCII format provided as an option with the editor. This is 9 necessary for MATLAB to read your file. Remember that when MATLAB creates and saves your file, it automatically attaches the .m to your filename and stores it into a folder specified by the Current Directory Window. This is where MATLAB will look for your script when you enter the command >> filename % It is now necessary to append the .m, just the filename. So if you construct your script using another editor and store it into the folder where MATLAB will look for the list of commands, you must also attach the .m suffix to your filename. Your filename must also comply with the MATLAB rules for naming variables which we will get to in a few moments. For example, you can use the Windows NotePad to create your M-file. NotePad is usually found in Windows Accessories. Start NotePad, enter your script line by line remembering to comment it well and use semicolons where you do not want the results echoed by MATLAB. When you are finished entering your MATLAB statements, you will need to save it in your current directory or where ever you have chosen to save your MATLAB work. From File, select Save As, then type in the filename that you have chosen for this script followed by .m. Select Text Document as the type and ANSI as the coding type. Save the file. Remember the filename must be a legal MATLAB filename. When you start MATLAB the next time, and open the Edit Window, you will find the file that you created. From the Edit Window you can continue to develop your program or run it. You can also run your script M-file by entering the filename in the Command Window. Remember the Current Directory needs to point to the folder where you are storing your M-files and other MATLAB data. Graphics Window The graphics window appears in response to the MATLAB command >> plot (x,y) You will use this command often in your work with MATLAB. You can cause multiple plots to occur in a single window, or you can use multiple windows to plot your functions. You will be able to label the axis, label the graph, choose colors and symbols for the plot, or use the default axis and colors. If you have created a plot, and then enter a second plot command, the first plot will be overwritten unless you cause MATLAB to create a second Graphics Window by typing >> figure(2) % Causes MATLAB to open a second Graphic Window. In the first small example that we did earlier, we created a graph of time and temps. The plotting capabilities of MATLAB will be covered more extensively a little later in our exploration of MATLAB. MATLAB has very powerful graphing capabilities including both 2 and 3 dimensional graphs. 10 Current Directory Window This is a very important window to understand. MATLAB uses the current directory located at the top of the main window to access and save information that you created during a MATLAB session when you indicate that you want to save information. If you want to use a folder to save your work such as Script M-files that you have created other than the default folder created by MATLAB, you must attach this folder to MATLAB’s path, i.e, to its list of all folders that MATLAB will access information or store information. Once your have added your folder to MATLAB’s path, you can select it using the drop down list button next to the current directory display. Upon so doing, MATLAB will now access your Script M-files stored there upon your command and any save information that you select will be saved to that folder. For our purposes, our systems have been configured so that the folder My Documents/MATLABwork has been added to the MATLAB path and upon your signing in this folder is mapped to your account with a similar name. Upon starting up MATLAB, drop down the window next to the current directory and click on My Documents/MATLABwork. As this is mapped to your account, you will save your Script M-files in your account as well as access them as you want. If you create Script M-files using another editor offline, you will want to store them into your account’s folder My Documents/MATLABwork. Don’t forget to append the .m suffix to your filename. Use the Windows NotePad to develop your scripts and save them as M-files. This has been discussed previously. This completes our overview of the MATLAB Environment. It is best to visit the computer lab and explore MATLAB first hand. Enter a few commands, see what happens to the Command History Window and the Workspace Window. Move commands to the Command Window from the Command History Window, check out the variable definitions in the Workspace Window. You can even open the Edit Window and enter a few commands there as well. Create a simple plot and explore the plotting command. Try doing the following to see what happens, from the Command Window enter; >> x = -1.5: 0.01: 1.5; % Create a vector x of values from 1.5 to 1.5, % in increments of 0.01 % Evaluate y from the values of x. >> y = x^2 – 1; >> Y = [1, 0, -1]; >> roots (Y) >> plot (x,y) >> xlabel (‘Independent Variable X’), ylabel (‘Dependent Variable Y’) What does the built in command roots (Y) do? 11 At this point, we are going to introduce a number of additional key elements about MATLAB and how it works. MATLAB Variables In using MATLAB we have to assign names to the variables that we use for scalars, vectors, matrices and of course filenames. The following requirements apply to all variable names. a. Variable names must start with a letter. b. Variable names are case sensitive, time and Time are different variables. c. Other than the first letter, variable names may contain letters, digits, and the underscore character ( _ ). d. Variable names can be any length but only the first 63 characters are used by MATLAB. e. Variable names can not have the same name of any of the MATLAB keywords. f. MATLAB allows you to use the same name as a built in function, but be careful in so doing. You are actually redefining the function when you do this. Not recommended. To check if you are using a valid MATLAB variable name, type >> isvarname ‘your proposed variable name without the single quotes’ MATLAB returns a 1 if your proposed name is valid, and a 0 if it is not. To see a list of all MATLAB keywords, type >> iskeyword % List all MATLAB keywords. To check if you are trying to use a built in function name, type >> which ‘your proposed variable name w/o the quotes’ For example, suppose you want to use the variable name sin, then by typing >> which sin MATLAB returns with sin is a built in function and therefore it is not recommended to use sin as a variable name. Scalar Operations 12 Although MATLAB derives is power from matrix manipulations, it is often necessary to work with scalars and scalar operations in our computations. Scalar operations are the typical algebraic operations that we are familiar with, addition, subtraction, multiplication, division and exponentiation. The MATLAB symbols used to denote these operations are +, -, *, /, and ^ respectively. Additionally, the use of the equality sign has a different mean in a MATLAB command, for example, >> x = 5; % Initial the variable x to have value equal to 5. means that the value 5 is assigned to the variable x. Therefore the command >> x = x + 1 x= 6 makes sense. Here on the right hand side of the expression 1 is added to the current value of x which is 5 and then re-assigned to x. At the conclusion of this command, x has the value of 6. Hence we say that the symbol = in MATLAB is the assignment operator. Precedence of Arithmetic Operations In many MATLAB commands you may choose to enter several arithmetic operations. So it is important to know the order that these operations are performed by MATLAB so that the order that MATLAB performs the operations is the same as the order that you want. Carelessness here will result in an unexpected outcome from the MATLAB computations and it is often difficult to find or may be missed completely leading to the wrong interpretation of your results. The order of precedence is given below in the following table. Precedence 1 is the highest and performed first, then 2, 3, with 4 being the lowest and performed last. Precedence of Arithmetic Operations 1. 2. 3. 4. Parentheses, innermost first Exponentiation, left to right Multiplication and division, left to right Addition and subtraction, left to right. Note that >> y = a*b/c*d; is not the same as >> y = a*b/(c*d); 13 In the first case, a multiplies b, then a*b is divided by c, then this result is multiplied by d. In the second case, c and d are multiplied first. Then a multiplies b and this result is divided by c*d. You can see that you will get different answers. If in doubt, use parentheses to clearly specify the order that you want the operations performed. Introduction to Matrix and Vector Operations Vectors and matrices are defined by square brackets in MATLAB, i.e., [ ]. MATLAB has a number of ways to generate often used vectors and matrices and of course a set of operations for manipulating them. In the simplest of cases, >> x = [1 2 3 4 5]; creates a row vector of 5 elements. Similarly the command >> y = [1; 2; 3; 4; 5]; creates a column vector, i.e., a matrix with 5 rows and a single column. In the case of the row vector, one can also delineate the elements with a comma, but it is not necessary, spaces will do. In the second case, delineating the elements with a semicolon causes MATLAB to create the column vector. In the first case, x could have been specified in the following manner, >> x = [1:5] x= 12345 Here we are using the colon operator to generate a specific row vector. The first element is 1, the last element is 5 and the elements are evenly spaced. The square brackets in this case are optional. Consider this command, >> x = -1.5: .01: 1.5; that we used previously. MATLAB creates a row vector with the initial entry of -1.5, the final value of +1.5 and 100 evenly spaced increments between -1.5 and +1.5. If we want to know how many elements are in the row vector x, enter >> size (x) ans = 301 14 Another way to create a row vector with evenly spaced increments is to use the built in linspace function in MATLAB. We could have said, >> x = linspace (-1.5, 1.5, 301); The first argument of the built in function linspace is the initial value, the second argument is the final value and the third argument is the total number of values to be created. They are evenly spaced. If you forget the definitions you can always get information by typing >> help linspace in the Command Window. Now suppose you want a matrix with 2 rows and 3 columns having values entered from a particular problem. For our illustration we will just assume sequential integers again, >> F = [1 2 3; 4 5 6] F= 123 456 F is a 2 rows by 3 columns matrix. Note that the semicolon denotes a new row in the matrix F. In a later chapter we will explore matrix operations in more detail, but for now we explore scalar operations on vectors and matrices. So consider the following commands >> A = [1 2 3} A= 123 >> B = A + 1 % Add the scalar 1 to each element of A B= 234 >> C = A – B % This is actually a matrix operation. C= -1 -1 -1 >> D = 3* A % Scalar multiplication of A by 3. 15 D= 369 Now suppose you want to multiple each element of A by the corresponding element in B. MATLAB allows you do this with a special from of the multiplication symbol, that is, >> E = A .* B % Multiplies element by element, note the .* E= 2 6 12 Similarly you can use ./ and .^ to divide element by element or raise to a power each element in a vector or matrix. >> G = A ./ B G= .5 .667 .74 Another useful matrix operator in MATLAB is the transpose operator, >> H = B’ % H is a column vector. H= 2 3 4 >> Scientific Notation and Display Formats MATLAB has several ways to process and display numbers. These formats are summarized in Table 2.3, page 42. You may select one of these formats by entering the appropriate command in the Commnand Window to the prompt. In general, integers are printed as integers and the default format is used to print values with decimal fractions. So for example, >> A = 5.1 A= 5.1000 That is, the default format prints with 4 decimal places. This default format is called 16 format short. See Table 2.3. When numbers become too large or too small for the default format, MATLAB automatically switches to scientific notation. You can force MATLAB to use only scientific notation by selecting format short e or format long e. For most of the problems that we will be doing, the default format will be sufficient, although you can certainly try using the various formats defined in Table 2.3. Note that in some calculations, MATLAB will express a result as a very small positive or negative number in scientific notation rather than expressing the result as zero. This is due to the fact that numbers are expressed in binary formats and have a fixed precision, i.e., the number of bits used to express the number is finite. So in some calculations you may want to set these very small numbers to zero before proceeding. It helps to make your output more readable and make the script run faster as well. Saving Variables and Scripts Often when developing programs and running these programs to calculate results it is convenient be able to save the variable and data created and the scripts that you are developing. MATLAB allows you to do this and then return the data and command statements for a future session. Recall that during a MATLAB session the commands that you enter in the Command Window generates a list of variables and corresponding values in the Workspace Window. To save these variable for a future use, you use the save command. MATLAB saves the contents of the Workspace Window or a subset of it to the Current Directory to a filename of your choice and attaches .mat to the filename. >> save filename % filename must be a valid MATLAB variable name (Note the book sometimes surrounds user defined filenames with < >. In these notes we will not do this. ) For the above command, the contents of the Workspace Window are stored in the current directory folder in the file named, filename. In some future session if you want to return the Workspace Window to its previous state, enter, >> load filename % Workspace Window is restored All the variables and their values that you had stored previously are restored and ready for use in the current session. As we have mentioned previously, when you start a MATLAB session, it always best to clear the Command Window and the Workspace Window so that there is no co-mingling of data or commands from a previous user. >> clear, clc % Clear Workspace and Command Windows 17 Being able to save intermediate results is useful when you are working on a large complex problem and you want to save those results so that you can return and continue your work. MATLAB allows you to save just some of your Workspace Window, i.e., you don’t have to save it all. To do so, you just list the variables that you want to save following the filename, >> save filename variable list % Save the variables listed in file filename To reload these variables for a future session, >> load filename If you want to export the contents of the Workspace Window to some other program you can do so attaching –ascii to the filename, >> save filename A B –ascii % Variable A and B are saved in ascii format. MATLAB uses the .dat suffix for ascii formatted data and the .mat format suffix otherwise. Just as it is useful to save variable and values, it is useful to save your MATLAB programs as you develop them or use them for future calculations. Recall that we use the Edit Window to create these list of commands or edit them. When you save the contents of the Edit Window, you must provide a filename. MATLAB stores the file in the Current Directory and attaches the .m suffix to the filename. The filename must be a valid MATLAB variable name. These are called m-files. There is a second type of mfiles for functions, for the time being we will focus on script m-files. You can recall the file from the Current Directory in the Edit Window to continue development of the program or run the program in the Command Window. MATLAB uses the ascii format to store m-files. This gives you the option to develop script m-files using another editor as long as you save the file using the ascii format and attach the .m suffix to the filename. If you want to know what m-files exist in the current directory, enter >> what MATLAB returns will all the m-files in the current directory. Since you are probably going to return and use an m-file at some future time or continue to develop your m-file, it is wise to comment it liberally during development to help you remember how it works. 18 Review the various commands and built in functions we’ve discussed in Chapter 2, operators shown on pages 50 and 51 and the additional commands and functions; i.e., isvarname, which, iskeyword, linspace. Review the Key Terms. Students should enter the two programs, Drag and UDF Engine Performance and verify the results. Assign homework from Chapter 2. 3. Predefined MATLAB Functions MATLAB is rich in built in functions. This is one of strong points in using MATLAB. We will only scratch the surface in this course, but you will have the tools to explore MATLAB further and take advantage of these built in commands. As you become a master user, you may also define your own functions and be able to use them just like any other MATLAB function. Our text, starting on page 266, list the functions that are described in the text, again, these a just small sampling. MATLAB has a number of ‘tooboxes’ that one can add to your MATLAB installation. These toolboxes contain additional functions developed for a particular engineering or mathematically area, signal processing, optimization, statistics, financial, data analysis, differential equations, on and on. As you add one or more of these toolboxes to your MATLAB installation or write your own, you are enhancing the MATLAB capabilities. Remember when you need additional information about a function (or MATLAB command), use the help command in the Command Window. >> help linspace MATLAB returns with information on how to use this built in function to create a row vector of evenly spaced increments between an initial and final value. The other key feature of these functions is that in general they operate on both scalars and matrices. So for example, >> A = 16; >> b = sqrt (A) % Compute the square root of A b= 4 >> C = [4 9 25]; >> D = sqrt(C)) % Compute the square root of the elements of C D= 235 In general functions have three components, a name, one or more inputs, and an output. 19 In the example above, for the function sqrt( ), the name is obviously sqrt, there is one input, A in the first case and C in the second case, and an output where in the first case the output, namely the square root of A is assigned to the variable b and in the second case the square roots of the elements of C are assigned to the elements of the row vector D. It is not unusual to have more than one input. Another term used to describe the inputs is arguments, i.e., a function may have one or more arguments. Some functions have no arguments. This is allowed in MATLAB. Functions can be nested, i.e., a function can be used as an argument of another function. So for example, consider >> w = pi/4; variable >> y = sqrt(sin(w)) % Assign pi/4 to w. pi = 3.14159…, a reserved MATLAB % Calculate the square root of the sine of pi/4 y= 0.84085 Using the help Feature We have already described how to use the help command in the Command Window. You can also use the Help in the menu toolbar to see a windowed version with a lot of information that you will find useful. In particular you will see a number of categories listed that you can read about for functions and capabilities in MATLAB that you may want to use at some point to solve problems. Note the two listings for the built in functions, Functions - By Category and Functions – By Alphabetical List. Also see the list of toolboxes installed that you can gain information about to see if there is something useful. To see the full list of mathematical functions in MATLAB, click on the Help button on the toolbar, then expand MATLAB and click on Mathematics in the left hand window. The Mathworks website is another place to visit. There is on line content submitted by users that is free to download and use. As we have discussed, MATLAB is rich in built in functions. The remainder of Chapter 3 describes a number of these starting with Math function, Trigonometric Functions, Simple Analysis Functions, and Random Number Functions. A number of examples are described to show how these functions are used in engineering problem solving. MATLAB also has a number functions that do not require any inputs or arguments. For example, the function pi is used to signify the mathematical constant 3.14.159…, i.e., the ratio of a circle’s perimeter to its diameter. The characters i and j are used by MATLAB to represent the imaginary part of a complex number, z = x + jy. Alternatively, i and j represent the number sqrt ( -1 ). It is a good idea to not use i or j as variables in MATLAB commands as these are reserved names. 20 If you try to divide a number by zero you will see the result Inf. Or you might see NaN this mean Not-a-Number. You typically see this when an expression is undefined. Let’s review a sampling of these built in functions. Recall that the power of MATLAB resides in the fact that these functions apply equally to scalars and matrices. When the argument is a matrix, you need to understand exactly how the function works. Use the help function command to get the information you need. >> abs(x); % Computes the absolute value of x. >> help sqrt sqrt(x) is the square root of the elements of x. Complex results are produced if x is not positive. >> x = [-3 5 -1 -5 7]; >> y = sign (x) % Form a row vector with plus and minus terms. % Row vector y contains the signs of the terms in x. y= -1 1 -1 -1 1 >> z = 1; >> w = exp (z); % Computes the value e^z i.e., e raised to the z power. >> log (w) % Computes the natural log of w. (Base e) ans = 1 For logarithms to the base 10, use the function log10 ( ) and for the base 2 use the function log2 ( ). >> b = log2 (16); ans = 4 Let’s look at example 3.1 on page 60. This example illustrates using the ClausiusClapeyron equation to calculate the saturation water-vapor as a function of atmospheric temperature. This example is detailed through the five steps in engineering problem solving. We will look at it through the sequence of MATLAB commands; Assume that we are using the Edit Window to enter our list of commands, %Example 3.1 21 %Using the Clausius-Clapeyron Equation, find the %saturation vapor pressure of water at various temperatures. % TF = [-60;10;120]; %Define the temp row vector in degress F. TK = (TF + 459.6)/1.8; %Convert to degrees Kelvin, element by element Delta_H = 2.45e6; %Define the latent heat of vaporization R_air = 461; %Define the ideal gas constant for air % %Calculate the Vapor Pressure Vapor_Pressure = 6.11*exp((Delta_H/R_air)*(1/273 – 1./TK)); %Display the results in a table my_results = [TF’,Vapor_Pressure’] We can save this script and run it in the Command Window. Suppose we saved this sequence in a file named my_results. Once it is saved you may execute it in the Command Window by entering, >> my_results MATLAB returns with a table where the first column is temperatures in increments of 10 degrees F from -60 to 120, and the second column is the vapor pressure. One could also plot this relationship by entering the command, >> plot (TF,Vapor_Pressure) The Trigonometric built in functions include sin(x), cos(x), tan(x), atan(x), and so on. Trigonometric functions are used essentially in every engineering discipline in problem solving. Getting used to using them in your sessions will greatly facilitate your future use of MATLAB in engineering problem solving. Remember the argument of the trigonometric function is always given as radians. The Simple Analysis functions include max(x), min(x), [a,b]=max(x), max(x,y), mean(x), median(x), sum(x), prod(x), cumsum(x), cumprod(x), and sort(x). There are more functions like these, you will have to explore to find them as you solve your problems. For example, the sort (x) function sorts the values in ascending order when x is a row vector and each column is sorted in ascending order when x is a matrix of n rows and m columns. All of these functions work on the columns of any two dimensional matrix. If you want to operate on the rows, simply transpose the original matrix, then use the function on the transposed matrix. For example, suppose we want to find the max value in each of the rows of the following matrix, >> x = [1 5 3; 2 4 6]; >> max ( x ) ans = 56 22 Don’t forget you can determine the size of a vector or matrix by using the size (x) command. For the matrix defined above, >> size(x) ans = 2 3 i.e., x has 2 rows and 3 columns. Using the command [a,b] = size (x) assigns the number of rows to a and the number of columns to b. Random numbers are used in many engineering problems. MATLAB provides several functions to create sequences of random numbers. The function rand( ) creates random numbers uniformly distributed between 0 and 1, whereas randn( ) creates random numbers that are normally (Gaussian) distributed. In this case the variance is 1.0. We can use these random functions to generate row vectors where each element is a random number or matrices where each element in the matrix is a random number. Random number generators need a “seed” value to initiate the process. If undefined, the seed value will be set to zero, but you can change this seed value easily. If you need a sequence of random numbers distributed between values other than 0 to 1, consider the following, First generate the sequence of random numbers between 0 and 1. >> n = 5; >> rand (‘seed’,n); >> r = rand(1,100); >> a = -5; >> b = 5; >> x = (b-a)*r + a; % Set seed value to 5 % Call the random number generate with the new seed value % Create a row vector r of 100 random numbers between 0 and 1 % New low bound % New upper bound % Create random numbers between -5 and 5 and store them in x. Gaussian random values are distributed with a mean value of 0 and a variance of 1. To scale Gaussian random values to ones having mean b and variance a, use the following scaling equation on a vector of Gaussian random values, namely, x = a*r + b where r is the original set of Gaussian random values. For example, >> x = randn(1,500)*2.5 + 3 creates 500 random values with mean value 3 and variance 2.5 stored in the row vector x. Manipulating Matrices As you use MATLAB more and more, you will see the power of describing your problems using matrices. We’ve demonstrated several illustrations where we defined row vectors, i.e., 1 x n matrices, and in so doing we simplified the programming steps to 23 get to our results. So it is important to stop and review what we know about using matrices in MATLAB and extend our knowledge. Here’s some ways to create vectors and matrices using MATLAB statements. >> A = [5,3]; % This is equivalent to A = [5 3] You can use commas or spaces to delineate elements of a row vector or of the elements in any row of an nxm matrix. >> B = [ 1, 2, 3; 4,5,6;7,8,9]; yields a 3x3 matrix with the first row having elements 1, 2, 3 and the second row having elements 4, 5, 6 and so on. Here the semicolon indicates the start of a new row in the matrix. In some cases you may have more elements than you can enter on a single line, for his case consider, >> C = [1, 5, 78, 45, -7, . . . 13, -57, 8]; Use … to extend the row onto the next line. You can also define matrices or vectors in terms of other matrices or vectors, so for example, >> D = [1.5, 3.1]; >> S = [ 3.0 D] S= 3.0 1.5 3.1 or consider, >> T = [1, 3, 5; S] T= 1 3 3 5 1.5 3.1 Sometimes we want to identify one particular element of a vector or matrix or subset of the elements. First for the case of identifying one element consider, >> y = B(3) y= 3 or 24 >> z = T(2,2) z= 1.5 Remember that when you are defining a matrix use the brackets [ ], whereas when you are referencing a particular element or subset you use the ( ). In some cases the square brackets are redundant, MATLAB knows what you are intending to do so they aren’t necessary. We’ll see that next. The Colon Operator The colon operator is a very powerful operator when it comes to defining and manipulating matrices. At first it seem a little strange but as you work with it, it will be come as easy to work with as all the other algebraic operators that you are used to using. So here are some examples, >> H = 1:8 % Creates row vector H with 8 evenly spaced elements. H= 1 2 3 4 5 6 7 8 Here the default spacing is 1. But you can adjust the default spacing as you like >> H = -2: 0.5: 3 H= -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 H has eleven elements spaced equally starting at -2.0 and ending at 3.0 with spacing 0.5. This is very useful when you want to define the domain of a function, x = 0: 0.1: 10 for example. Here x is defined from 0 to 10 with increment spacing of 0.1. If you want to evaluate some function, say y = x^2 +1 over this domain, all you need do is to write the MATLAB commands, >> x = 0:0.1:10; >> y = x^2 + 1; MATLAB evaluates the function for each value of x and creates a row vector y to store the values. Note that the square brackets are redundant here, you can use them for consistency or not. Your choice. Now consider the following, >> M = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7]; % M is a 3x5 matrix. 25 >> x = M( :,1) x= 1 2 3 x is a column vector, the first column of M. You read the notation M(:,1) as the “all the rows in column 1. Similarly, M(;,3) would be all the rows in column 3. What about M(2,:). This would be the second row of the matrix, i.e., row 2, all the columns, >> z = M(2,:) z= 2 3 4 5 6 % z is a row vector made up of the 2nd column of M. We can really go crazy now, what does M(2:3, :) mean? Let’s try it, >> w = M(2:3,:) w= 2 3 4 5 6 3 4 5 6 7 w is a 2 row by 5 column matrix, a subset of M. 4. Plotting We are going to only cover the first couple sections of this chapter, namely two dimensional plots. MATLAB can be used to generate three dimensional plots, you can certainly read the additional material and try some of the examples, but for us and this introductory class, we will concentrate on two dimensional plotting. Engineers use graphical representations of data and results to make the information more accessible and understandable. Often seeing the relationships helps determine if the solution is reasonable or there is something wrong in the computations. Graphing the results usually leads to additional insight into the nature of the problem and its underlying structures. So plotting is an important element to use and become skilled at using with MATLAB. The most common plot used by engineers is the standard x-y plot, so we will start here. Generally, for the x-y plot we call the x values the independent variable and they are defined by the x-axis of the graph, we call the y values the dependent variable and they are usually graphed along the vertical axis. The relationship between x and y may be determined experimentally, i.e., one collects data from an experiment in tabular form and uses the MATLAB plotting capability to understand the relationship or one might have a 26 mathematical expression relating x and y and one wants to use the plotting features to help understand this mathematical relationship. You will find both very useful in your engineering careers. Consider the following example, suppose we are evaluating how far a collection of football players can kick a football. We want to use this data to choose the team’s punter. After some preliminary evaluation we are down to two kickers. As coach, you have decided to have a “kick-off”. Each kicker will get 10 kicks, or 10 trials. The distance will be measured for each kick and you will plot the distances for each trial. As coach, you are sure this will help to determine who your team’s kicker will be. Assume the distances are measured in yards, The data is shown in the following table. Trial Kicker #1 Kicker #2 ------------------------------------------------1 2 3 4 5 6 7 8 9 10 72 63 70 67 62 68 60 70 63 60 69 67 70 71 70 69 67 65 68 71 Which kicker would you select and why? Consider the following sequence of MATLAB commands, >> trial = 1:10; % independent variable trial is initialized >> kicker = [72, 63, 70, 67, 62, 68, 60, 70, 63, 60; 69, 67, 70, 71, 70, . . . 69, 67, 65, 68, 71]; >> % kicker data is entered in the previous statement >> % kicker is a 2x10 matrix containing the kicker’s results >> plot(trial, kicker) >> title (‘Kicker Evaluation’) >> xlabel (‘Trial’) >> ylabel (‘Distance in Yards’) >> grid on When MATLAB executes this sequence of commands it opens a Graphic Window and plots the data. Since kicker is a 2x10 matrix, the command shown causes MATLAB to 27 plot both kicker’s results in a single chart. The Graphic Window is reused each time a new plot is made, one must either create a new Graphic Window to not loose the previous chart, or cause the new data to be plotted in the current Graphic Window. Both techniques have their usefulness. This chart is the contents of the Graphics Window following the execution of previous sequence of MATLAB commands. We will soon learn how to make the two charts more readable, but for the time being, which kicker would you choose? Kicker #1 tends to be more erratic and he tends to get tired, i.e., his distance falls off for later trials. Kicker #2 tends to more consistent although he doesn’t kick as far as kicker #1 did in trial 1. We could have entered the sequence of “kicker” commands using the Edit Window and created a script m-file. Suppose we had saved this file with the filename Kicker. Then by entering Kicker following a Command Window prompt, the sequence of commands would have been executed and the chart created as shown above. In many examples several plots might be created in the execution of a m-file. To halt execution when a chart is created you can use the Pause command. This temporarily stops the execution of the m-file and waits for you to press any key and the script will continue, or you pause for n seconds by placing Pause(n) at the point where you want execution to stop. These commands let you look at and investigate intermediate results before continuing. The first time one executes the plot command, MATLAB creates a Figure window for the results, it is called Figure 1. If you want subsequent results to be plotted in their own window simply enter Figure (2) as a MATLAB command prior to the second plot 28 command and a second Figure Window will be created for the new results. Figure 2 then becomes the active window for the next and subsequent charts. In the example above, two sets of dependent data were plotted on the same chart. We stored the data as rows in the matrix kicker. Any number of sets of data can be plotted on one chart using this approach. There are several other ways to accomplish the same result. So for example consider the following, >> kicker1 = [72,63,70,67,62,68,60,70,63,60]; >> kicker2 = [69,67,70,71,70,69,67,65,68,71]; % Kicker #1’s data % Kicker #2’s data >> trial = 1:10; >> plot (trial, kicker1, trial, kicker2) Then assuming we labeled the x and y axis as above and titled the chart the same as above, we would created exactly the same chart as shown previously. A third way to achieve the same results is shown next, >> plot (trial, kicker1) >> hold on; >> plot (trial, kicker2) >> hold off; The hold on suppresses MATLAB from over writing the current Figure with the new results and causes MATLAB to plot the second set of data in the current Figure window, in this case Figure 1. Subsequent charts will continue to overlay in Figure 1 until hold off command is executed. When MATLAB plots several data sets on one chart, MATLAB chooses to plot each on in a different color. For our example above, kicker1 is blue and kicker2 is green. We will soon learn how to use symbols and colors to highlight your charts for easier reading. Note that in all cases, MATLAB connects subsequent points with straight lines. Hence to generate smooth looking plots you have to have sufficiently small increments of the independent variable. Let’s try another example. We have an engineering system that has a sinusoidal input, sin (x) and a sinusoidal output, namely (cos (x*4))*exp(-x/(2*pi)). To help us get a better understanding of relationship between the input and output, we will use the MATLAB plotting capabilities to learn more about this system. We’ll imagine that we are using the Edit Window to create our script m-file that we will save and name Engn_Sys1 in our current directory. We begin by the edit command in the Command Window and then start entering commands in the Edit Window. >> edit % MATLAB opens the Edit Window 29 ________________ % This m-file studies the input-output relationship for an engineering system. x = 0:pi/100:2*pi; % Create the indep. variable x from 0 radians to 2*pi radians % in increments of 0.01*pi. Recall pi=3.14159… input = sin(x); output = cos (x*4).*exp(-2*x/(2*pi)); % Input to engineering system % Output of the engineering system % Note the array multiplication (.*) plot (x, input) hold on; plot (x, output) title (‘Engineering System 1’) xlabel (‘x from 0 to 2 pi) ylabel ( ‘Input-Output Relationship’) grid on; hold off; ____________________ After creating this script we store it in the m-file named Engn_Sys1 in our current directory and return to the Command Window. To see the results all we need do is enter the Engn_Sys1 command in the command window, >> Engn_Sys1 Then the following chart appears in the Graphic Window as Figure 1. 30 Since you have created an m-file and saved it in the current directory, you can at some future time edit this file, add new or modify the output function or change the domain of interest, resave the file and investigate the new input-output relationship without having the reenter all the MATLAB commands. For this simple example, it might not make much difference, but you can imagine the time savings when you have a large MATLAB program that you are using to model or study an engineering system. What do you think would happen if you entered the command, >> help Engr_Sys1 MATLAB returns with, This m-file studies the input-output relationship for an engineering system. The comment(s) at the beginning of the m-file are returned by the help function. This helps you remember what the m-file does and demonstrates why it is important to comment the operation and purpose of your m-file. Remember if you want to see what m-files have been stored in your current directory, >> what MATLAB list all the current m-files listed in the current directory. 31 Unlike the first example, when we invoke the plot function twice as we did in this example, each line is drawn in the same color by default. Had we used one plot command as we did in the first example, MATLAB would have plotted the two lines using different colors. Next we explore how to choose colors and symbols for your plots where you have multiple lines on the same chart. This greatly enhances the readability of the chart. MATLAB allows you to choose the line style, the point type and the color for each of the lines you plot on a chart. This is accomplished by adding a string of characters after each set of x-y arguments in the plot command. To denote a string of characters in MATLAB, you surround the string with single quotes, i.e., ‘this is a string of characters’. We have already done this when we labeled and titled our charts in the previous examples. When you need help to determine the various options you have, you can always get the information by entering the command, >> help plot MATLAB returns with information about the plot command including the information on the line styles, point types, and colors. This information is also summarized in out text on page 107. So for example, suppose we want to use the line style, dotted, the point type, star, and the color, red, for our x-y chart. We’d accomplish this in the following way, >> plot (x,y, ‘:*r’) % Plots y as a function of x, line dotted, points stars, color red When we have multiple lines being plotted with one plot command, each set of x-y arguments is followed by the string of style definitions that you have chosen. If you do not specify them, MATLAB uses its default definitions. Note that the order that you specify the style information is arbitrary. In all the examples we have explored and that are in the text up to this point, MATLAB has automatically chosen the scales for the x and y variables. MATLAB allows the user to define the scales for the axes with the axis command. Consider >> v = [xmin, xmax, ymin, ymax]; >> axis(v); v is a row vector made up of 4 elements, namely the minimums and maximums for the independent and the dependent variables. The command axis(v) then sets these new scales for the x and y axis for subsequent plots. Use of the axis command without an argument freezes the current scale for future plots. A second use of the axis command returns to automatic scaling. MATLAB offers several additional functions that allow you to annotate your charts, namely the legend ( ) command and the text ( ) command. These are described in the 32 text on page 108. The legend command allows you to show a sample of each line style you have selected and lists the style string that you specified. This is useful to annotate what each lines represents in your chart. So for example in our previous example had we plotted the input and output with different line styles (recall we didn’t do this), we could have added this command to our m-file Engn_Sys1, legend (‘input’, ‘output’) after the ylabel command. In so doing, samples of the line styles and labels input and output would be placed in a small box inside the chart to identify each line and its corresponding style and label. This is very helpful to make your charts more readable especially when you have several lines plotted in the same figure. At this point, let us look at Example 4.2 from the text to bring these concepts together. Example 4.2 asks us to explore the range of a projectile shot from a cannon at an angle theta with respect to the x-axis for two initial velocities, 50 m/sec and 100 m/sec. We know that range is related to the initial velocity, but how is it affected by the angle of the cannon with respect to the x-axis? After some exploration in our physic book, we see that the range(theta) = ((v^2)/g)*sin(2*theta) where 0 <= theta <= pi/2. (Read this inequality as theta being greater than or equal to 0 radians, and less than or equal to pi/2 radians). v is the initial velocity and g is the acceleration due to gravity. g = 9.9 m/sec^2. We want to develop a script m-file, call it Engn_Sys2, and plot the range versus the angle theta to study this problem. After entering the edit command in the Command Window we enter our MATLAB statements, % Example 4.2 % This program called Engn_Sys2 calculates the range of a ballistic projectile % at two different initial velocities. % % Define the constants g = 9.9; % Acceleration due to gravity, m/sec^2 v1 = 50; % Case one, initial velocity 50 m/sec v2 = 100; % Case two, initial velocity 100 m/sec % Define the angle vector between 0 and pi/2 angle = 0:0.05:pi/2; % Calculate the range for each case R1 = (v1^2/g)*sin (2*angle); R2 = (v2^2/g)*sin (2*angle); % Plot the results plot (angle, R1, angle, R2, ‘:’) 33 title (‘Cannon Range’) xlabel (‘Cannon Angle from x-axis’) ylabel (‘Range in meters’) legend (‘Initial velocity = 50 m/sec’, ‘Initial velocity = 100 m/sec’) After saving this file in our current directory with filename Engn_Sys2, we are ready to execute the program and view the results. >> Engn_Sys2 One result of our analysis is obvious from this chart. The maximum range occurs for theta equal to pi/4 independently of the initial velocity. Of course the maximum range does depend on the initial velocity, but the angle that maximizes the range is always the same, namely, pi/4 or 0.785 radians. Notice the legend box has been added to make the chart more readable. MATLAB offers a number of other two dimensional plotting capabilities that we will review briefly in addition to the x-y plots that we have already discussed. The additional plotting capabilities include polar plots, semilog and loglog plots, bar graphs and pie charts, and histograms. Each of these additional plotting capabilities has a role in engineering solution, particular the polar, and log plots. Bar charts, pie charts and histograms are useful in analyzing data groupings for patterns or distributions. 34 Polar Plots- Polar plots are useful for represent complex quantities of the form z=x+jy or functions of complex variables. Here x is the real part and y is the imaginary part of the complex number z. Another way to represent z is in polar coordinates, namely, z has magnitude rho and angle theta in radians. In this form, z is represented as a complex exponential. We use the polar plotting feature to plot rho and theta, >> plot(rho, theta) where rho and theta are two vectors of length n. For each value of index of theta there is a corresponding value of rho or the magnitude of the complex number. See the text for the sine function plotted in polar coordinates from 0 radians to pi radians. What do you think it would look like if you continued to plot from pi radians to 2*pi radians? Try it out and see what happens. Logarithmic Plots- When either the independent or the dependent variable (or both) range over many orders of magnitude (powers of 10), it is useful to represent the data using one of the logarithmic forms. Recall the plot (x,y) uses a linear scaling of the axis. For logarithmic plotting we have three forms to choose from. 1. semilogx(x,y)- Use this form when the independent variable x ranges over many orders of magnitude. 2. semilog(x,y)- Use this form when the dependent variable y ranges over many orders of magnitude. 3. loglog(x,y)- Use this when both x and y range over many orders of magnitude. Since logarithms of zero or negative numbers do not exist, if you have either in the results that you are trying to plot, MATLAB will issue you a warning message and delete the point from the chart. If you end up in this situation, you have probably done something incorrect in your computations and need to start there to see what is wrong. Bar Graphs and Pie Charts- As discussed previously, these charts are valuable techniques for displaying data to see patterns and or distributions. Some options include, 1. bar(x)- Vertical bar chart when x is row vector. When x is a matrix, bar(x) groups the data by row. 2. barh(x)- Horizontal bar chart of the data x. If x is a matrix, barh(x) groups the data by row. 3. pie(x)- Generates a pie chart from x. Each element in the row vector or matix is represented as a slice of the pie. In all cases, x is either a row vector of length n or an mxn matrix. Histograms- Histograms are special types of bar charts often used and relevant to statistics. Histograms help you visualize the distribution of data and to see how it groups. MATLAB sorts the data contained in vector x into one of 10 bins (default case) and draws a chart to show the number of samples in each bin. If we have a large number of 35 data points and we want to divide it up more finely we can increase the number of bins for the sorting. Suppose we have 18 students how have taken the final exam in Engineering 101. We can use the histogram function to see how the scores are distributed, >> x = [78,82,56,95,73,45,59,79,83,92,71,64,52,59,49,67,75,55]; % Student scores >> hist(x) To have more bins than the default number of 10 between the minimum and maximum values, use the command hist (x,20). Here 20 bins are used. From our histogram, we see that 2 students scored between 90 and 95 points, 2 students scored between 80 and 85, and so on. The second argument of the hist (x,y) command defines the number of bins. In additional to the plotting capabilities that we have discussed, MATLAB offers a number of others, called specialized 2-D plots. These include the ability to plot discrete sequences of data using the stem function, which is used in digital signal processing to view input and output sequences. Other plots include the feather plot, the rose plot, the compass plot, and scatter plot. Use the help function of learn more about these plotting capabilities and how and when you should consider using one of them. Our final topic of discussion for 2-dimensional plotting is the ability to split the plotting window into subwindows. To accomplish this we use the subplot function. Normally, one doesn’t split the graphic window into more than 4 subplots, else they become to small to be useful. For our example we’ll assume that we want to split the graphics 36 window in 4 subplots. The function subplot has 3 arguments, subplot(m,n,p) where m and n are integers that tell MATLAB to partition the graphics window into an array of mxn plots. That is, an array of m rows and n columns of plots. For the case of 4 subplots, usually m=2 and n=2. The integer p tells MATLAB which of the mxn plots to use the next time the plot function is used. The plots are numbered from left to right, top to bottom. So p=3 means the plot identified in the second row, first column. So for example, after we have used plots 1 and 2 and we want now to plot in graphics subplot window 3, consider, >> subplot(2,2,3); >> plot (x,y) % Select subplot number 3 in or 2x2 grid of plots % Plot our function Immediately following the plot command with title, xlabel, and ylabel, legend, etc., will label subplot 3 appropriately. Editing Plots from the Menu Bar and Creating Plots from the Workspace WindowMATLAB provides two additional capabilities regarding plotting that you may find useful from time to time. First, when you have created a chart in the Figure window, click on Tools and Insert in the Figure window tool bar. The Insert button features allow you to fine tune the appearance of your chart, you can add or change the title, axis labels, legends, etc. The Tools button allows you to change the way the chart looks by zooming in or out, changing the aspect ratio, etc. Once you have finally modified your chart to its final form, use the Edit button and select Copy Figure. This will allow you to paste your results into a word processing document like Word or Powerpoint. Note: Any editing you do to a chart following the execution of your MATLAB program is lost the next time you run the program. Finally, if you want to view graphically a variable in the Workspace Window, click on the variable to select it and then click on the plotting icon in the Workspace Window Toolbar. This will cause MATLAB to generate a chart in the Figure window. You can annotate the chart using the editing features described above. Several variable can be plotting in the same Figure window by selecting the first, holding down the Ctrl key and selecting the others by clicking on them. This ends our discussion of two dimensional plotting using MATLAB. But we have not exhausted all the capabilities in MATLAB for plotting. You can investigate additional capabilities using the help facility in MATLAB or more advanced textbooks that you can research at the www.mathworks.com website. After all is said and done, the x-y plot, the semilog and loglog plots are the ones most useful in engineering. 5. Programming in MATLAB Up to this point we have been using the Command Window as a scratch pad or we have written simple sequences of MATLAB commands. We have imbedded the data within 37 the progam or entered it in the Command Window. Our sequences of commands have not interacted with the user for input nor have they used logical operators to control the flow or our programs. As we become a more sophisticated user of MATLAB, we will want to write and then reuse our programs for new data. Our programs will become longer and more sophisticated as well. We will also want to write new functions, save these functions and use them in future m-files just as we use the built in functions in MATLAB. In this section we will explore writing more complicated programs, writing new functions, using input and output statements, and using logical operators to control the flow of our programs. Before we look and input and output commands we need to review one of the matrix operations that we have earlier studied. Recall we defined the operator (.*) as the element by element multiplication of two vectors each with the same number of elements, so for example, >> x = 1:5 x= 12345 >> y = 6:10 y= 6 7 8 9 10 >> a = x .* y % a is formed by element by element multiplication. a= 6 14 24 36 50 MATLAB refers to this type of multiplication as array multiplication to distinguish it from true matrix multiplication that we will study later on. Note that x and y must have the same number of elements. In some engineering problems we will want to multiply each element of say x by each element of y and form a new matrix of these results. The new matrix formed will be have dimensions length of y by length of x. Note we do not require that x and y have the same length to do this. So suppose we redefine y as, >> y = 11:13 % y is a row vector of three elements y= 11 12 13 >> [new_x, new_y] = meshgrid(x,y) % Form a new matrix new_x = 12345 38 12345 12345 new_y = 11 11 11 11 11 12 12 12 12 12 13 13 13 13 13 Now when we use the .* command with these two matrices, we have >> B = new_x .* new_y B= 11 22 33 44 55 12 24 36 48 60 13 26 39 52 65 You might be asking why do all this? An alternative way to develop the matrix B is to use a loop and compute each row, one at a time. This is certainly acceptable, but one of the important aspects of MATLAB is to be able to write command sequences without the need for programming loops. Hence, MATLAB has defined a number of functions to facilitate loop-less sequences. When you study example 5.1 starting on page 141 of our text, you will see the utility of such a function. Here in this example one wants to compute the distance for a free falling body traveled in from 0 to100 seconds on each of the planets and earth’s moon. Here we have two variables, time ranging from 0 to 100 seconds and the acceleration due to gravity on each of the planets and earth’s moon, that is we have two variables that we need to accommodate in our solution using MATLAB. Note that the solution uses the meshgrid(G,T) function of create two new matrices, g and t. Initially G = [accelerations due to gravity] and T = 0:10:100, the matrix of time increments in seconds from 0 to 100 seconds. Note the length of G is 10 (see example in the text) and T is 11. Therefore, g is a new matrix where each row of g is the same as G, and there are 11 rows in g. t is a matrix with each column of t being the same as T’, that T transpose and there are 10 columns in t. Hence g is an11x10 matrix and t is 11x10 matrix. When we use the command d = ½ * g.*t.^2 the following operations are performed in MATLAB. 1. First all the elements of t are squared. 2. The first row in d is formed by multiply element by element the first row of g and the first row of t. 3. Repeat for all the rows of g and t. 39 4. The first row of d is the distance of free fall for all planets and the moon for 0 seconds. 5. Each subsequent row of d is the distance of free fall for 10 seconds, 20 seconds, etc., respectively. 6. Finally all elements of d are multiplied by the scalar ½. Finally then, the first column of d is the free fall distances for planet 1 for all time increments. Column 2 in d is for the second planet, and so on. Although it may seem confusing at first, our sequence of MATLAB is greatly simplified. Now let’s move on to input and output statements. Input/Output MATLAB provides several commands to allow a user to interact with their program while it is executing, namely, input, disp, fprintf and pause. Previously we discussed the pause command. By inserting it in a sequence of commands, usually at some point where we want our program to pause so that we can study intermediate results, we cause the program to stop executing until we hit a key on the keyboard to continue. This is useful in debugging programs and may be removed at a later time when we know that the program is functioning as we expect. In some cases, rather than including the data used as input data in the program itself, we want to have the program stop and ask for input. This lets the user enter the data for this particular trial. Once the input data has been entered by the user, we would like the program to continue execution. We use the input command to achieve this result. The input command is usually used in the follow way, >> z = input (‘Enter a value for z’); Enter a value for z The program halts execution waiting for the user to enter a value for z. Upon entering a value for z and hitting Enter the program continues. MATLAB assigns the input to the variable z. If you place a semicolon after the input (‘Enter a value for z’); statement as shown here, z is not echoed by MATLAB. If you leave the semicolon off, z will be echoed. When a matrix is expected as input, remind yourself of this, for example, >> z = input (‘Enter the matrix for z’); Enter the matrix z [1,2,3; 4,5,6] (hit Enter) Then your might type in [1, 2, 3; 4, 5, 6] and hit Enter. Note your have to follow all the rules for entering matrices. 40 With the semicolon at the end of the input statement, the matrix z is not echoed. Let’s review how one typically uses these input statements in a MATLAB program. Assume we are entering the program using the MATLAB editor. % Free Fall Study clear, clc % Request the input data to use in the program. g = input(‘What is the value of acceleration due to gravity?’); start = input(‘What is the initial starting time?’); finish = input(‘What ending time would you like to use?’); incr = input( ‘What increment of time do you want to use for the calculations?’); t = start:incr:finish; %Calculate the distance a body falls d = (1/2) * g*t.^2; % Plot the results using the loglog plotting feature loglog ( t,d) title (‘Distance traveled in free fall’) xlabel (‘time in seconds’), ylabel (‘distance in meters’) % Show the maximum distance traveled for the input conditions. final_distance = max (d) As always, give this m-file a name, call it free_fall_analysis and store it in the current directory as an m-file. Then upon entering the command in the Command Window, the following takes place, >> free_fall_analysis What is the value of the acceleration due to gravity? 1.6 What is the initial starting time? 10 What ending time would you like to use? 100 What increment of time do you want to use for the calculations? 10 final_distance = 8000 41 This chart is created as Figure 1. As each input statement is executed, the string requesting the information is shown, the execution of the program pauses until the uses enters the value requested and hits the Enter key. Note that the semicolons following the input statements suppress the echoing of the input values. If you want to verify correct entry of these values, remove the semicolons until your program is functioning as intended. Output Options To this point in our study of MATLAB, when we have chosen to output a variable, we have simply typed the variable without a semicolon and MATLAB has echoed the value of the variable at that time. Since variable values can change as a program executes, it is always the case that the last value associated with the variable is echoed by MATLAB. In all the previous examples, MATLAB has displayed the results using a default format. There are two other than default displays that we will study next, namely the disp function and the fprintf funchion. Obviously, the disp function is shorthand for display. Consider the following, >> x = 1:5; x= 42 1 2 3 4 5 MATLAB has echoed the contents of the matrix x. This is what we have already seen. Nothing new here. >> y = 1:5; >> disp(y) 1 2 3 4 5 % With the semicolon, MATLAB does not echo. % Enter disp (y) to display the contents of y. >> disp (‘The values in the y matrix are:’) The values in the y matrix are: The disp function can be used to display strings of characters. Now suppose we had entered the following two disp commands into an m-file, disp (‘The values of the y matrix are:’) disp (y) When these two disp functions are executed, the output in the Command Window would look like, The values of the y matrix are: 1 2 3 4 5 A much better presentation would be to include the values of the matrix y following the colon so that the display would look like, The values of the y matrix are: 1 2 3 4 5 How do we do this? Since the disp function requires a matrix as its argument, we need to combine the values in the matrix y with the string of characters to create a single matrix of characters. Fortunately for us, MATLAB make list very easy to do. We use the MATLAB function called num2str, and you guessed it, we would call this function, number to string. So now consider entering the following commands in the command window, >> A = [‘The values in the y matrix are: ‘ num2str(y)]; >> disp(A) A is a matrix is a character array, containing the string of characters, “The values in the y matrix are: and append to the end of that string is another string of characters, 1 2 3 4 5. When the matrix A is displayed, we see The values in the y matrix are: 1 2 3 4 5 43 which is exactly the presentation that we were looking for. Our second display function is fprintf. This function gives a lot of control over the output display formatting, much more than either the default case or even the disp function. By properly using this function for displaying output information, your output will be much more readable. fprintf allows your to mix strings of characters of descriptive information with your output data and specify how you want your data formatted including the number of fields to use to present your data. Here the number of fields means the number of characters to use to represent your data. Let’s see how this works. fprintf requires two arguments, a format_string and a list of variables. In general the variables are scalars or matrices. The general form is then, fprintf (format_string, var1, var2, …) Consider the following example from the text, temp = 98.6; fprintf (‘The temperature is %f degrees F ‘, temp); MATLAB displays The temperature is 98.600000 degrees F The %f sequence in the fprintf command tells MATLAB to output the value of temp at this location in the string and to use fixed point notation, which is always of the form, xxx.yyyyyy. There will always be 6 decimal places displayed for fixed point notation. Other options are %e for exponential notation and %g where MATLAB displays the shorter of %f or %e. Before continuing we have to back up for a moment. When MATLAB displays the line The temperature is 98.600000 degrees F MATLAB leaves the cursor at the character following the last character in the format_string, here we left a space following the F in the format_string. If we execute another fprintf command, the printing will start at this point which is probably not what we want. Rather we’d like the printing to start on a new line. So let’s modify the original fprintf command to take care of this for us, fprintf (‘The temperature is %f degrees F \n’, temp) The \n character tells MATLAB to linefeed and carriage return to the beginning of a new line. When you introduce more flexibility you have to worry about more things, it is just the way the world works, so for us, as we want to have more flexibility in how our 44 display looks, we have to worry about carriage returns, and line feeds. The four special characters that we can use to control the display operation are Format Command Description ________________________________________ \n \r \t \b Linefeed Carriage return Tab Backspace Now having figured out how to control the format command, let’s return to the format_string definition. In many cases, we would like to control the width of the field and the number of decimal places that we would have MATLAB use to display a number. We do this with the slight modification to the %f string. For example, %8.2f means, display the result in a field of 8 characters with 2 decimal places. If the number we are displaying has less than eight characters, MATLAB fills with spaces. So for example, the number 98.6 displayed using a format or %8.2f would appear as 98.60 where there are 3 spaces to the left of the 9. The decimal point is included as one of the fields in the width of 8. All the examples so far have the argument var1 in the fprintf statement represented as a scalar. To the power of MATLAB, suppose var1 is a matrix. patient = 1:3; temp = [98.6, 100.1, 99.2]; history = [patient; temp]; fprintf ( ‘Patient %4f had a temperature of %7.1f degrees \n, history); MattLab would output the following Patient 1 had a temperature of 98.6 degrees Patient 2 had a temperature of 100.1 degrees Patient 3 had a temperature of 99.2 degrees Note that history is a 2 row by 3 column matrix. The fprintf command displays the values in the first column, then the second column, and so on. Also we could have replace the first three statements with the single statement, history = [1:3; 98.6, 100.1, 99.2]; or we could have written the fprintf statement as, fprintf (‘Patient %4f had a temperature of %7.1f degrees \n, patient, temp) 45 Like many other topics that we have introduced and discussed, we have only scratched the surface on using input and output functions. More can be explored by using the MATLAB help feature. But at least for now you have additional information on using the input function and the output function, fprintf. These functions help you develop MATLAB programs and generate formatted output. MATLAB Functions MATLAB is built around a number of functions, some general purpose and some developed for dealing with special problem solving needs. You are already familiar with a number of functions and have been using them in your exercises. A function is simply a piece of computer code, MATLAB statements, which accepts one or more inputs from the user of the function and provides an output to the program. Functions are re-useable pieces of code. Their value derives from the fact that we want to use the function over and over again without having to type in the sequence of commands each time. It may not be so obvious, given the kinds of examples that we have been assigned, the value of functions, but suppose you are studying an engineering problem and as you study this problem you generate a series of functions that help you analyze the problem for various input conditions, parameters, etc. What you will want to do is to develop the functions that you will require, test them, save them for future use and then use them in your future computations. MATLAB contains a number of toolboxes for specialized computations in engineering, mathematics, business, etc. These toolboxes are precisely a collection of functions that have been developed and found useful. To study how to write functions we need to understand the syntax used to define functions, the properties of local vs global variables, naming, and the general rules for writing functions. We’ll study each of these as we go. Function Syntax User defined MATLAB functions are written using the MATLAB editor and saved as mfiles in the current directory just like we have done previously for script m-files. Functions have a special form though that distinguish them from script files. Let’s look at a built in function that we are familiar with, namely the function sin which computes the sine of a angle specified by the user. A typical use for this built in function might be, >> y = sin (x); % x is expressed in radians This built in function computes the sin of x, x a scalar or a matrix, and returns the value and assigns it to variable y. If x is a matrix, y will be a matrix. If x is a scalar, y will be a scalar. This function has a name, namely sin, and a list of input arguments, namely x. In this case, the sin function returns a value. All functions are required to have a name, but functions are not required to have input arguments nor are they required to return a value(s). Having said that, most of the functions that you will probably develop will have input arguments and will return a value(s). 46 Hence in defining a function, the first statement must include its name and the list of input arguments. Listing a series of MATLAB comments following the initial statement in the function documents what the function does and helps you remember how to use the function. Moreover, if you use the help command followed by the name of your function, those comment statements are displayed in the Command Window to help you remember how to use the function. Comments are a good thing, use them liberally. Let’s look at a simple case of a function that you might want to write and save and use. We open the MATLAB Edit Window and compose the following, function s = f(x) % This function named f, adds 3 to the input provided by the user. s = x + 3; That’s it, save this as an m-file named f in the current directory. You save the m-file as the function name. Typing help f in the Command Window results in the following, >> help f This function named f, adds 3 to the input provided by the user. >> b = f(3) b= 6 A slightly more complicated function to perform array multiplication on two row vectors might look like this, function output = g(x,y) % This function performs array multiplication for two inputted row vectors that % must be of the same length. a = x.*y; output = a; Saving this m-file with filename g makes this function available for future use in your programs. Suppose we have more than on value to return. How do we handle that case? Consider the previous example, suppose we also want to return the maximum value following the array multiplication of the two row vectors. function [max-value, output] = g(x,y) % This function performs array multiplication on two inputted row vectors that must be % the same length. It also returns the maximum value from the returned row vector. a = x .* y; output = a; max_value = max (a); 47 This function returns a row vector and a scalar quantity. Once we have written this function and saved it with filename g, consider how we might use it. Imagine we are writing a sequence of MATLAB statements and we want to use the function g. >> a = [1,2,3]; >> b = [5,6,7]; >> [d,e] = g (a,b); >> d % Some vector called a % Some other vector called b % Call the function g with inputs, a and b d= 21 >> e e= 5 12 21 Local Variables One observation to be aware of when you write and use functions is that the variable names that you use within the function are local variables. They are only known within the body of the function. So in our example above for the function g, the variable a, the variable output, and the variable max_value are all local variables. When we invoke the function g, the variables a, b, d, and e are called Workspace variables and will show up in the Workspace Window. Note that in this example, the variable a appears as a Workspace variable and a local variable.. This is ok since MATLAB is able to keep local variables, i.e., variables within functions and global variables, those outside of the function, as two distinct variables. MATLAB does not permit a function to use variables outside its definition, i.e., Workspace variables, and MATLAB does not allow the main program to reference variables used within the function. The only communication between the main program and a function is through the function’s input arguments and the only way to get information out of a function is through its function output. Naming Function M-Files Recall that when we developed a script m-file we needed to name it to save it in our current directory. This name could be anything we wished to name it, the only thing that was required was that the filename must be a valid MATLAB variable name. For functions one additional requirement is imposed, the filename must be the name of the function defined in the first line of the function definition, function [max_value, output] = g (x,y) 48 Here the function must be saved with filename g. By so doing, when you use the function later in a program and call the function g, MATLAB will know how to identify it in your current directory. Note that it is possible to name one of your functions with one of the built in function names, but this is not recommended. If you do this, MATLAB will always use the function that you defined rather than the built in one as long as it is in the current directory or until you change the current directory. The built in function is not destroyed, yours is just used first. Danger!! Rules for Writing and Using Function M-files Here’s a summary of the rules for writing and using functions that we have discussed in some detail. a. The first line of a function is very specific. It starts with the word function followed by the output argument or matrix of output arguments, an equal sign, the name of the function followed by the list of input arguments enclosed with parentheses. Ex: [max_value, output] = g (x,y) b. Comments- The first few lines should always be comments describing what the function does, how it works, and anything else that would be useful for someone using the function as some later time. These comments will be displayed when the user uses the help command. c. To return information from a function, the function must contain a statement within the body of the function assigning this information to the output(s) arguments. Ex: output = . . . . . . max_value = . . . . d. A function with multiple input arguments, those arguments must be listed in the function statement following the name of the function surrounded by parenthesis. e. A function that is going to return more than one value must show all the values to be returned as a vector in the function statement, see a. above. f. The main program and the function may use the same variable names. Any value computed in the function other than the ones assigned to the output(s) arguments are not accessible to the main program. g. MATLAB provides two built in functions to determine the number of input and output arguments for a function, nargin and nargout. For example, for our function g, 49 >> nargin (g) ans = 2 >> nargout (g) ans = 2 h. When you have finished writing and testing your function, you must save it in your current directory with the filename the name of the function found in the first line of the function definition. That’s it. Remember functions are fun and powerful tools in MATLAB. We will be writing some functions for the assignments to follow to practice writing and using them. Let’s write a short MATLAB program and a function that let’s a user input an angle in degrees and computes the same angle in radians. We’ll call the function deg2rad, it will have a single input argument, namely the angle in degrees and a single output argument, namely the angle in radians. We start by first developing the function, and then the main program. Assume that we are using the Edit Window, function angle_in_radians = deg2rad (angle_in_degrees) % This function converts an angle in degrees to an angle expressed in radians. angle_in_radians = angle_in_degrees*pi/180; That’s it for the function, now save it in the current directory with filename deg2rad. For our main program, we want to query the user to input an angle in degrees. The main program will call the function to make the conversion and then it will display the results. We clear the Edit Window and begin again to develop our main program, this time it will be a script m-file. % This m-file can be used to convert degrees to radians. clear, clc % Ask the user to input an angle in degrees x = input(‘Enter the angle in degrees: ‘); y = deg2rad (x); % Display the angle in degrees and in radians in a formatted statement. fprintf (‘The angle %7.2f degrees is the same as %7.3f radians. \n’, [x;y]); Now save this script m-file with filename convert. To convert an angle, consider >> convert 50 Enter the angle in degrees: 45 (The user enters 45 and hits Enter on the keyboard.) The angle 45.00 degrees is the same as 0.785 radians. Let’s do this again, but note what we are doing now, >> convert Enter the angle in degrees: [30,60,90] The angle 30.00 degrees is the same as 0.524 radians. The angle 60.00 degrees is the same as 1.047 radians. The angle 90.00 degrees is the same as 1.571 radians. Statement Level Control Structures One topic we need to discuss is statement level control structures and the relationships between relational and logical operators. These operators allow the user to control the operation of their MATLAB programs based up internal computations within their program or some external input to the program. In all the previous cases that we have explored, the sequence of commands has been unidirectional, we started at the first statement, executed the statements one at a time until we reached the last statement and then the program stopped. We categorize this structure as a sequence. Two other structures that we want to introduce are the selection structure and the repetition (loop) structure. For the selection structure, the program starts execution until it reaches some point where a determination to proceed with sequence #1 or start sequence #2 is made. This determination is based upon a relational or logical operation. For example, suppose the variable x has been computed and we determine the sequence to follow, either sequence #1 or #2 based upon whether x greater than zero or not. If x > 0 then follow sequence #2, if x is not greater than zero, then continue with sequence #1. This would be an example of using a relational operator. We may also be using logical operators as well to determine next sequence of commands to follow. The repetition structure is somewhat more involved. It normally involves a sequence of commands that we want to execute some number of times based upon a value tested by either a relational expression like x>0 or a logical operator such as x >0 and y >0 or a combination of both as shown here. For this case, ‘and’ is the logical operator. The sequence of commands is typically called a loop. When MATLAB evaluates a relational expression or a logical expression, it returns a value of 1 or 0, 1 if it is true and 0 if it is false. So if one would enter the following, >> x = 3; >> x > 0 51 ans = 1 If x and y are matrices, then MATLAB returns a matrix of comparisons element by element, so for example, >> x = [1,2,3]; >> y = [3,2,1]; >> x == y % Note == is the relational operator, equal to. It does not change % the value of x, i.e., == is not the assignment operator = ans = 0 1 0 >> x < y & x > y % x less than y and x greater than y ans = 0 0 0 >> x ~= y % x not equal to y ans = 1 0 1 In summary then, the relational operators are less than, less than or equal to, greater than, greater than or equal to, equal to, and not equal to. The logical operators are and, not, or. The symbols used in MATLAB are summarized in section 5.4.1 of our text, pages 162 and 163. MATLAB allows for the relational and logical operators to operate on scalars and matrices. For our purposes of learning MATLAB and the kinds of problems that we will solve using MATLAB, it is reasonable to assume that we will only be using scalars in our relational or logical expressions. This simplifies our studies and reduces complexity and confusion. Our text does discuss the more general case where matrices are used in the comparisons and we’ll leave it up to you to read this if you want. As you become a more sophisticated user, you may want to review these capabilities. Before we look at if, for and while statements, we look at an interesting MATLAB command called find. Consider the MATLAB statements, >> temp = [100, 98, 94, 101, 93]; >> find (temp<95) What does this statement do? First recall that the statement temp<95 is a relational statement and MATLAB returns a row vector of 5 elements in this case, 0 if the corresponding element of temp is => 95, and a 1 in the corresponding element of temp is < 95. 52 That is, MATLAB would return the row vector [0 0 1 0 1] for the command temp<95. What does find(temp<95) return? ans = 3 5 a row vector of length 2 with the indices of the row vector temp where temp < 95. Hence if we entered, >> temp(3) ans = 94 >> temp(5) ans = 93 If, For and While Statements MATLAB supports three general forms, If, For and While statements to control the sequence of execution of programs. There will cases where these statements will be required, but in general MATLAB is so designed that most programs can be written as a linear sequence of instruction. Let’s explore each and see where they can be used. Note that in general we will only be interested for relational or logical statements using scalars. This is our simplifying assumption. First we will look at if, else, and elseif statements. The syntax for a simple If statement is if comparison statements; end % Indented only to show the body of the If statement When the relational or logical expression signified in this example as the ‘comparison’ is true, then the sequence of statement between the if statement and the end statement will be executed. If the ‘comparison’ is false, then the sequence is skipped. By adding the else statement we can generalize the if statement to include both cases, if the ‘comparison’ is true and if the ‘comparison’ is false. To see this consider, if comparison 53 statements #1 else statements #2 end Here for this example, if the ‘comparison’ is true statements #1 will be executed, if it is false, statements #2 will be executed. One set of commands will be executed in all cases. The final form of the if command is the if elseif form. Here we can nest several ‘comparisions’ and execute the set of instruction for the ‘comparison’ that is true. Consider, if comparison1 statements #1; elseif comparison2 statements #2; elseif comparison3 statements #3; . . . else statements #n; end Here if comparison1 is true, statements #1 will be executed. Then the first command following the end statement will be executed. If comparison1 is false, comparison2 will be tested. If it is true, statements #2 will be executed followed by the first command following the end command. And so on as you can infer. If none of the comparisons turn out to be true, statements following the else will be executed. At the completion of one set of commands, command execution continues with the first statement following the end command. Let’s go over an example to see the if command in action. Example 5.6 asks us to develop a function that assigns a letter grade, A, B, C, D, E to a numerical score, A or 90 to 100, B for 80 to 89, etc. We also want to check that the numerical value enter is a number between 0 and 100. If it is outside this range, then the function needs to return the fact that the input is illegal and try again. function results = grade (x) % This function requires a scalar input x, a numerical value between 0 and 100. % The function returns a letter grade assigned to the numerical input. if (x >= 0 & x <= 100) if (x >= 90) results = ‘A’; % Assign the letter grade A if (x >= 80) results = ‘B’; % Assign the letter grade B if (x >= 70) 54 results = ‘C’; if ( x >= 60) results = ‘D’; else results = ‘E’; end % Assigns the letter grade C % Assigns the letter grade D % Assigns the letter grade E else results = ‘Illegal Entry, Try Again’; % x is not between 0 and 100 end Note that this function uses both the if else form of the if command and the elseif form of the if command. When an argument is passed to the function, if it is not between 0 and 100, the function returns with the string, Illegal Entry, Try Again. When the argument is between 0 and 100, the elseif command is used to sort out if it is greater than 90. greater than 80 and so on and the appropriate letter grade is assigned. The function returns a string of one character with the corresponding letter grade. So once this function has been written and saved as a m-file with filename grade we can use it. >> grade (75) ans = C >> grade (101) ans = Illegal Entry, Try Again >> Our next statement is the for command. for commands help us control the number of times we want a loop to be executed. When we know how many times we want to loop through our set of statements, the for command is preferable to the while command. The syntax for a for command looks like this, for index = expression; statements; end In most cases that you will deal with, index is a variable, expression is a row vector, and the statements will be executed in a loop for each value of the index defined by the expression. The expression is typically a row vector. So suppose we have, for k = 1:10; statements; end 55 Here for the initial execution of the statements, k = 1, for the next execution of the set of statements, k = 2, and so on. The last execution of the statements has k = 10. Following this execution of the statements, the loop ends and the next command is the first one following the end statement. Some general guides for using the for command, 1. Normally use the for command when you know in advance how many times you want to loop 2. expression is generally a row vector, defined by initial:increment:final values 3. As long as the index is between initial and final the execution will continue to loop 4. index is incremented by increment each time through the loop, starting with initial 5. When index is greater than final, execution ceases and the next command executed is the one following the end command 6. Stay away from using i and j as variable names for the index, these are reserved MATLAB names used to represent the imaginary part of complex numbers. Our last statement control command is the while command. Whereas we use the for command when we know the number of times we want to execute a sequence of commands, one typically uses the while command to repeat the sequence of commands until some condition is met. while expression statements; end % expression is a relational or logical expression Here, when the while command is first encountered, expression is evaluated. If it is true, then the statements are executed and the expression is evaluated again at the end of the first pass through the statements. This execution of the statements needs to modify the variables used in the expression so that at some point when the expression is evaluated for the nth time, it is now false. When expression is false, execution continues with the first command following the end statement. MATLAB defines a break command that is useful when you use loops. You would normally use the break command in the main body of the loop following a relational or logical expression. If the expression is true, then by using break you can exit from the loop and continue execution following the end command. The break command gives you a safety value for exiting loops that have gone out of control. There is a trade off between using and not using loops in MATLAB. For the beginner MATLAB user, loops are often easier to understand and easier to visualize the calculations being performed in MATLAB, but using loops tends to be inefficient. Developing MATLAB programs using the array and matrix multiplication facilities is faster but it may be more confusing. One way to approach this conundrum is to first develop your programs in a way that helps you understand the flow and then work to make them more efficient once you have debugged them. 56 6. Matrix Computations At this point we are going to return to studying how MATLAB uses matrices effectively in calculations. Many engineering problems can be formulated using matrices. In the earlier study, we looked as scalar-matrix operations and array operations, or element by element operations between vectors or matrices. In this section we will study what traditionally is referred to as matrix operations. In your engineering studies one of the most useful applications of matrix mathematics is the solution of a set of simultaneous equations. These types of equations arise in many if not all engineering disciplines. Let’s begin by reviewing several aspects of matrix manipulations and then focus on simultaneous equations. Transpose of a Matrix Suppose A is a mxn matrix, i.e., A has m rows and n columns. Then, the transpose of A, signified by A’ in MATLAB is a nxm matrix where the first row of A becomes the first column of A’, the second row of A becomes the second column of A’. If B is a row vector, namely a 1xn matrix, then B’ is a column vector of n elements, that is a nx1 matrix. Suppose A is given as the 2x3 matrix, 1 2 3 4 5 6 Then A’ has its first row as 1 4, its second row as 2 5, and its third row as 3 6. A’ or A transpose is a 3x2 matrix, 3 rows and 2 columns. If one is given a row vector and you need to turn it into a column vector or vice versa, you can do so by using transpose operator. Dot Product The dot product of two vectors is a scalar formed by summing the products of corresponding elements of the two vectors. Both vectors must be of the same length. Dot products are generally found in vector manipulations. MATLAB can compute the dot product in two ways, either by using element by element multiplications or by using the dot function. >> A = [2,4,6]; >> B = [-1, 3, 2]; >> dot_product = sum(A .* B) dot_product = 22 >> dot (A,B) % Built in function dot that computes the dot product 57 ans = 22 Mathematically, the dot product of two vectors is equal to the magnitude of vector #1 times the magnitude of vector #2 times the cosine of the angle between the two vectors. The magnitude of a vector is the length of the vector. Determinants Determinants are defined only for square matrices, i.e., nxn matrices. The determinant of a nxn matrix is a scalar. The MATLAB function det(D), with argument D, a nxn matrix, returns a scalar which is the determinant of D. Determinants are use to compute the inverse of a matrix that we will discuss subsequently. Matrix Multiplication Matrix multiplication is only defined for two matrices A and B when the number of columns of A equals the number of rows of B. For example, if A is a mxn matrix and B is a nxk matrix, then the operation of matrix multiplication is defined, C = A*B where C will be a mxk matrix. In general if A*B is defined, B*A may not be, and even if it is defined, A is a mxn matrix and B is a nxm matrix, A*B is not generally equal to B*A. In this example A*B is a mxm matrix while B*A is a nxn matrix. We call mxn the dimensions of the matrix. When matrix multiplication is defined between A and B, C = A*B, each element of C is computed in the following way, Let C(i,j) be the element in the i-th row and j-th column of C. Then C(i,j) = dot product of the i-th row of A and the j-th column of B. If one tries to multiply two matrices that are not compatible, i.e., the columns of A is not equal to the number of rows of B, then MATLAB will issue the error message, ??? Error using ==> * Inner matrix dimensions must agree. Note that if A and B are the same dimensions, mxm or nxn, then A.*B is defined as well as A*B but the results will be totally different. Recall A.*B is the element by element multiplication where as A*B requires one to multiple rows and columns and sum the intermediate terms. Now why is this so valuable? Suppose we have a system of equations such as 3x + 2y - z = 10 -x + 3y + 2z = 5 58 x - y - z = -1 Equations such as these result from studying linear systems. We are interested in determining the values of x, y, and z that satisfy these three equations. In order to find x, y, and z, we need to know that the three equations are independent. If one of the equations is simply a multiple of one of the others, the three equations are not independent and we can not determine x, y, and z uniquely. Rather we can only find x and y in terms of z. The three equations can be written using matrices in the following way, A*X = B, where A is a 3x3 matrix, X is a 3x1 matrix and B is a 3x1 matrix. A = 3 -1 1 2 3 -1 -1 2 -1 x X = y z 10 B = 5 -1 Note that the equation A*X = B yields the set of equations as above. MATLAB now gives us two methods to solve these equations, that is to determine the values x, y, and z that satisfy the three equations. Recall that for there to be a unique solution, the three equations must be independent. MATLAB has the built in function rank that returns the number of independent equations contained in a mxn matrix. For the matrix A above, >> rank (A) ans = 3 means there are 3 independent equations and unique values can be found for x, y, and z. For the general case, for D a mxn matrix, >> rank (D) ans = m means the m rows of D are independent. The function rank may return a value less than m which means that they are not independent, one or more equations in D can be expressed as a linear combination of the other rows of D. Now let’s look at the two ways to solve the equation A*X = B provided in MATLAB. Solution Using the Matrix Inverse 59 For the first method we will use the inverse method. From your studies of linear algebra, we know that a square nxn matrix A has an inverse if the rank (A) = n, that is if the n linear equations are independent. For our purposes we will call the inverse of A, inv(A). This is the way MATLAB represents an inverse matrix. Note that inv(A) will also be an nxn matrix. Then from linear algebra we know that inv(A)*A = I where I is call the identity matrix, I is an nxn matrix, all the diagonal elements of I are 1’s and all the off diagonal elements are 0. By diagonal elements we mean the elements I(1,1), I(2,2),….., I(N,N). Then if follows that the matrix multiplication of I and X or I*X = X. (Try it to convince yourself of this property.) Therefore consider the following equations, A*X = B inv(A)*A*X = I*X = X = inv(A)*B We have simply multiplied both sides of the equation by inv(A). Using the inverse method, we now have a solution for our set of simultaneous equations, namely, X = inv(A)*B Remember that X is the column vector of unknowns, x, y, and z. The matrix B is determined from the simultaneous equations along with A. Using the function inv we obtain the inverse of A and then we can easily determine the values for x, y, and z. For our example of three simultaneous equations, consider the following MATLAB commands, >> A = [3,2,-1;-1;3,2;1,-1,-1]; >> B = [10;5;-1]; >> rank (A) % Enter the matrix A % Enter the column vector B % Test to see if the equations are independent ans = 3 >> X = inv(A)*B % Compute X = [x,y,z]’ X= -2.0000 5.0000 -6.0000 Solution Using Matrix Left Division 60 MATLAB provides for a second method for solving a set of simultaneous equations. This method uses the process of Gaussian elimination and doesn’t require that the inverse of the coefficient matrix be computed. In general this technique is quicker for very large matrices and the results may be more accurate as well. For the set of simultaneous equations A*X = B we would simply write the following MATLAB command to compute the unknown column vector X, >> X = A\B X= -2 5 -6 The syntax for Matrix Left Division doesn’t follow from any algebraic notation so you just have to look it up or remember it when you want to use this technique. Again, you should test that the rank(A) = n before using this technique. If rank(A) < n, MATLAB will issue an error message indicating that computed values may contain infinites or NaN’s. Mesh Current Analysis Let’s develop a MATLAB script for a problem often encountered by electrical engineering students in the study of electric circuits made up of resistors and batteries. Our text provides Example 6.4, we are going to generalize the problem somewhat and use some MATLAB commands that we know for practice. Example 6.4 is a circuit made up of three meshes. Meshes are indivisible loops, that is, they can not be made any smaller. For each mesh there is a mesh current, these mesh currents become the unknowns. If there are n meshes, there will be n mesh currents. Solving problems like this end up as solving a set of simultaneous equations of the form R*I=V where R is an nxn matrix (n meshes), I is a column vector of the n unknowns, i1, i2, i3,…, iN, and V is the column vector of battery voltages. We’ll assume there is only one battery as shown in Figure 6.3 on page 197 connected in mesh 1 as shown. We will develop a script m-file that we can use to solve for I for some arbitrary number of meshes in our circuit. We will use the inverse method for his problem. Our challenge for arbitrary N is to input the resistances in the meshes and place them into the proper location R(k,l) of the R matrix. Once we have done this, the solution is quite simple. To input the resistances we will follow these simple rules; 1. For each mesh, say mesh m, the sum of the resistances around mesh m is placed into R at location R(m,m), i.e., along the diagonal at the mth diagonal location. 61 2. If there is a resistance, say R ohms, between two meshes, say mesh p and mesh q, p not equal to q, then R(p,q) = -R. Note that R(q,p) = -R as well. Those are our rules for forming the nxn matrix R. (Remember that using i and j as variable names isn’t recommended so we will use p, q and n for our indices as needed.) To use this script, one would draw the circuit on paper, label the meshes 1, 2, …, N and label the mesh currents, i1, i2, …, iN as shown in Example 6.4. Note the currents are flowing in a clockwise manner by assumption and we’ll assume that the battery is connected in mesh 1. We assume the units for the voltage of the battery is volts, the resistances are ohms and the currents will be in amps. Here goes; % This m-file calculates the mesh currents for a circuit of N meshes. The user is % prompted to input the resistances in each mesh and between the meshes. The script % returns the N mesh currents as the results. N must > 1 and < 10, i.e., 2,3, …, 9. clear,clc; N = input(‘Enter the number of meshes in the circuit, N: ‘); if (N>9) disp (‘ N is too large, N must be less than 10 meshes.’) elseif (N<2) disp (‘ N is too small, N must be greater than 2 meshes.’) else v = input (‘Enter the value of voltage of the battery in mesh 1, V: ‘); % Create the column vector V from the input voltage. V = zeros (N,1); V (1,1) = v; % First we will input the sum of the resistance around each mesh using a for loop for n = 1:N; fprintf (‘For mesh %3.0f \n’, n); R(n,n) = input(‘Enter the sum of the resistances for this mesh: ‘); end % Now enter the resistances between the meshes and enter them into R. for p = 1:N-1; % Row index for q = p+1:N; % Column index fprintf (‘For the resistor between mesh %3.0f and %3.0f \n’, p, q); res = input (‘Enter the resistance value between the meshes: ‘); R(p,q) = -1* res; R(q,p) = R(p,q); end end % At this point all the resistance values have been entered and the matrix R % is formed. % Solve for the currents, I if (rank(R) == N); % Note the relational operator == 62 I = inv(R)* V; disp (‘ ‘) disp (‘ Mesh Number disp (‘ ‘) n = 1:N; fprintf (‘ %3.0f % Compute the currents % Skip a blank line Mesh Current Value ‘) % Reset the mesh current index %10.3f \n’, [n; I’]); % Note the transpose else disp(‘ Error: Rank of R is not N; Try Again.’) end end That’s it. Now it is time to save it as a script m-file in our current directory with filename mesh_analysis. Note that we used the MATLAB function zeros to create the column vector V and placed the voltage v in the first location. Also note that we used indentation to show where our if and for statements began and ended. This is helpful to read the script and to check that each if and for statement is properly completed. Suppose we want to compute the mesh currents for a circuit of three meshes containing a battery of 9 volts in mesh 1. We’ve drawn our circuit and the determined the sum of the resistances in each mesh and the resistances between the meshes. Here we go; >> mesh_analyis Enter the number of meshes in the circuit, N: 3 Enter the value of the voltage of the battery in mesh 1, V: 9 For mesh 1 Enter the sum of the resistances for this mesh: 12 For mesh 2 Enter the sum of the resistances for this mesh: 10 For mesh 3 Enter the sum of the resistances for this mesh: 18 For the resistor between mesh 1 and 2 Enter the resistance value between the meshes: 7 For the resistor between mesh 1 and 3 Enter the resistance value between the meshes: 5 For the resistor between mesh 2 and 3 Enter the resistance value between the meshes: 3 Mesh Number 1 2 3 Mesh Current Value 2.168 1.788 0.900 >> Special Matrices 63 Before we end our discussion of matrix computations, MATLAB includes a group of functions that generate special matrices. The function zeros was used in the previous example to create a column vector V initially containing all zeros. We’ll touch on these functions briefly next. As the names imply, the zeros and ones functions create mxn matrices containing either all zeros or all ones respectfully. zeros(mxn) creates an mxn matrix of all zeroes and similarly for ones(mxn). As a shortcut, if the argument is a scalar k, then a kxk square matrix of all zeroes or ones is created. Since the size function returns the number of rows and the number of columns of a matrix A, then zeros(size(A)) would create a matrix the same size as A containing all zeroes. Another special function is the eye function. The eye function creates a matrix where ones are placed along the diagonal and zeroes everywhere else. If the argument is a scalar, then the matrix created is square with diagonal elements equal to one. That would be case for eye(3). Here a 3x3 matrix would be created with elements 1,1; 2,2; 3,3 all equal to 1 and the others equal to 0. For eye(2,3), a matrix of 2 rows and 3 columns would be created with elements 1,1 and 2,2 equal to 1 and the others equal to 0. Finally there is a special function that can generate a diagonal matrix from an existing vector or extract the diagonal from an existing matrix. It is called the diag function. See section 6.3.4 in the text for further explanation. 7. Symbolic Mathematics MATLAB provides us with the tools and capabilities to perform symbolic operations, in effect we can manipulate equations, find roots of polynomials, perform integration and differentiation of mathematical expressions without using numbers. MATLAB’s symbolic manipulations are based upon a software package from Maple, Inc. These capabilities are included in the Symbolic Math Toolbox. To use the symbolic capabilities we have to start by defining the mathematical expression symbolically. We do this by using the sym function. We assign a MATLAB variable name to a string of characters that define the mathematically function that we want to manipulate in some manner. So suppose we have the formula; S = x^2 – 2*y^2 + 3*a To represent this symbolically in MATLAB, using the sym function we would enter >> S = sym(‘x^2 – 2*y^2 + 3*a’) S= x^2 – 2*y^2 + 3*a 64 Note that the string defining our function is enclosed in single quotes when you use the sym function. This function for our example is defined for three independent variable, x, y, and a. In the MATLAB Workspace Window S will be listed as a symbolic variable, but that x, y, and a are not specifically listed since they have no specific value assigned to them by the expression for S. If you want to know what independent variables are contained in the expression for S, use the findsym function. >> findsym(S) ans = a, x, y They will be listed in alphabetical order. A second method used to describe an expression symbolically is to define each of the independent variables as symbolic variables and then manipulate them as you would do with any symbolic expression. So for example, >> a = sym(‘a’) a= a Here the symbolic character a on the left hand side of the assignment relation is assigned the character string a. When I want to define several symbolic variables at the same time, use the syms function. >> syms a x y Note that a, x, and y now appear in the Workspace Window as symbolic variables. Once these symbolic variables are created we can create symbolic expressions using them, for example, >> S_new = x^2 -2*y^2 + 3*a Before going on, we pause for a moment and see how the symbolic manipulations in MATLAB can be useful. Let’s take a simple example, find the roots of a quadratic equation. Suppose we want to factor the expression x^2 – 9. You may already know the answer to this simple case, but it illustrates the power here, consider, >> S = sym(‘x^2 – 9’) % Our expression is enclosed in single quotes. S= x^2 – 9 >> factor(S) % Function that returns the factors of the expression S. 65 ans = (x-3)*(x+3) >> diff(S) % Returns the derivative of S with respect to x. ans = 2*x Now that’s pretty cool. Although this is a very simple case, MATLAB is able to perform these and a number of other symbolic manipulations of very complicated expressions. It seems that this capability would be useful when one does their calculus homework to check the results. Let’s continue exploring the symbolic capabilities. There may be a need to substitute one variable in a symbolic expression for another. To do this, one would use the subs function. The command subs(S, old, new) will substitute the new variable string for the old variable string. From above, >> subs(S_new, ‘a’,’b’) ans = x^2 – 2*y^2 + 3*b >> subs(S_new, {‘x’,’y’], [‘q’,’r’}) ans = q^2 -2*r^2 + 3*a Note that when we substituted for ‘a’ first and then for ‘x’ and ‘y’, the first substitution does not change the original expression for S_new. Neither will the second substitution. Multiple substitutions are made by listing the arguments in curly braces. Also, the single quotes can be dropped when the arguments have been previously defined as symbolic arguments by using the sym or syms functions. The symbolic toolbox contains a plotting function called ezplot for plotting symbolic expressions of a single variable. To develop a graph of S = x^2 -9 using the ezplot function over the interval for x from -6 to +6, we’d enter >> ezplot (S, [-6,6]) >> title (‘Plot of the function x^2 – 9’) >> xlabel (‘x’), ylabel (‘S’) The graph below will appear in the Graphics Window. If no interval for x is specifically given, the range for ezplot defaults to the interval [-2*pi, 2*pi]. In this case, simply enter the command ezplot (S). Note that we forgot to enter the command grid on, so it makes our plot somewhat difficult to read. 66 Although we have so far only explored expressions that are polynomials, symbolic expressions can contain other mathematical or trigonometric functions like sin(x), tan (x), exp(x), log10(x), abs(x), and so on. Hence MATLAB can deal with general and complicated mathematical expressions symbolically. Simplifying Mathematical Expressions The Symbolic Toolbox contains a number of functions that we can use to simplify mathematical expressions, namely, collect, expand, factor, simple and simplify. We’ve already seen what the function factor does, it returns the factors from the factorization of a polynomial expression. Note that in some cases the factors may be complex. When we have a long expression, the collect function can be used to collect the terms. The expand function and the function factor are complimentary. From several factors, expand will generate the corresponding polynomial. For example, >> S = sym (‘(x-2)*(x+1)’); >> expand (S) ans = x^2 – x – 2 67 The functions simple and simplify simplifies an expression using one or more techniques. Simple actually displays all of its attempts to simplify the expression and the result for each and finally returns what it considers the simplest form. Simplify uses one of Maple’s simplification rules to perform the simplification. For example consider the following expression, >> S = sym(‘(x^2 – 3*x – 10)/(x + 2)’); >> simplify(S) ans = x–5 Here the numerator polynomial is divided by the denominator polynomial resulting in the expression x – 5. Operations on Symbolic Expressions Without explicitly saying it previously, we have been using standard arithmetic operations applied to symbolic expressions, i.e., we can add them, subtract them, multiple two symbolic expressions together, divide them, raise them to a power. Suppose we have defined two symbolic expressions, S1 and S2. Then S1*S2 is defined as well as S1/S2 (as long as S2 is not equal to 0), S1 + S2 is defined, and so on. In some cases we may want to convert back and forth between numerical representations and symbolic representations. MATLAB supports this with two functions, poly2sym and sym2poly. The numerical representation for a polynomial is given by a row vector of all the coefficients of the polynomial. To convert this numerical representation to a symbolic representation, use the poly2sym function, so for example, >> V = [1, -3, -10]; >> poly2sym (V) ans = x^2 – 3*x – 10 You can imagine that the sym2poly function does just the opposite. Solving Equations The MATLAB Symbolic Toolbox can be used to solve a single equation, a set of equations, and differential equations. We’ll only review the first two, solving a single equation or a set of equations and leave solving differential equations to some other time. The MATLAB function that we use is the solve function. The function solve with argument f, solve(f), solves the symbolic equation f for its symbolic value, or it solves the equation f = 0 assuming of course that f is a symbolic 68 expression. If there are multiple variables, MATLAB solves for x preferentially. Of course you can redirect the solve function to solve for one of the other variables. The command solve(f1,f2,…,fn) solves a system of equations represented by f1, f2, …,fn. Here’s some examples, >> eq1 = sym (‘x- 3 = 4’); >> solve(eq1) ans = 7 % Note that 7 is not a number here, it is % character. >> eq2 = sym(‘x^2-x-6’); >> solve (eq2) ans = 3 -2 % Similarly, 3 and -2 are characters. >> eq3 = sym (‘x^2 + 2*x +4 = 0’); >> solve (eq3) % Roots will be complex conjugates ans = -1+i*3^(1/2) -1-i*3^(1/2) % These are strings of characters, not % numbers. >> eq4 = sym(‘3*x + 2*y –z = 10’); >> eq5 = sym(‘-x + 3*y + 2*z = 5’); >> eq6 = sym(‘x – y –z = -1’); >> [A, B, C] = solve (eq4, eq5, eq6) A= -2 B= 5 C= -6 The values assigned to A, B and C are determined alphabetically, that is, the alphabetical order of the variables x, y, and z is precisely, x, y, and z, so x is assigned to A, y is assigned to B and z is assigned to C. If our equations had been described in terms of r=x, p=y and q=z, the following assignment would have been made; p would be assigned to A, q would be assigned to B, and r would be assigned to C. Remember that the result(s) of a symbolic manipulation and certainly for the solve function are symbolic. To use a result in a subsequent numerical computation you must 69 convert it to a number. Use the function double to do the conversion. So for the previous example, >> eq1 = sym (‘x – 3 = 4’); >> x = double(solve(eq1)) x= 7 % x is now a real number and can be used in a computation To verify this, look in the Workspace Window for the variable x. You will see that it is specified as double. Suppose we have an expression like D = D0*exp(-Q/(R*T)) and we want to solve for Q. >> X = sym (‘D = D0*exp(-Q/(R*T))’); >> solve (X, ‘Q’) % Solve for Q ans = -log(D/D0)*R*T Examples 7.2 and 7.3 revisit the ballistics problem where we found a numerical solution previously. In these two examples, the formulas describing the vertical and horizontal distances travel by a projectile are manipulated using symbolic mathematics to arrive at a formula for the range of a projectile, i.e., the distance traveled when it hits the ground after being shot from a canon with initial velocity v0 and angle theta. Then v0 and theta are substituted for using the subs function and the resulting formula is plotted using the ezplot function for values of theta between 0 and pi/2. In a later example, one could differentiate the range function as a function of theta, set the expression equal to 0, and solve the equation to determine the value of theta that maximizes the range function. Of course we’d find that theta = pi/4 maximizes the range, but these examples demonstrate how symbolic manipulations are very useful and how MATLAB can be used to perform these manipulations. 70