ME-419 Computer-Aided Mechanical Engineering Final Project Manual Chaumont Pham-Le, (Daniel) Ye Ding, (Eric) Hao Fei Zhang, Oguzhan Topaloglu California State University, Los Angeles 03.16.2010 Table of Contents Introduction ............................................................................................................................................. 9 Introduction ............................................................................................................................................. 9 Part I. Basic Techniques .................................................................................................................... 10 A. Excel .................................................................................................................................................... 11 1. General Tips .................................................................................................................................... 11 a. Entering Formulas ....................................................................................................................... 11 b. Inputting More than One Cell ..................................................................................................... 12 c. Selecting Multiple Cells Using Mouse ......................................................................................... 12 d. Navigation Shortcuts ................................................................................................................... 13 2. Using the Fill Feature ...................................................................................................................... 13 B. MATLAB............................................................................................................................................... 15 1. General Tips .................................................................................................................................... 15 a. Planning and File Organization.................................................................................................... 15 b. clear............................................................................................................................................. 15 c. % for Comments .......................................................................................................................... 16 d. disp .............................................................................................................................................. 16 e. Array Editor ................................................................................................................................. 17 2. Manipulating Arrays and Their Elements........................................................................................ 17 3. Declaring Global Variables .............................................................................................................. 21 4. Function Definition ......................................................................................................................... 22 5. for Loop ........................................................................................................................................... 23 6. if Branch .......................................................................................................................................... 24 Part II. Method Implementations ................................................................................................. 26 A. Numerical Root-Finding ...................................................................................................................... 27 1. Methods .......................................................................................................................................... 27 a. Graphing ...................................................................................................................................... 27 b. Newton-Raphson Method .......................................................................................................... 27 2. Problems ......................................................................................................................................... 27 a. Equation That Cannot Be Solved Analytically ............................................................................. 27 b. Solving the van der Waals Equation ........................................................................................... 28 3. Implementations ............................................................................................................................. 29 a. Creating Charts in Excel............................................................................................................... 29 b. Using Spreadsheet in Excel ......................................................................................................... 31 4. Results and Conclusion ................................................................................................................... 32 a. Numerically Calculated Roots of an Equation Cannot Be Solved Analytically ............................ 32 b. van der Waals Equation Solutions .............................................................................................. 32 c. Comparisons and Discussion ....................................................................................................... 33 B. Solving Systems of Linear Equations ................................................................................................... 34 1. Methods .......................................................................................................................................... 34 a. Overview ..................................................................................................................................... 34 b. Inverse Matrices and the Linear Algebra of Solving Systems of Linear Equations ..................... 35 c. Examples of the Matrix Inverse Method and the Elimination Method ...................................... 35 2. Problems ......................................................................................................................................... 37 2 a. Mass-Spring System .................................................................................................................... 37 b. Indeterminate Structure ............................................................................................................. 38 3. Implementations ............................................................................................................................. 39 a. Using Solver in Excel.................................................................................................................... 39 b. Using minverse and mmult in Excel ............................................................................................ 40 c. Matrix Operations in MATLAB..................................................................................................... 41 d. 2-Dimensional Plotting in MATLAB ............................................................................................. 42 4. Results and Conclusion ................................................................................................................... 46 a. Mass-Spring System Solutions .................................................................................................... 46 i. Solution Approach .................................................................................................................... 46 ii. Using Solver to Find the Displacements .................................................................................. 47 iii. Using Inverse Matrix and Matrix Multiplication to Solve the Problem.................................. 47 iv. Using MATLAB ........................................................................................................................ 48 b. Indeterminate Structure Solutions ............................................................................................. 49 i. Solution Approach .................................................................................................................... 49 ii. Using MATLAB ......................................................................................................................... 49 c. Comparisons and Discussion ....................................................................................................... 51 C. Optimization ....................................................................................................................................... 53 1. Problems ......................................................................................................................................... 54 a. Finding Extrema .......................................................................................................................... 54 b. Bicycle Truss ................................................................................................................................ 54 2. Implementations ............................................................................................................................. 55 a. Creating Surface Charts in Excel.................................................................................................. 55 b. Using Solver to Find Extrema ...................................................................................................... 57 c. Calculating Numerical Gradients in MATLAB .............................................................................. 58 d. Searching for Extrema Using fminsearch in MATLAB ................................................................. 59 e. 3-Dimensional Visualization in MATLAB ..................................................................................... 60 3. Results and Conclusion ................................................................................................................... 63 a. Finding Extrema Solutions........................................................................................................... 63 b. Bicycle Truss Solutions ................................................................................................................ 64 c. Comparisons and Discussion ....................................................................................................... 67 i. Optimization............................................................................................................................. 67 ii. Sensitivity Analysis in Excel and MATLAB................................................................................ 69 iii. Future Considerations ............................................................................................................ 71 D. Numerical Integration......................................................................................................................... 72 1. Methods .......................................................................................................................................... 72 a. Trapezoid Rule............................................................................................................................. 72 b. Simpson's 1/3 Rule ...................................................................................................................... 72 c. Simpson's 3/8 Rule ...................................................................................................................... 73 2. Problem ........................................................................................................................................... 73 a. Work ............................................................................................................................................ 73 3. Implementations ............................................................................................................................. 73 a. Using Spreadsheet in Excel ......................................................................................................... 73 b. Interpolation Using interp1 and ppval in MATLAB ..................................................................... 75 c. Numerical Integration in MATLAB............................................................................................... 76 4. Results and Conclusion ................................................................................................................... 77 a. Solutions ...................................................................................................................................... 77 3 b. Comparisons and Discussion....................................................................................................... 79 E. Solving Ordinary Differential Equations Numerically.......................................................................... 81 1. Methods .......................................................................................................................................... 81 a. Euler's, Heun's, and Runge-Kutta ................................................................................................ 81 2. Problem ........................................................................................................................................... 82 a. Pendulum Motion ....................................................................................................................... 82 3. Implementations ............................................................................................................................. 84 a. Built-In ODE Solvers in MATLAB .................................................................................................. 84 4. Results and Conclusions .................................................................................................................. 86 a. Solutions ...................................................................................................................................... 86 b. Comparisons and Discussion....................................................................................................... 87 i. Numerical Solutions to Differential Equations ......................................................................... 87 ii. Future Considerations ............................................................................................................. 90 References ............................................................................................................................................. 91 Index ......................................................................................................................................................... 95 4 List of Figures Figure 1. Entering Formulas in Excel. .......................................................................................................... 11 Figure 2. Formula Updates With the Newest Values. ................................................................................. 11 Figure 3. Using Single Quotation Marks When Inputting Cells. .................................................................. 12 Figure 4. Selecting Multiple Cells Using Mouse. ......................................................................................... 13 Figure 5. Fill Updates the Cell References. ................................................................................................. 14 Figure 6. Using the Dollar Sign to Fix a Reference Cell's Index. .................................................................. 14 Figure 7. Local Directory of MATLAB Files. ................................................................................................. 15 Figure 8. M-File Using disp Commands. ...................................................................................................... 16 Figure 9. Output of disp Commands. .......................................................................................................... 17 Figure 10. Using the Array Editor to Display and Select Data. .................................................................... 17 Figure 11. Specifying Matrices. ................................................................................................................... 18 Figure 12. Specifying Matrices (Alternative). .............................................................................................. 18 Figure 13. Matrix Concatenation. ............................................................................................................... 19 Figure 14. Returning Matrix Elements. ....................................................................................................... 19 Figure 15. Specifying Matrix Elements........................................................................................................ 20 Figure 16. Element-by-Element Multiplication versus Matrix Multiplication (M-File). .............................. 20 Figure 17. Element-by-Element Multiplication versus Matrix Multiplication (Command Window). ......... 20 Figure 18. M-File Using max Functions. ...................................................................................................... 21 Figure 19. Outputs of max Functions. ......................................................................................................... 21 Figure 20. Global Variables Declared. ........................................................................................................ 22 Figure 21. Global Variables Used in an M-File Other Than Where They Were Declared. .......................... 22 Figure 22. Function Definition with Multiple Outputs. ............................................................................... 23 Figure 23. Function Definition with No Output. ......................................................................................... 23 Figure 24. Loop Statements Using for......................................................................................................... 24 Figure 25. if Control Branches (M-File). ...................................................................................................... 25 Figure 26. if Control Branches (Figure). ..................................................................................................... 25 Figure 27. Creating a Scatter Plot in Excel. ................................................................................................. 30 Figure 28. Excel Charts Used to Compare Two Numerical Methods. ......................................................... 31 Figure 29. Mass–Spring System. ................................................................................................................. 37 Figure 30. Rigid Bar and Applied Forces. .................................................................................................... 38 Figure 31. Data for Solver. .......................................................................................................................... 39 Figure 32. The Solver Window. ................................................................................................................... 40 Figure 33. Elimination: one way of solving the mass-spring system problem............................................ 41 Figure 34. Matrix Inverse: another way of solving the mass-spring system problem. ............................... 42 Figure 35. The plot Command. .................................................................................................................... 43 Figure 36. The subplot Command. .............................................................................................................. 44 Figure 37. Navigating between Subplots. ................................................................................................... 45 Figure 38. Subplots Overlap. ....................................................................................................................... 46 Figure 39. Solver Results for the Mass-Spring System Problem. ................................................................ 47 Figure 40. Matrix Operations in Excel for Solving the Mass-Spring System Problem................................. 48 Figure 41. MATLAB Results for the Mass-Spring System Problem. ............................................................ 48 Figure 42. MATLAB Solutions for the Indeterminate Structure Problem. .................................................. 51 Figure 43. Global and Local Extrema. ......................................................................................................... 53 Figure 44. Bicycle Truss Problem. ............................................................................................................... 54 Figure 45. Excel Surface Chart for the First Problem. ................................................................................. 55 5 Figure 46. Changing the 3-D View Parameters of a Surface Chart. ............................................................ 56 Figure 47. Surface Chart Turned into a Contour Plot.................................................................................. 56 Figure 48. Formatting the Legend of a Surface Chart. ................................................................................ 57 Figure 49. Increased the Density of Isolines after Decreasing the Major Unit Value. ................................ 57 Figure 50. Formula for Finding Extrema Using Solver................................................................................. 58 Figure 51. Solver Paremeters Window. ...................................................................................................... 58 Figure 52. Gradient Generation for Finding the Extrema of an Function. .................................................. 59 Figure 53.fminsearch with Options for the Bicycle Truss Problem (M-File). .............................................. 60 Figure 54. fminsearch Outputs for the Bicycle Truss Problem (Command Window). ................................ 60 Figure 55. Graphing the First Problem (M-File). ........................................................................................ 62 Figure 56. Curtain Plot of the First Problem. .............................................................................................. 62 Figure 57. Contour Plot of the First Problem. ............................................................................................. 63 Figure 58. Solver Results for the Maxima. .................................................................................................. 63 Figure 59. Matlab Solution for Finding the Extremum. .............................................................................. 64 Figure 60. Contour plot of the First Problem. ............................................................................................. 64 Figure 61.Free Body Diagram of the bicycle bracket. ................................................................................. 65 Figure 62. Excel Solution for the Bicycle Truss Problem at 30 Degree Angle. ............................................ 65 Figure 63. Excel Chart for the Bicycle Truss Problem Solutions from 0 to 90 Degree Angle. ..................... 66 Figure 64. Matlab output. ........................................................................................................................... 66 Figure 65. Displacement and Potential Energy change with respect to angle. .......................................... 67 Figure 66. Solver Searching for Maximum, Minimum, or Function Value.................................................. 68 Figure 67. Solver Options. ........................................................................................................................... 68 Figure 68. Solver Iteration Dialog Box......................................................................................................... 68 Figure 69. Excel Status Bar for Solver Iteration 1. ...................................................................................... 69 Figure 70. Excel Status Bar for Solver Iterations. ........................................................................................ 69 Figure 71. Solver Sensitivity Report. ........................................................................................................... 69 Figure 72. Varying the Width of the Bicycle Truss. ..................................................................................... 70 Figure 73. Varying the Height of the Bicycle Bracket.................................................................................. 71 Figure 74. Trapezoid Rule. .......................................................................................................................... 72 Figure 75. Work Problem. ........................................................................................................................... 73 Figure 76. Excel data for the Work Problem. .............................................................................................. 74 Figure 77. Required Results Table for the Work Problem. ......................................................................... 74 Figure 78. Trapezoid Rule Formula in Excel for the Work Problem. ........................................................... 74 Figure 79. Simpson 1/3 Rule in Excel for the Work Problem. ..................................................................... 75 Figure 80. Simpson 3/8 Rule in Excel for the Work Problem. ..................................................................... 75 Figure 81. Computing % Error in Excel for the Work Problem. .................................................................. 75 Figure 82. Interpolating Using interp1 and ppval for the Work Problem (M-File). .................................... 76 Figure 83. MATLAB Implementations of the Trapezoid Rule, Simpson's 1/3 Rule, and Simpson's 3/8 Rule. .................................................................................................................................................................... 77 Figure 84. Excel Results and Some MATLAB Results for the Work Problem. ............................................. 78 Figure 85. MATLAB Results for the Work Problem. .................................................................................... 79 Figure 86. Euler's Method. .......................................................................................................................... 81 Figure 87. Heun's Method. ......................................................................................................................... 82 Figure 88. Fourth Order Runge-Kutta Method. .......................................................................................... 82 Figure 89. Pendulum Motion Problem. ...................................................................................................... 83 Figure 90. Non-Stiff (Left) and Stiff (Right) Problems. ................................................................................ 85 Figure 91. Using MATLAB ODE Solvers for the Pendulum Motion Problem (M-File). ................................ 85 6 Figure 92. Using MATLAB ODE Solvers for the Pendulum Motion Problem (Figure). ................................ 86 Figure 93. MATLAB ODE Solver Solutions for the Pendulum Motion Problem. ......................................... 87 Figure 94. Euler1 and Heun2 Compared to ode45 and ode23tb at Roughly 550 Steps. ............................. 88 Figure 95. Euler1 Converges As Step-Size Decreases.................................................................................. 89 Figure 96. Euler2 Shows Slight Improvement; Heun1 Shows Little Loss. ................................................... 90 7 List of Tables Table 1. Given Data for the van der Waals Equation Problem. .................................................................. 28 Table 2. Sample Layout of a Spreadsheeting Implementation of the Newton-Raphson Method. ............ 32 Table 3. Sample Layout of EXCEL for the Newton-Raphson ....................................................................... 32 Table 4. Newton-Raphson Results for the First Problem............................................................................ 32 Table 5. Results from the Newton-Raphson Method and the Ideal Gas Law. ............................................ 33 Table 6. Excel Input for the Mass-Spring System Problem. ........................................................................ 40 Table 7. Expermimental Data for the Work Problem. ................................................................................ 73 Table 8. Some of the MATLAB ODE Solvers. ............................................................................................... 84 8 Introduction This manual introduces some of the basic features in Excel and in MATLAB. The "Basic Techniques" section teaches ways of accomplishing certain tasks, such as entering formulas and declaring variables. The "Method Implementations" section uses a number of engineering problems as examples of selecting and applying different methods and techniques. The References section allows the reader to verify sources and delve deeper into the topics presented. An index has been compiled for information to be found quickly. 9 Part I. Basic Techniques 10 A. Excel 1. General Tips a. Entering Formulas Entering a formula into a cell helps the user compute some of the more complicated mathematics, especially if one of the built-in functions in Excel is used. If other cells are referenced in the formula, then the host cell's value would be able to change at the same time the referenced cells change in value, allowing the spreadsheet to adapt to different problems. To enter a formula, type the equal sign = first, followed by the expression. To reference a cell, either type out that cell's position by row and column, respectively, or select that cell using the mouse or the arrow keys, as shown in Figure 1. Now, whenever the referenced cell changes, the host cell would be updated using the newest values, as seen in Figure 2. Figure 1. Entering Formulas in Excel. Figure 2. Formula Updates With the Newest Values. Sometimes, an equal sign is is intended to be the start of a string without any formulas that would follow. In that case, type a single quotation mark ' before inputting the intended content. A quotation mark as the first character of a cell is almost never treated by Excel as a part of that cell's value; thus, in order to include a quotation mark in the beginning of a cell's value, input two consecutive ones so that Excel could pick up the second one as a quotation mark. In Figure 3, the highlighted cell displays the cell's actual value, while the function bar above, to the right of the cell position and the equal sign, displays exactly what was input. 11 Figure 3. Using Single Quotation Marks When Inputting Cells. b. Inputting More than One Cell When more than one cell is selected, press the Ctrl key and the Return key at the same time to enter the same input into all of the cells. c. Selecting Multiple Cells Using Mouse Similar to selecting files in WIndows, hold down the Shift key to select a group of consecutive cells by first clicking on the initial cell and then clicking on the ending cell. Hold down the Ctrl key to select multiple cells one by one. To select non-contiguous groups of consecutive cells, first select a range as usual, then release the Shift key. Hold down the Ctrl key while clicking on the initial cell of the next group but release it when that cell has been selected. Now, hold down the Shift key while clicking on the ending cell. Follow the same procedures when selecting each additional group. Depending on the situation, it might be easier to select cells within a group by dragging the cursor while holding down the mouse button, in which case one would not need to release even the Ctrl key. As seen in Figure 4, a large number of cells at different locations can be selected in a short amount of time. 12 Figure 4. Selecting Multiple Cells Using Mouse. d. Navigation Shortcuts Use the Return key to complete inputting a cell and move the focus down one cell. Use the Tab key to complete inputting a cell and move the focus to the cell immediately to the right. Use the Ctrl key together with an arrow key to move immediately to the left or right end of the current row, or the top or bottom cell of the current column, in the entire worksheet. Use the Ctrl key together with either the Home key or the End key to move immediately to the left-upper-most or the right-bottom-most cell, respectively, in the entire worksheet, that has a non-blank cell in the same row or column. This techniques may be used while holding down the Shift key, in which case a range of cells from the inital cell to the ending cell would become selected. Use the Ctrl key together with either the Page Up key or the Page Down key to move to the previous or the next worksheet, respective. One cannot cycle from the very last worksheet to the very first worksheet by using this technique, however, without going through all the worksheets in between. 2. Using the Fill Feature The Fill feature can be used to enter a horizontal or vertical groups of cells with values that follow a linear or exponential trend. With a linear trend, each cell differs from its neighbor by a fixed amount or is the same as all other cells—a zero trend. With an exponential trend, each cell 13 is a fixed multiple of its neighbors. The linear or exponential step size, as well as the terminal value, can be specified by the user. To perform FIll, first select the starting cell. Then, either drag the square dot at the bottom right corner of the highlight box over the cells to be filled, or select a group of cells and click on one of the Fill options under the Edit or a similar menu, depending on the version of Excel. The Fill feature can also be used to repeat the same formula from one cell to the next, yet changing the cell references, if used as parameters, from cell to cell according to each cell's position. As seen in Figure 5, the formula in cell B4 is repeated from C4 to K4, yet each cell gives a different result because the formula updates the cell references as the host cell changes. On the other hand, in the sixth row, all cells give the same result because the cell reference, in this case $B4, is fixed to column B, hence the dollar sign in front of B, as seen in Figure 6. One may also fix the row by inserting a dollar sign in front of the row number or fix both the column and the row by using a dollar sign in front of each index. Figure 5. Fill Updates the Cell References. Figure 6. Using the Dollar Sign to Fix a Reference Cell's Index. 14 B. MATLAB MATLAB, which stands for MATrix LABratory, is an interactive programming environment designed to facilitate computations and visualizations involving data arrays such as matrices. Coding in MATLAB often takes only a fraction of the time it would take to write something similar in a scalar, non-interactive language such as C or Fortran. 1. General Tips a. Planning and File Organization MATLAB codes are stores as M-Files. Before starting to program, think about what needs to be done and plan out major sections of codes. For example, information regarding the dimensions of a structure, material property coefficients, fixed forces, etc., can be assigned to variables and kept in their own M-File. There will also be functions for solving specific problems. In order to be called by MATLAB, each function must form its own M-File. Doing so also prevents the confusion that might result from mixing functions with other variables and subroutines and allows function files to be imported or exported individually. The main M-File is usually a script, in which a series of commands complete the necessary tasks, often calling on functions and other data to solve detailed steps. Figure 7. Local Directory of MATLAB Files. Notice that each function is contained in its own M-File. The initialize.m file contains all the constants. The run_me__for_solutions.m file is a script that contains commands for carrying out all the steps involved in b. clear The clear command frees up memory by removing all variables. Use clear all to delete or remove all variables, functions, and MEX-files from memory. To remove a specific item, type its name after the command (i.e., to clear a variable named x, type clear x). Refer to the Help section in MATLAB or on the MathWorks Web site for detailed explanations on all commands. 15 c. % for Comments The % symbol marks an entire line as comments, thus ignored by MATLAB when actually running a script. Along with other uses, comments allow a user to keep notes for future reference, especially on subtle details of exactly what each section of codes do. It also helps a user understand codes written by someone else, especially when debugging or customizing a program. d. disp The disp command takes an argument, which can be a string, an array, or a variable of the said types, and displays it in MATLAB's Command Window. The syntax for each of the three types of arguments is as follows. disp('literalStringToBeDisplayed') disp(arrayName) disp(variableName) The output would not include the name of the variable argument, unlike the case of directly calling the variable, which would result in the variable name being included in the output, thus printed along with its value. After displaying whatever content associated with the argument, the disp procedure would move the Command Window caret down to a new line, which becomes the starting point for any subsequent outputs. If a line change is not desired, then the fprintf command could be used instead of disp. [Xmax,Xind] = max(X); AngleforXmax = Xind - 1 disp('degree'); disp(' '); [Ymax,Yind] = max(Y); AngleforYmax = Yind - 1 disp('degree'); Figure 8. M-File Using disp Commands. Semi-colons and the disp commands are used to control how the output looks. Notice the use of an empty space, enclosed in quotation marks like any other string would be, to create an otherwise empty line; MATLAB would not output anything if the argument of the disp command is or evaluates to an empty string '' or an empty array []. >> script AngleforXmax = 0 degree AngleforYmax = 16 90 degree >> Figure 9. Output of disp Commands. e. Array Editor Sometimes, a variable's output is too large to be entirely displayed inside the Command WIndow, which buffers up to 25000 lines depending on the version of MATLAB. In that case, its content can still be selected, thus copied to the Windows Clipboard, using the Array Editor. Figure 10 shows the location of the Array Editor icon at where the cursor points. The variable Euler0007 contains 51429 lines, but it can still be fully displayed and selected inside the Array Editor. Figure 10. Using the Array Editor to Display and Select Data. 2. Manipulating Arrays and Their Elements In MATLAB, variables are bound to their values using the equal sign =. For array values, square brackets are used to enclose the elements. For a 2-dimensional matrix, as shown in Figure 11, first specify the first row, using commas to separate the elements—they belong to different columns. Type a semi-colon once the first row has been entered. Now, input the succeeding rows, again using commas to break the columns and semi-colons to break the rows . 17 >> A = [-30,20,0;20,-30,10;0,10,-10] A = -30 20 0 20 -30 10 0 10 -10 >> >> b = [-2*9.81;-3*9.81;-2.5*9.81] b = -19.6200 -29.4300 -24.5250 >> Figure 11. Specifying Matrices. Alternatively, a space can be used in place of a comma, and a new line can be used in place of a semi-colon as Figure 12 shows. Close the square brackets when done, and press the return key. By default, MATLAB displays the variable with its value just assigned. To suppress this or any output in general, use a semi-colon before returning a command . >> A = [-30 20 0 20 -30 10 0 10 -10]; >> >> b = [-2*9.81 -3*9.81 -2.5*9.81]; >> Figure 12. Specifying Matrices (Alternative). As shown i Figure 13, use the comma or the space to concatenate arrays horizontally, by writing the substrate arrays as if entering elements of a 2-dimensional array and enclosing them inside a pair of square brackets. To concatenate vertically, use the semi-colon or the new line. >> A = [-30,20,0;20,-30,10;0,10,-10] A = -30 20 0 20 -30 10 0 10 -10 >> >> AVert = [A;A;A] AVert = -30 20 0 20 -30 10 0 10 -10 -30 20 0 20 -30 10 0 10 -10 -30 20 0 20 -30 10 0 10 -10 >> >> AHorz = [A,A] AHorz = -30 20 0 -30 20 0 20 -30 10 20 -30 10 18 0 10 -10 0 10 -10 >> >> AMixed = [A,A;A,A;A,A] AMixed = -30 20 0 -30 20 0 20 -30 10 20 -30 10 0 10 -10 0 10 -10 -30 20 0 -30 20 0 20 -30 10 20 -30 10 0 10 -10 0 10 -10 -30 20 0 -30 20 0 20 -30 10 20 -30 10 0 10 -10 0 10 -10 >> % This function creates the constraint matrix for the linear system coeMatrix * forceMatrix = constrMatrix. It takes a scalar P and a 1-dimensional array d, and outputs a 3 by length(d) matrix. function [constrMatrix] = constrMatrixFn(P,d) PRow = P*ones(1,length(d)); % Makes a row of Ps dPRow = P*d; % Makes a row of P*d zeroRow = zeros(1,length(d)); % Makes a row of zeroes constrMatrix = [PRow;dPRow;zeroRow]; % concatenates the output Figure 13. Matrix Concatenation. To return an element or elements of an array, type its name followed by a pair of parentheses in which the row index and the column index, separated by a comma, of the element are specified. To return an entire row, specify the row index but use a colon as the column index. To return an entire column, specify the column index but use a colon as the row index. To return the intersection of multiple rows with multiple columns, use an array of the desired indices, enclosed in square brackets, in place of the row and/or column index, as shown in Figure 14. >> AMixed(9,2) ans = 10 >> >> AMixed([2,5],:) ans = 20 -30 10 20 20 -30 10 20 >> -30 -30 1 1 Figure 14. Returning Matrix Elements. Similarly, an element or elements of an array can be specified or re-assigned a new value. Enter the command as if returning an element or elements, followed by an equal sign, then the new value(s). When specify multiple elements, be sure to enclose the desired values inside an array of appropriate dimensions, as shwon in Figure 15. 19 >> AMixed(9,2) = 92; >> >> AMixed([8,9],[5,6]) = [9,9;9,9]; >> >> AMixed AMixed = -30 20 0 -30 20 1 20 -30 10 20 -30 1 0 10 -10 0 10 1 -30 20 0 -30 20 1 20 -30 10 20 -30 1 0 10 -10 0 10 1 -30 20 0 -30 20 1 -30 20 0 -30 9 9 0 92 -10 0 9 9 >> Figure 15. Specifying Matrix Elements. Sometimes it is necessary to operate on two or more arrays element by element. That is, say C = R{A,B}, where R is some operation on the elements of arrays A and B. Its output makes up the array C such that for each element of C, cij = R{aij,bij}, in which aij and bij are elements of A and B having the same indices as the corresponding output cij. To differentiate such procedures from certain matrix operations, MATLAB defines element-by-element multiplication .*, division ./, and exponentiation .^ in addition to matrix multiplication *, Gaussian elimination \, and matrix exponentiation ^. An example of .* is shown in Figure 16. A = eye(2) B = ones(2) elemC = A .* B matrC = A * B Figure 16. Element-by-Element Multiplication versus Matrix Multiplication (M-File). The same two matrices are first multiplied element by element, then multiplied as matrices. The resulting output to the MATLAB Command Window is shown in Figure 17. >> script A = 1 0 0 1 B = 1 1 1 1 elemC = 1 0 0 1 matrC = 1 1 1 1 >> Figure 17. Element-by-Element Multiplication versus Matrix Multiplication (Command Window). 20 To search for the largest or the smallest elements of an array, the max or the min commands, respectively, can be used. MATLAB can also return the indices of the elements found. The syntax is as follows. resultArray = max(inputArray) [resultArray, indexArray] = max(inputArray) resultArray = min(inputArray) [resultArray, indexArray] = min(inputArray) If the input array has more than one dimension, then a row vector is returned containing the maximum or minimum of each column of the input array. In the case of indices, that of the first maximum or minimum found is returned, even though there might be more than one element having the same maximum or minimum value. Figure 18 and 19 show how max was used to locate the angles associated with the greatest x- and y-displacements among a large data set of results. [Xmax,Xind] = max(X); AngleforXmax = Xind - 1 disp('degree'); disp(' '); [Ymax,Yind] = max(Y); AngleforYmax = Yind - 1 disp('degree'); Figure 18. M-File Using max Functions. Both an array of maximums and that of their indices were generated for arrays X and Y, which contain the data for x- and y-displacements, respectively. Only the indices were modified and displayed; they correspond to the angle in degrees that yield the maximums in x- and ydisplacements. The actual output is shown in Figure 19. >> script AngleforXmax = 0 degree AngleforYmax = 90 degree >> Figure 19. Outputs of max Functions. 3. Declaring Global Variables It is sometimes desirable to have M-files share the same variable, such as when developing and testing new codes using a large number of different data sets before integrating it into a more complex program that would require the stringency of passing every variable. The keyword 21 global is used to declare a global variable such that any assignment to that variable, in any function, is available to any other function also declaring it global. The syntax is as follows. global variableName global E E = 2E11; global A A = 1E-4; global w w = 0.24:0.02:0.64; global h h = 0.3:0.02:0.7; global F F = 10E3; Figure 20. Global Variables Declared. To use a global variable in where it was not originally declared, it must be called first as seen in Figure 21. function [U] = energyFn(Deform,theta,wInd,hInd) % A function that calculates potential energy. % Deform = [xdisplacement,ydisplacement] % theta = angle, in radians % wInd = the index for w; locates a value for the width of the truss % hInd = the index for h; locates a value for the height of the truss % U = E*A/L* (w/2l)^2 * x^2 + E*A/l* (h/l)^2 * y^2 + -1*F*cos(theta)*x + % -1*F*sin(theta)*y global E; global A; global w; global h; global F; x = Deform(1); y = Deform(2); wVal = w(wInd); hVal = h(hInd); % Call the lFn function to calculate the correct l. lVal = lFn(wVal,hVal); coe1 = E * A / lVal * (wVal / 2 / lVal)^2; coe2 = E * A / lVal * (hVal / lVal)^2; coe3 = -1 * F * cos(theta); coe4 = -1 * F * sin(theta); U = coe1 * x^2 + coe2 * y^2 + coe3 * x + coe4 * y; Figure 21. Global Variables Used in an M-File Other Than Where They Were Declared. 4. Function Definition In MATLAB, functions are defined using the syntax function [output1,output2,outputLast] = functionName(arg1,arg2,argLast) calculationStep1 calculationStep2 22 calculationStepLast output1 = expressionReturned1 output2 = expressionReturned2 outputLast = expressionReturnedLast Note that there may be no argument required, in which case the function would be defined and called with nothing inside the parentheses. There might also not be any steps involved. It is technically possible to define a function without any outputs and/or without returning any outputs, as seen in Figure 23, in which the function xpermt does require input and does not return anything, but actually performs the interim steps when called. On the other hand, multiple outputs can be assigned to an array of variables, as seen in Figure 22 with the function Funky. function [mean,stdev] = Funky(x) n = length(x); mean = sum(x)/n; stdev = sqrt(sum((x-mean).^2/n)); >> [mean,stdv] = Funky([1:9]) mean = 5 stdv = 2.5820 >> >> a = [3,3] + Funky([1:9]) a = 8 8 >> Figure 22. Function Definition with Multiple Outputs. function []=xpermt() global result result = 1*2*3; >> xpermt >> >> global result >> >> result result = 6 >> Figure 23. Function Definition with No Output. 5. for Loop Given a range of values, a for statement assigns the first value to an index variable, performs a series of steps that come before the keyword end in the statement declaration, before assigning 23 the next value to the index variable and going through the series of steps again, until no values are left to be assigned. The keyword end is required; it limits the scope, that is, the steps that are repeated during each round or pass of the for loop. To insert a point where the entire loop could be stopped and exited, use break or sometimes return; control would be passed to the statement following the keyword end. Use continue to stop and exit from the current pass of a loop subroutine without exiting the entire loop. for n = 1:17 forces(:,n) = forcesFn(n - 1); end Figure 24. Loop Statements Using for. 6. if Branch An if control branch is a set of statements that are executed only when a specified condition is met. The syntax is as follows. if expressionOfACondition statementToBeExecuted … end A condition must evaluate to a Boolean, that is, either True or False. Arithmetic comparison, such as == (equal to), >, != (not equal to), <=, are often used, but there are other means of generating a Boolean. The if keyword can be used with the elseif and else keywords, in which case elseif specifies additional conditions to be checked and the statements to be executed if a condition were true, and else specifies what the control branch executes when no conditions are met. The general syntax would be as follows. if expressionOfCondition statementToBeExecuted statementToBeExecuted … elseif expressionOfACondition statementToBeExecuted … elseif expressionOfACondition statementToBeExecuted … else statementToBeExecuted … end 24 subplot(3,1,1); % So that subsequent graphs do not displace previous ones. hold on; % Graph the x displacement versus angle. plot(R,Xw(k,:)); if k == 1 % Label the graph for the smallest width. gtext('width 0.24 m; length 0.5142 m') end if k == 21 % Label the graph for the largest width. gtext('width 0.64 m; length 0.5936 m') end Figure 25. if Control Branches (M-File). Figure 26. if Control Branches (Figure). 25 Part II. Method Implementations 26 A. Numerical Root-Finding Some cubic and higher order polynomial equations can be solved analytically, but the calculations are long and tedious. As for non-polynomial equations, such as those involving trignometric and transcendential functions, there can be no analytical solution at all. They can only be solved by numerical methods. 1. Methods a. Graphing Plotting out the formula in as much detail as possible, one may inspect the graph for where f(x) = 0. It could thus serve as a way of making an initial guess for more precise numerical methods. By using a computer, a function can be easily graphed; however, it would take a long time to plot it by hand. Some functions may approach 0 but never intercept it, thus one must keep that possibility in mind when inspecting graphs. b. Newton-Raphson Method This method is based on linear approximation--starting with an original guess then approximating the function by its tangent line. The x-intercept (y=0) of this tangent line should be closer to the function's true root than the guess. Usually, the error between the xintercept and true root can be reduced with additional iterations. Therefore, for this method to work, the original guess must be sufficiently close to the true root. Otherwise, the algorithm might diverge, never converging on a singular value. 1. Guess xi 2. xi+1 = xi f xi f' xi x x 3. Error = i+1 i 100% xi+1 2. Problems a. Equation That Cannot Be Solved Analytically Given: f ( x) e x x 0 27 Find: x-values that satisfy the equation b. Solving the van der Waals Equation Given: T = 300K, 500K, 700K P = 1atm, 10 atm, 100 atm Gas a b 02 1.360 0.03183 3.592 0.04267 C02 Table 1. Given Data for the van der Waals Equation Problem. Ideal Gas Law : pV = nRT , V = n pn = nRT =R T P van Der Waals Equation : a p + 2 b = RT Re - arranging the van Der Waals Equation : a f = p + 2 b RT = 0 First Derivative : f' = p a 2 + 2ab 3 Find: the molar volume ν 28 3. Implementations a. Creating Charts in Excel Excel allows the user to create charts very easily from data. When different numerical methods are used, their solutions can be compared in case one method has failed without being noticed. As Figure 27 shows, a scatter plot of the equation that cannot be solved analytically was created by first highlighting a table of data, then inserting a chart using a wizard program built into Excel. Selecting a chart at any time would highlight the corresponding data. Different sets of data may be selected together and graphed on the same chart, or added to an existing chart. Figure 28 shows both the plot of the equation and the Newton-Raphson results from successive iterations—four iterations can be seen, with the last two merging into each other near the x-intercept of the plot. It appears that the algorithm has successfully converged on the root. 29 Figure 27. Creating a Scatter Plot in Excel. 30 1.2 1 0.8 0.6 f(x) 0.4 0.2 0 0 0.2 0.4 0.6 0.8 1 1.2 -0.2 -0.4 -0.6 -0.8 x Plot Newton Raphson Figure 28. Excel Charts Used to Compare Two Numerical Methods. b. Using Spreadsheet in Excel The first step in using the Newton-Raphson method with excel is labeling the columns, as shown in Table 2. The next step is to input the formula under the corresponding column. One of the most basic techniques when spreadsheeting in Excel is entering formulas following the proper formats. For f(xi), the formula used is the same as the transcendental function, so the input formula would be =EXP(-[cell of xi]) - [cell of xi]. For example, if the initial value will be at the cell B2, the input formula for f(xi) would be =EXP(-[B2]) - [B2]. Since f’(xi) is the derivative of f(xi), then the input formula would the derivative of the transcendental function, or =-EXP(-[cell of xi]) - 1. The method for obtaining x(i+1) is expressed by the Newton-Raphson equation, so the input formula would be =[cell of xi] ([cell of f(xi)] / [cell of f’(xi)] ). And to get the percentage error of xi and x(i+1), the input formula would be =(ABS( [cell of x(i+1)] - [cell of xi] ) / [cell of x(i+1)] )*100. The next step is to assign the second xi to the value of x(i+1) from the first xi. Then the rest of the cells; f(xi), f’(xi), x(i+1), and error % can be copy from the first row onto the second row. Lastly, the rest of the table can be copied from the second row. The number of rows is completely base on the user’s preference. When completed, the table should be the same as Table 2. 1 2 3 A Xi A2 =D2 B f(xi) =EXP(-A2)-A2 =EXP(-A3)-A3 C f'(xi) =-EXP(-A2)-1 =-EXP(-A3)-1 D x(i+1) =A2-(B2/C2) =A3-(B3/C3) E Error (%) =(ABS(D2-A2)/D2)*100 =(ABS(D3-A3)/D3)*100 31 4 =D3 =EXP(-A4)-A4 =-EXP(-A4)-1 =A4-(B4/C4) =(ABS(D4-A4)/D4)*100 Table 2. Sample Layout of a Spreadsheeting Implementation of the Newton-Raphson Method. The procedure of applying the Newton-Raphson method is the same as that of the transcendental function. But the X’s on the column labels should be changed to V’s is to avoid any confusion on which unknown is targeted. Since the Van der Waals equation will be used, the input formula should be the same as the Van der Waals equation. The input formula for f(v) would be =( [pressure] + { [value of a] / [cell of v^2 } )*( [cell of v] – [value of b] ) - ( [gas constant] * [temperature] ). As for the f’(v), since it is the derivative of f(v), the input formula would be =[pressure] - ( [value of a] / [cell of v]^2 ) + (2 * [value of a] * [value of b] / [cell of v]^3 ). The v(i+1) would remain the same because it uses the NewtonRaphson expression, so the input formula would be =[cell of xi] - ( [cell of f(xi)] / [cell of f’(xi)] ). The expression for obtaining the percentage error would remain the same as that used in the transcendental function. Please see Table 3 for an example of how the cell should be formatted. C D E f'(v) v(i+1) Error (%) P(P+(a/A2^2))*(A2A2(ABS(D21 1 (a/A2^2)+(2*a*b/(A2 b)-(R*T) (B2/C2) A2)/D2)*100 ^3)) P(P+(a/A3^2))*(A3A3(ABS(D32 D2 (a/A3^2)+(2*a*b/(A3 b)-(R*T) (B3/C3) A3)/D3)*100 ^3)) Table 3. Sample Layout of EXCEL for the Newton-Raphson Method for the van der Waals equation. P = the pressure, R = the gas constant, T = the absolute temperature, a = the measure of two particles’ attraction, b = the volume excluded by one mole of particles 0 A v B f(v) 4. Results and Conclusion a. Numerically Calculated Roots of an Equation Cannot Be Solved Analytically The Newton-Raphson method can be used to find roots of an equation that cannot be solved analytical. The main advantage of using the Newton-Raphson method is that it requires only one initial guess. The acceptable solution is reached--that is, the algorithm is considered to have converged—when the error is less than or equal 10E-6 %. As Table 4 shows, the acceptable x-value is 0.567. xi 1.000 0.538 0.567 0.567 f(xi) f'(xi) x(i+1) -0.632 -1.368 0.538 0.046 -1.584 0.567 0.000 -1.567 0.567 0.000 -1.567 0.567 Table 4. Newton-Raphson Results for the First Problem. Error (%) 8.591E+01 5.133E+00 2.756E-02 7.795E-07 b. van der Waals Equation Solutions 32 Another equation that can be solved using the Newton-Raphson method is the van der Waals equation. In this is case, the unknown will be the molar volume v. The problem requires the finding of the solutions for CO2 and O2 under 9 sets of temperature and pressure conditions. The absolute temperature, the pressure, the gas constant, the measure of two particles’ attraction, the volume excluded by one mole of particles, and the number of moles are given. The Ideal Gas Law can be used to compare the results from the Newton-Raphson method. Table 5 shows that the results for both O2 and CO2 match the solutions for the Ideal Gas Law in 8 out of 9 cases. T 300 300 300 500 500 500 700 700 700 P V-ideal gas V-O2 Van Der Waals V-CO2 Van Der Waals law 1 24.616 24.593 24.513 10 2.462 2.438 2.355 100 0.246 0.226 0.080 1 41.027 41.026 40.982 10 4.103 4.102 4.058 100 0.410 0.412 0.366 1 57.438 57.446 57.418 10 5.744 5.752 5.724 100 0.574 0.584 0.558 Table 5. Results from the Newton-Raphson Method and the Ideal Gas Law. c. Comparisons and Discussion For the first problem, four iterations were enough to find the root with an error of 7.795E07%. With EXCEL, the solution can be obtained easily. For the second problem, the initial guesses were obtained from the Ideal Gas Law . The Ideal Gas Law gives applies at low pressures and high temperatures. For 1 atm and 700 K, three iterations were enough, but at 100 atm and 300 K, seven iterations were needed. The Newton-Raphson method gives better approximations than the graphing method, so it is better to use. One must make sure, however, that the initial guess is close enough to the true root. 33 B. Solving Systems of Linear Equations A system of linear algebraic equations can be written as a11 x1 + a12 x2 + a1(n1 ) xn 1 + a1n xn = b1 , a21x1 + a22 x2 + a2(n1 ) xn 1 + a2n xn = b2 , a(n1 )1 x1 + a(n1)2 x2 + a(n1 )(n1 ) xn 1 + a(n1)n xn = bn 1 , (Eq. II.B-1) an1 x1 + an2 x2 + an(n1 ) xn 1 + ann xn = bn . There are m equations and n unknowns. Some equations are dependent on one another, that is, they are redundant forms of the same equation. Otherwise, an equation is considered independent. When there are fewer independent equations than unknowns, the system of equations is referred to as under-determined or under-constrained. In this case there are infinitely many possible solutions. When the number of independent equations is equal to the number of unknowns, the system is referred to as uniquely determined or uniquely constrained, referring to the fact that the solution is unique. When there are more independent equations than unknowns, the system is referred to as overdetermined or over-constrained. In this case, there is no exact solution to the problem although approximate solutions are possible. 1. Methods a. Overview A number of methods can be used to find the solution to a system of linear equations, provided that a unique solution exists. Graphing: By graphing each equation, the coordinates of where the lines intersect give the solution to the system. This can be done relatively easily for a 2-dimensional problem, i.e., with only two unknowns in the system. The graphs should be compared with results from other methods, and all results should roughly agree with one another, even if the graphs were not too precise. Matrix Inverse: By setting up the system of equations as matrices, their inverses might be found. Matrix operations are then used to solve the system. 34 Elimination: Elimination, sometimes referred to as Gaussian elimination, involves algebraic manipulations of one or more equations. The goal is to successively cancel out the unknowns until at least one equation has only one unknown left. Substitution is then used to solve for the rest of the system. b. Inverse Matrices and the Linear Algebra of Solving Systems of Linear Equations Using a matrix-vector notation, Eq. II.B-1 is written as (Eq. II.B.1.b-1) Ax=b If the system of equations is re-written in the form of Eq. II.B.1.b-1, it would be easy to get the inverse of matrix A using a MATLAB or Excel. x = A 1 b (Eq. II.B.1.b-2) Then the unknowns can be found from Eq. Eq. II.B.1.b-2. c. Examples of the Matrix Inverse Method and the Elimination Method To illustrate how to solve system of linear equations using matrix methods, consider the following set of equations. x1 + 2x 2 + 2x 3 = 1 (Eq. II.B.1.c-1) 2x1 + 2x 2 + 2x 3 = 2 2x1 + 2x 2 + x3 = 3 We want to solve for the unknowns x1, x2, and x3. Since there are more than two unknowns, it would be difficult to graph the problem by hand, and the interpretation of the 3-D graphs themselves might prove difficult. Graphing is thus not recommended. The first step is to express these equations in matrix form as A x = y. 1 2 2 2 2 2 2 2 1 A x1 x2 x3 x 1 2 3 (Eq. II.B.1.c-2) y 35 Next, left-multiply both sides of the equation by A-1, the inverse of A. There are a number of ways of obtaining a matrix's inverse, but the process gets very complicated for matrices larger than 3 by 3. Refer to section II.B.3 for solving for the inverse using Excel and MATLAB. 0 1 1 1 1.5 1 0 1 1 1 2 2 2 2 2 2 2 1 A 1 A x1 x2 x3 0 1 1 1 1.5 1 0 1 1 A 1 x 1 2 3 y (Eq. II.B.1.c-3) And finally, since A-1 A x = I x = x, the following is true. x1 x2 x3 0 1 1 1 1.5 1 0 1 1 1 2 3 A 1 x y 1 1 1 (Eq. II.B.1.c-4) x Thus, the unknown quantities are: x1 = 1, x2 = 1, and x3 = -1. To solve by elimination, multiply the first equation (counting from the top) in Eq. II.B.1.c-4 by -2, then add the result to the second equation, as well as the third equation. Doing so eliminates x1 from the second and the third equations. Notice that x does not change, because all the coefficients of the variables are changing with A, and the rest of the equations is changing with y. 2 1 2 0 2 2 0 2 3 A x1 x2 x3 x 1 0 1 (Eq. II.B.1.c-5) y To eliminate x2 so that the third row has only x3 left as an unknown, multiply the second row in Eq. II.B.1.c-5 by -1 and add the result to row 3. 36 2 1 2 0 2 2 0 0 1 A x1 x2 x3 x 1 0 1 (Eq. II.B.1.c-6) y Now that it is apparent x3 = -1, substitute it into the second equation or any of its variants that have resulted from the elimination steps. x2 = 1. With the values of x2 and x3, solve for x1, which turns out to be 1. These answers agree with those obtained from the matrix inverse method. Elimination can be performed even without re-writing the equations in matrix form, but it might take more steps and/or lead to more errors, depending on how neat the equations are, than a systematic approach would. 2. Problems a. Mass-Spring System Given: mass-spring system as shown in Figure 29; assume spring constants k is the same for all springs Figure 29. Mass–Spring System. 37 m1 = 2kg k = 10kg / s 2 m2 = 3kg g = 9.81m / s 2 (Eq. II.B.2.a-1) m3 = 2.5kg System of Linear Equations Representa tion : dx 2 F1 = m1 a = m 2 = 2k x 2 – x1 + m1 g kx1 d t dx 2 F2 = m2 a = m 2 = k x3 – x 2 + m2 g 2k x 2 x1 d t dx 2 F3 = m2 a = m 2 = m3 g 2k x3 x 2 d t (Eq. II.B.2.a-2) Find: the displacements x1, x2 , and x3 after free fall b. Indeterminate Structure Given: a beam supported by 3 bars with pin connections as shown in Figure 30, a force P = 40 kN is applied to the beam at a distance d Figure 30. Rigid Bar and Applied Forces. L AD = 4m E AD = 70GPa LBE = 5m E BE = 200GPa LCG = 2m ECG = 115GPa (Eq. II.B.2.b-1) 38 System of Linear Equations Representa tion : FAD + FBE + FCG = P (Eq. II.B.2.b-2) 10 FBE + 16 FCG = d P 10 LCG 6L AD 16 LBE FAD + FBE + FCG = 0 E AD AAD E BE ABE ECG ACG Elongation Function : (Eq. II.B.2.b-3) FL EA Find: forces F1AD, FBE, and FCG 3. Implementations a. Using Solver in Excel Solver is an Add-In for Microsoft Excel. With Solver, you can find an optimal value for a formula in one cell—called the target cell—on a worksheet. i. Enter your data and write the equations to the sheet. Figure 31. Data for Solver. ii. Then, write the equations using the cells B1, B2, B3, B4, B5, B8:B10, and E8:E10. iii. Define these linear equations for Solver. 39 Figure 32. The Solver Window. iv. In Solver, set target cell to be $E$11, which is the sum of all equations. v. Specify that the target cell is to be made Equal To: Value of 0, By Changing Cells: $B$8:$B$10. vi. Finally, add constraints to the problem by Subject to Constraints: $E$8:$E$10 = 0. vii. When the solve button is pressed, the initial guesses will be changed to make each of these equations equal to zero, as well as making the target cell have the specified value, in this case also 0. b. Using minverse and mmult in Excel i. First, separate the unknowns from their known values into a 3x3 matrix and have the values that don’t have any unknowns into its own 1x3 matrix, as shown in Eq. II.B.1.c-2. ii. In Excel, place the given constants into a separate cell and the values of the matrix into separate cells as shown in the figure below. m1 = m2 = m3 = k = g = [A] 30 -20 0 2 3 2.5 10 9.8 kg kg kg kg/s^2 m/s^2 -20 0 30 -10 -10 10 Table 6. Excel Input for the Mass-Spring System Problem. [b] 19.6 29.4 24.5 40 iii. To solve for the unknown values, A has to be inverted before left-multiplying it with b as shown in Eq. II.B.1.c-3. iv. To get the inverse of A: (a) Highlight a 3x3 block of empty cells. (b) Type =minverse(cells of the matrix to be inverted). E.g., if the original matrix consists of the first three rows and the first three columns, then to find its inverse, type = minverse(A1:C3). (c) Press the Ctrl, Shift, and Enter keys at the same time (Ctrl + Shift + Enter). The inverse will fill in the highlighted empty cells. v. Once the inverse of A is found, it must be left-multiplied to b to find the answer for the unknowns. To multiply matrices: (a) Highlight a 1x3 block of empty cells. (b) Type =mmult(matrix on the left of multiplication,matrix on the right of multiplication). I.e., once the 1x3 cells have been highlighted, (1) type: =mmult( (2) Then select the cells that make up the inverted matrix A-1. (3) Type a comma , before selecting the cells of the next matrix. (4) Select the cells of matrix b. To select multiple cells, hold down the Crtl key and select them one by one. (c) Press Ctrl + Shift + Enter to solve the multiplication. c. Matrix Operations in MATLAB One way to solve the matrix equation A x = b is by elimination. The backslash sign \ is used to do so in MATLAB. To help remember which variable goes before the backslash, think of A \ b as A divides into b, as opposed to A divided by b in the case of a forward slash, A / b. >> x = A \ b x = 7.3575 10.0553 12.5078 >> Figure 33. Elimination: one way of solving the mass-spring system problem. 41 Alternatively, the inverse of A can be used such that x = A-1 b. To use the MATLAB function inv, enter its name followed by a pair of parentheses, as shown in Figure 34. Inside the parentheses enter the values or variables that serve as parameters—they are often referred to as "arguments". In general, if a function requires more than one argument, commas are used to separate them, which must be entered in the order that is originally defined by the function program. Forming the explicit inverse of A, however, may reduce the accuracy of the solution obtained. Compared to Gaussian elimination Figure 33, there is a slight discrepancy in the value of the second element of x. >> AInv = inv(A) AInv = -0.1000 -0.1000 -0.1000 -0.1000 -0.1500 -0.1500 -0.1000 -0.1500 -0.2500 >> >> x = AInv * b x = 7.3575 10.0552 12.5078 >> Figure 34. Matrix Inverse: another way of solving the mass-spring system problem. d. 2-Dimensional Plotting in MATLAB The plot function is used to plot 2-D graphs generated from 1-dimensional array data. It takes an even number of arguments, in which the odd-numbered arrays contain data for the horizontal axis, and the even-numbered arrays contain data for the vertical axis. Graphs are made from pairs of consecutive arrays, counting from the first two arguments. The syntax is as follows. plot(array1,array2,array3,arrayLastMinus1,arrayLast) >> plot(d,Fad) >> 42 Figure 35. The plot Command. The subplot function creates a smaller, empty plot of specified location and size.The size is determined by the plot area divided by the row and column numbers—imagine the plot area divided into uniform rectangular cells. The location of the subplot, corresponding to the subplot number, would be the cell counted from the left to the right, from the top row to the bottom, as seen in Figure 36. The syntax is as follows. subplot(rowNumber,columnNumber,subplotNumber) >> >> >> >> >> >> >> >> plot(d,Fad) subplot(2,1,1) subplot(2,1,2) plot(d,Elongad) 43 Figure 36. The subplot Command. Once a subplot is selected, use the plot command to graph data. Use the subplot command to switch between subplots. As shown in Figure 37, after the lower graph was completed, the top subplot was selected, and a graph created there. >> >> >> >> >> >> >> >> >> >> >> >> plot(d,Fad) subplot(2,1,1) subplot(2,1,2) plot(d,Elongab) subplot(2,1,1) plot(d,Fad) 44 Figure 37. Navigating between Subplots. Note that the subplot function does not clear any part of the existing figure unless it overlaps with the newly selected subplot. As seen in Figure 38, the 4x4 subplot number15 would have overlapped with the lower 2x1 subplot, which was thus cleared. The top 2x1 subplot was not affected. >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> plot(d,Fad) subplot(2,1,1) subplot(2,1,2) plot(d,Elongad) subplot(2,1,1) plot(d,Fad) subplot(2,1,1) plot(d,Fad,d,Fbe,d,Fcg) subplot(4,4,15) 45 Figure 38. Subplots Overlap. To return to a single plot, enter subplot(1,1,1). To clear the figure of all plots, use the command clf. To make a new figure window, use the command Figure. 4. Results and Conclusion a. Mass-Spring System Solutions i. Solution Approach To solve the system using linear algebra, the initial step is to convert the forces, Eq. II.B.2.a-2, to matrix form. 3k 2k 0 2k 3k k 0 k k x1 m1 g x m g 2 2 x3 m3 g (Eq. II.B.4.a.i-1) Then, use the inverse of the force matrix to solve for displacements. 46 x1 3k x 2k 2 x3 0 2k 3k k 0 k k 1 m1 g m g 2 m3 g (Eq. II.B.4.a.i-2) Alternatively, elimination can be used on Eq. II.B.4.a.i-1. The steps are omitted here due to their complexity. ii. Using Solver to Find the Displacements Figure 39. Solver Results for the Mass-Spring System Problem. The solutions are in cells B8, B9, and B10. Note that Solver uses one or a combination of methods to fit the constraints, not necessarily relying on linear algebra. iii. Using Inverse Matrix and Matrix Multiplication to Solve the Problem 47 Figure 40. Matrix Operations in Excel for Solving the Mass-Spring System Problem. The solutions are in cells A18, A19, and A20. iv. Using MATLAB In Matlab, we solve the linear algebraic equations by getting the inverse of the coefficient’s matrix and get the results as seen on Figure 41. Figure 41. MATLAB Results for the Mass-Spring System Problem. 48 The results are in column vector form and rows are equal to x1, x,x2 , x3 respectively. b. Indeterminate Structure Solutions i. Solution Approach To solve the system, linear algebra will be used. First convert Eq. II.B.2.b-2 to matrix form. 1 1 0 10 16 LBE E BE ABE 6 LAD E AD AAD FAD FBE FCG 16 10 LCG ECG ACG 1 1 1 0 10 6 LAD E AD AAD 16 LBE E BE ABE FAD FBE FCG P Pd 0 16 10 LCG ECG ACG 1 1 (Eq. II.B.4.b.i-1) P (Eq. II.B.4.b.i-2) Pd 0 Then, use the inverse of the coefficient matrix to solve for the forces. ii. Using MATLAB For the indeterminate structure problem, solutions must be calculated and plotted for all integer distances from 0 m to 16 m, thus a total of 17 sets of equations must be solved. A for loop statement was used to perform a full round of calculations on each set, one after another. As an alternative to loop structure, a larger constraint matrix was constructed to take into account of all the distances involved. One round of calculations was performed in that approach. Either way, the solutions came out to be the same. >> Fad Fad = 1.0e+004 * Columns 1 through 9 3.1930 2.9678 2.7427 1.3918 Columns 10 through 17 1.1667 0.9415 0.7164 >> Elongad 2.5175 2.2924 2.0673 1.8421 1.6170 0.4912 0.2661 0.0409 -0.1842 -0.4094 49 Elongad = Columns 1 through 9 0.0365 0.0339 0.0313 0.0159 Columns 10 through 17 0.0133 0.0108 0.0082 >> >> Fbe Fbe = 1.0e+004 * Columns 1 through 9 2.1520 2.0858 2.0195 1.6218 Columns 10 through 17 1.5556 1.4893 1.4230 >> Elongbe Elongbe = Columns 1 through 9 0.0108 0.0104 0.0101 0.0081 Columns 10 through 17 0.0078 0.0074 0.0071 >> >> Fcg Fcg = 1.0e+004 * Columns 1 through 9 -1.3450 -1.0536 -0.7622 0.9864 Columns 10 through 17 1.2778 1.5692 1.8606 >> Elongcg Elongcg = Columns 1 through 9 -0.0047 -0.0037 -0.0027 0.0034 Columns 10 through 17 0.0044 0.0055 0.0065 0.0288 0.0262 0.0236 0.0211 0.0185 0.0056 0.0030 0.0005 -0.0021 -0.0047 1.9532 1.8869 1.8207 1.7544 1.6881 1.3567 1.2904 1.2242 1.1579 1.0916 0.0098 0.0094 0.0091 0.0088 0.0084 0.0068 0.0065 0.0061 0.0058 0.0055 -0.4708 -0.1793 0.1121 0.4035 0.6949 2.1520 2.4435 2.7349 3.0263 3.3177 -0.0016 -0.0006 0.0004 0.0014 0.0024 0.0075 0.0085 0.0095 0.0105 0.0115 50 Figure 42. MATLAB Solutions for the Indeterminate Structure Problem. Using either the loop structure or a larger constraint matrix, the solutions came out to be the same. The text output lists in a single row the results of the calculations for distances from 0 m to 16 m for each property of interest: the force at A, the elongation of AD, the force at B, the elongation at BE, the force at C, and the elongation at CG. Notice that at some point close to 12 m, all elongations are the same, meaning that the beam would not only be straight, thus satisfying the third equation in Eq. II.B.2.b-2, but also be level with respect to the coordinate system used. c. Comparisons and Discussion Solver was reliable and quick. It can be used not only on linear algebra problems but also on other kinds of problems dealing with constraints. With an increasing number of equations, however, it would be time-consuming to set-up them all up. This disadvantage is true for all Excel methods, including matrix operations that involve a large number of cells that need data or formulas to be entered or cross-referenced. MATLAB, however, is designed to help users input and manipulate large arrays. The required steps are less tedious, especially when using variables to stand for frequently used yet non-constant parameters. Excel was adequate for solving the mass-spring system. It took some time to enter the formulas and check them for errors. Once set-up, however, the calculations were completed 51 almost immediately. Data entry in MATLAB was much easier compared to Excel because MATLAB can work with variables. No difference was noticed in terms of solution accuracy and how long the actual calculation took, whether using Solver, inverse matrices, or elimination, whether in Excel or in MATLAB. MATLAB is probably much better suited for the indeterminate structure problem than Excel is, considering the latter was not even used. There were a lot more data compared to the first problem, which would be difficult to point-and-click on a spreadsheet. Moreover, varying the parameters of the problem in Excel would mean that all results must be kept, becoming increasingly difficult to keep track of. Although Excel dynamically updates the cell values, it cannot expand arrays of data automatically as the problem’s scope changes. Moreover, MATLAB codes can be re-used. In Excel, however, since the programs (formulas, macros, etc.) may be tied to the cells’ locations, they often cannot be used on a different but similar problem. In conclusion, for a relatively simple problem that must be presented soon, Excel might be the better choice. For anything more complex, especially when building a large project of solutions, MATLAB should be used. 52 C. Optimization The goal of optimization theory is to find the "best available" value or values of some objective function given a defined domain. When the domain is global, that is, as large as mathematically possible, global maxima or minima are sought, as seen in Figure 43. Otherwise, local extrema are sought. Many engineering applications incorporate optimization at every step of the decisionmaking process. Figure 43. Global and Local Extrema. Optimization is somtimes similar to root-finding when it also involves the guessing of some initial values with which to start off the search and the actual search for the roots of some functions related to the original objective function. For example, the gradient methods of optimization require the computation of the derivatives. At an extrema, all first derivatives should be zero. f ˆ f ˆ f ˆ i j k ... 0 x y z 53 Whether the extreme point is an extremum or a saddle-point—where the slope is flat but the curvature or higher derivatives is not—depends on the value of the higher derivatives of the function at that point. For example, the Hessian matrix is the square matrix of the second partial derivatives of a function. In the two-dimensional case, if its determinate, also referred to as the Hessian, were positive, then the point where it is evaluated is an extremum. If the second derivative is also greater than zero, then the point would be a local minimum; if it were less than zero, then the point would be a local maximum. When the Hessian is negative, the point is a saddle-point. When the Hessian is zero, then one must look further at the higher derivatives at that point in order to discriminate between an extremum and a saddle-point. The extrema of a function can be also be found using direct methods, which do not require the computation of derivatives. Random search methods require the evaluation of the function at several points. If the function were evaluated at a sufficiently large number of points, then the desired extremum may be found. A univariate search would set all but one independent variables constant while looking for an extremum with respect to the free variable. Similar processes are undertaken sequentially for the rest of the independent variables. 1. Problems a. Finding Extrema 2 2 Given: f ( x, y) y x 2 x 2 xy y Find: the maximum of the given function b. Bicycle Truss Figure 44. Bicycle Truss Problem. 54 Given: the Young Modulus E = 2 1011 Pa, the cross-sectional area A = 0.0001 m2 , the width w = 0.44 m, the length L = 0.56 m, the height h = 0.5 m Find: the horizontal and vertical displacements at the point of applied force if the angle θ were to shift between 0 and 90 degree and predict the effects on the displacements if the width, lenth, or height of the truss were to change. 2. Implementations a. Creating Surface Charts in Excel Creating a surface chart in Excel is similar to creating any other type of charts. First, select a grid of data to be graphed. Then, click on the Chart feature, or one of the several options for charts if they are already being listed, under the Insert menu. Be sure that Surface is selected as the chart type. Figure 45. Excel Surface Chart for the First Problem. Right-clicking on the chart brings up the context menu, under which the 3-D View… option may be adjusted, as Figure 46 shows. In fact, using the proper configurations, a surface chart turns in to a contour plot viewed from above, as seen in Figure 47. Right-clicking on the 55 legend and formatting it allows the user to adjust the density of isolines by changing the major unit value of the z-axis, in this case from 200 to 100, as showed in Figure 47, 48, and 49. Figure 46. Changing the 3-D View Parameters of a Surface Chart. Figure 47. Surface Chart Turned into a Contour Plot. 56 Figure 48. Formatting the Legend of a Surface Chart. Figure 49. Increased the Density of Isolines after Decreasing the Major Unit Value. b. Using Solver to Find Extrema 57 Solver is an Add-In for Microsoft Excel. With Solver, you can find an optimal value for a formula in one cell—called the target cell—on a worksheet. i. Write the equations using the corresponding cells. Figure 50. Formula for Finding Extrema Using Solver. ii. Enable Solver; a Solver Parameters window will appear. Figure 51. Solver Paremeters Window. iii. In Solver, set target cell to be $C$2. iv. Specify that the target cell is to be calculating the max of the equation. v. Finally, set the changing cells to A2 and B2. vi. When the solve button is pressed, the cell A2 and B2 will be updated. c. Calculating Numerical Gradients in MATLAB The gradient function takes in an array of j dimensions and returns j arrays, each containing the numerically calculated gradient or differences along one of the dimensions of the input array. Since gradient uses only the input array, the results of its computations may or may not match the actual partials of whatever function that might underlie the input data. gradient also switches the order of the outputs for the 1st and the 2nd dimensions; that is, the first array returned contains the computed gradients along the 2nd dimension of the 58 input array, whereas the second array returned contains the computed gradients along the 1st dimension of the input array. The syntax is as follows. [array2ndDim, array1stDim, array3rdDim, array4thDim, arrayLastDim] = gradient(arrayInput, h1stDim, h2ndDim, h3rdDim, h4thDim, hLastDim) The h parameters following arrayInput specify the scaling factors that are divided by the computed gradients before being returned. If omitted, then the value of 1 is assumed. They are often used to match gradient results with data sets whose intervals between elements are not valued at 1. % Function f(x,y) variables changes from -5 to 5 [x,y] = meshgrid([-5 : 0.5 : 5]); % Function values f(x,y) are given as the matrix fun1 fun1 = y - x - 2 .*x .^2 - 2 .*x .*y - y.^2; % The gradient of the function is calculated for points along x and y % directions 0.5 apart. [dx,dy] = gradient(fun1,0.5,0.5); Figure 52. Gradient Generation for Finding the Extrema of an Function. d. Searching for Extrema Using fminsearch in MATLAB The fminsearch function takes in a function and an array of initial positions and searches for the function’s local minimum starting from the specified initial positions. If the search algorithm converges, then fminsearch returns the minimum found, the function value at that minimum, and perhaps some related information. fminsearch can be used to solve linear or non-linear unconstrained optimization problems. Its syntax is as follows. [arrayMin, funValueMin, exitflag, output] = fminsearch(function, arrayInitial, optimset(expressionOfOptions)) If the optional keyword exitflag is used, then fminsearch would also return a 1 if the algorithm has converged, a 0 if the maximum number of function evaluations or of iterations has reached, or a -1 if the algorithm was otherwise terminated. If the optional keyword output is used, then fminsearch would return information on the algorithm used, the number of function evaluations, the number of iterations, and an exit message. The optimset function is optional; it allows the user to specify additional options, such as ‘TolFun’ for the termination tolerance on the function value and ‘TolX’ for the termination tolerance on the minimum being searched for; they are set to 1E-4 by default. These options are entered by typing a keyword as a string, followed by a comma, followed by the desired value, followed by another comma if another keyword is to be entered. Sometimes the function to be minimized takes more arguments than an array of initial positions. In that case, fminsearch can call an anonymous function constructed such that it 59 captures as constants any arguments in addition to an array of initial positions and behaves as if the arrayInitial argument is the only variable. The example in Figure 53 and 54 uses this technique as well. for j = 1:91 theta = (j - 1) * pi / 180; [minm,fminm,exitflag,output] = fminsearch(@(Deform) energyFn(Deform,theta,11,11),[1E-3,1E-3],optimset('TolFun', 1E-8,'TolX',1E-8)) X(j) = minm(1); Y(j) = minm(2); U(j) = fminm; End Figure 53.fminsearch with Options for the Bicycle Truss Problem (M-File). minm = 1.0e-003 * 0.8420 0.0000 fminm = -4.2098 exitflag = 1 output = iterations: 48 funcCount: 93 algorithm: 'Nelder-Mead simplex direct search' message: [1x196 char] minm = 1.0e-003 * 0.8418 0.0028 fminm = -4.2088 exitflag = 1 output = iterations: 47 funcCount: 91 algorithm: 'Nelder-Mead simplex direct search' message: [1x196 char] Figure 54. fminsearch Outputs for the Bicycle Truss Problem (Command Window). e. 3-Dimensional Visualization in MATLAB MATLAB is capable of graphing an array of data in the third dimension, that is, as z-values in an x-y-z coordinate system. One of the commands used is mesh and its variants meshc and meshz. The syntax is as follows. The … means that any kind of input that is valid in other situations would be valid here as well. mesh(arrayZValues) mesh(arrayXDomain, arrayYDomain, arrayZValues) meshc(…) meshz(…) 60 If arrayXDomain and arrayYDomain are one-dimensional, i.e. vectors, then the columns of arrayZValues would correspond to the elements in arrayXDomain, and the rows would correspond to the elements in arrayYDomain. If arrayXDomain and arrayYDomain are twodimensional arrays, then each data point in arrayZValues would simply be associated with the identically indexed elements in arrayXDomain and arrayYDomain. If no domain information is specified, then the z-values would be plotted on a domain region generated by default to match the dimensions of arrayZValues. mesh draws a wireframe whose intersections are formed from the x-, y-, and z-values; if a graph with colored/filled-in surfaces is desired, then the surf command should be used instead. The meshc command draws a contour plot in the x-y plane below the wireframe. The meshz command draws a curtain around the wireframe. One way to generate a domain region is to use the meshgrid function, which takes in a number of vectors and outputs the same number of identically sized arrays such that the jth dimension of the j-th array would consists of the j-th vector, with no variations in any other dimension. In addition, the order of the first two vectors and thus that of the first two output arrays are switched. The syntax is as follows. Note that meshgrid can take two or three vectors as inputs. meshgrid(vectorX, vectorY) meshgrid(vectorX, vectorY, vectorZ) The contour command takes in an array and plots the projection of its isolines, sometimes referred to as elevation lines, onto its domain plane. To label the isolines with their z-values, contour matrices and handles must be generated before using the clabel command. The syntax is as follows. contour(arrayZValues) [contourMatrix, handleMatrix] = contour(arrayZValues) clabel(contourMatrix) The quiver command plots vectors on a plane. The vectors’ x- and y-components, as well as the plotted region of the plane, can be specified by a total of four two-dimensional arrays of the same size. The syntax is as follows. quiver(arrayXDomain, arrayYDomain, arrayXComponents, arrayYComponents) By default, each time a graph is drawn, MATLAB replaces any previous graphs and re-sizes the plot. To add graphs on top of each other, use the hold command to retain previous graphs or toggle turn this feature off. The syntax is as follows. 61 hold on hold off figure(1); % Creates a new figure with handle 1. meshz(x,y,fun1); % A 3-D curtain graph is drawn for fun1. figure(2); % Creates a new figure with handle 2. hold on; % so that new graphs do not displace previous graphs in the same plot. [c,h] = contour(x,y,fun1); xlabel('x'); ylabel('y') % Contours of fun1 plotted clabel(c); % Function values of the contours are displayed. quiver(0,0,0,0,'o'); % Draws a zero vector to mark the origin at (0,0). quiver(x,y,dx,dy) % Displays velocity vectors as arrows at the points (x,y). hold off; Figure 55. Graphing the First Problem (M-File). Figure 56. Curtain Plot of the First Problem. 62 Figure 57. Contour Plot of the First Problem. 3. Results and Conclusion a. Finding Extrema Solutions This problem can be solved with gradient methods and direct methods. Excel uses gradient method and Matlab uses direct methods to find the extremum of the function. For Excel solution Solver Add-In is used. In Matlab fminsearch function is used. This function finds the minima of the function so in order to get the maxima of the function equation is multiplied by -1. Excel Solver Add-In used to find the minimum value of the function. The two variables x, and y are manipulated to find the maxima. Figure 58. Solver Results for the Maxima. 63 Matlab fminsearch command used to solve the problem. The maxima of the function can be found at x= 1.000026308959714 y= 1.500043574205774. The Matlab output is: fun2 = @(V)((V(2)-V(1)-2*V(1)^2-2*V(1)*V(2)-V(2)^2)*-1) XY = -1.000026308959714 1.500043574205774 fval = -1.249999999009750 exitflag = 1 output = iterations: 28 funcCount: 54 algorithm: 'Nelder-Mead simplex direct search' message: [1x196 char] EDU>> Figure 59. Matlab Solution for Finding the Extremum. To visualize the solution contour command is used. Isolines (circles) and the gradient (velocity vectors – arrows) is seen on the graph in Figure-3. The maxima point is signed with "o". Figure 60. Contour plot of the First Problem. b. Bicycle Truss Solutions Displacement x and y can be solved by minimizing potential energy of the trust. F = 10000 N 0 < θ < 90° 64 2 V ( x, y ) 2 EA w 2 EA h 2 x y Fx cos Fy sin l 2l l l Figure 61.Free Body Diagram of the bicycle bracket. Using Solver potential energy is set to minimum then x and y variables manipulated to find the minima. The results for 30° can be seen in cells B8 and B9. For a different angle, the theta value at B10 should be changed and Solver re-run. Three sets of results were gathered; one for the x-displacement, one for the y-displacement, and one for the minimized potential energy. They were plotted in Figure 63. Intuitively, the x-displacement is the smallest when the angle is at 90 degree, and the y-displacement the least when the angle is at 0 degree. At around 80 degree, the x- and y-displacements are identical. It is observed that, at least for the current configuration, the x-displacement changes much more across the angles, in fact almost 5 times as much, compared to the y-displacement. This behavior agrees with the nature of the problem, in that it actually lacks a second horizontal member—the two existing members act as one horizontal member in the xdirection—but has two members acting redundantly in the y-direction, that is, with a greater combined cross-sectional area. Understandably, the stresses on the two existing members trying to stay continuous seem to be much greater in the x direction than they are in the y-direction, leading to greater displacements. Figure 62. Excel Solution for the Bicycle Truss Problem at 30 Degree Angle. 65 Figure 63. Excel Chart for the Bicycle Truss Problem Solutions from 0 to 90 Degree Angle. In Matlab, the for loop was used to find the minima values of the function for each theta angle. The results, almost identical to those from Excel,are shown in Figure 64 and 65 for angles from 0 to 90 degree. Columns = Theta X Allvalue = 0 0.000912237259423 Y Min. Pot. Energy -0.000000796378662 -4.535374083757671 10.000000000000000 0.000894162250719 0.000031038828136 -4.425239102611168 20.000000000000000 0.000851851240847 0.000061227384236 -4.107655779395699 30.000000000000000 0.000785823902867 0.000087334759019 -3.621166183163207 40.000000000000000 0.000695150035326 0.000111751381119 -3.024327084719397 50.000000000000000 0.000582744753326 0.000136765341272 -2.389110290360057 60.000000000000000 0.000453825933965 0.000152900167551 -1.792425105180489 70.000000000000000 0.000308687243308 0.000165693951491 -1.305895033770616 80.000000000000000 0.000156446016133 0.000173568763562 -0.988348528628919 90.000000000000000 0.000002279772845 0.000176117329187 -0.878044196295685 Figure 64. Matlab output. 66 Figure 65. Displacement and Potential Energy change with respect to angle. c. Comparisons and Discussion i. Optimization Solver can search for not only a minimum but also a maximum or a certain function value, whereas fminsearch searches for a minimum only. In Excel 2003, Solver uses the Generalized Reduction Gradient code, which includes the simplex method and the branch-and-bound method. No information has been found regarding what Solver uses on a specific problem, or what it uses in Excel 2007, but its Options dialog box suggests that it is capable of using derivatives, even if not on every problem. fminsearch uses the Nelder-Mead simplex direct search, which does not entail numerical or analytical computations of gradients. It appears that Solver can handle more types of problems than fminsearch can, especially since it can search for a maximum or a certain function value in addition to a minimum. MATLAB might have other functions useful for optimization, however. To compare Solver and fminsearch, the number of iterations can be counted, but an iteration in Solver might not have of the same calculations involved in an iteration using fminsearch. There is no way to resolve this uncertainty with the limited amount of information available on these two programs. Another approach would be to time the calculation process, but doing so would incur not only human errors but also factors such as software and hardware performances beyond the two algorithms themselves. Thus, although some data have been gathered on how the two programs were solving certain problems, no comparisons can be really made. In the first problem, Solver took 7 67 iterations, whereas MATLAB took 39 iterations. Both started the search at (1, 1), with the tolerance in Solver set to 5% of the target (in this case, the maximum at 1.25) and the tolerance for fminsearch set to 6.25E-2. Figure 66. Solver Searching for Maximum, Minimum, or Function Value. The option Max was used since the original problem asks for a local maximum of a function. fminsearch used a function that was the negative of the original function, so that fminsearch’s minimum is Solver’s and the actual maximum. Notice that the initial position was (1, 1), which is the same as that for fminsearch. Figure 67. Solver Options. To count the number of iterations, Show Iteration results must be checked. Also note the tolerance, which is set to 5% of the target, if the algorithm converges. Figure 68. Solver Iteration Dialog Box. 68 After each iteration, a dialog box would prompt the user for how to proceed. Figure 69. Excel Status Bar for Solver Iteration 1. Excel’s status bar would display which iteration Solver was on, and the target value. For the first problem, Solver took 7 trial solutions or iterations before terminating. Figure 70. Excel Status Bar for Solver Iterations. ii. Sensitivity Analysis in Excel and MATLAB Solver has a sensitivity analysis feature included and was able to generate sensitivity reports for potential energy, which is the target to be minimized, in terms of the truss’s width, height, or diagonal length, as Figure 71 shows. However, for this particular problem, the x- and y-displacements might turn out to be imaginary depending on the constraints or even the range of values Solver uses to optimize the target. This turned out to be an insurmountable problem, since imaginary results cannot be interpretted. Going for real results would have required trial-and-error, which might never find a set of parameters that works at every angle, not to mention doing so would take a much longer time than anticipated. Figure 71. Solver Sensitivity Report. Instead, MATLAB was used. Since it doesn't come with any built-in sensitivity analysis features, a brute force approach was undertaken by where 21 different widths (from 0.24 m to 0.64 m, 0.02 m apart) at the original height were used as inputs for energy minimization, and 21 different heights (from 0.3 m to 0.7 m, 0.02 apart) at the original width were also used as inputs for energy minimization. The results for angles from 0 to 69 90 degree, 1 degree apart, are shown in Figure 72 and 73. Notably, starting with the original configuration, the x-displacement is much more sensitive to changes in either width or height than the y-displacement. This behavior is consistent with the observation noted in section 3.b. It was also observed that changes in the width and the height have a non-linear effect on the x-displacement, since reducing either one gives a smaller and smaller effect, but elongating it yields greater and greater displacements. This is consistent with the energy minimization equation, in which the value of width and that of height are both squared. They may also have a non-linear effect on the ydisplacement, but since y-displacement changes so little compared to x-displacement, more refined testing should be conducted in order to confirm the conjecture. Figure 72. Varying the Width of the Bicycle Truss. 70 Figure 73. Varying the Height of the Bicycle Bracket. iii. Future Considerations In terms of optimization, nothing can be concluded at this point except that Solver appears to be more versatile than fminsearch, if not MATLAB as a whole. Solver very conveniently comes with a sensitivity analysis feature, which should be used unless Solver cannot solve the actual problem first, e.g. in the case of the bicycle truss problem with the x- and y-displacements. In terms of graphing, MATLAB is preferred because not only can it do what Excel does, but also a lot more, given the same amount of time put in. 71 D. Numerical Integration 1. Methods a. Trapezoid Rule When an equation is not given, the trapezoidal method is one of the many methods used to finding the numerical integration of the given points under a curve. The formula is shown as: b I f ( x) (b a) a f ( a) f (b) 2 Figure 74. Trapezoid Rule. b. Simpson's 1/3 Rule The Simpson’s method can be broken down farther to the 1/3 rule and the 3/8 rule. The 1/3 rule is an extension of the trapezoidal rule where the integration is approximated by a second order polynomial as shown in the formula as: I N N 1 h f ( a ) 4 f ( x ) 2 f ( x j ) f (b) i 3 i 2, 4, 6,... j 3, 5, 7 ,... where h ba N 72 c. Simpson's 3/8 Rule The Simpson’s 3/8 rule approximates the integral by letting the values of a function be tabulated at the given points. The formula is given as: N 1 N 2 3 I h f (a) 3 f ( xi ) f ( xx 1 ) 2 f ( x j ) f (b) 8 i 2, 5,8,... j 4, 7 ,10,... 2. Problem a. Work Figure 75. Work Problem. x, ft F(x), lbf 0 5 10 15 20 25 30 0.0 9.0 13.0 14.0 10.5 12.0 5.0 θ , rad F(x) cos θ, lbf 0.50 0.0000 1.40 1.5297 0.75 9.5120 0.90 8.7025 1.30 2.8087 1.48 1.0881 1.50 0.3537 Table 7. Expermimental Data for the Work Problem. Find the amount of work used to pull the box from points 1 to 2 using the trapezoidal and Simpson methods. 3. Implementations a. Using Spreadsheet in Excel i. Duplicate the original table with the known data to excel. 73 Figure 76. Excel data for the Work Problem. ii. Create a table with the correct label for each of the methods, their solutions, the best solutions, and the percentage errors. Figure 77. Required Results Table for the Work Problem. iii. Enter the formulas for the different segments on each of the methods with the corresponding cells. Figure 78. Trapezoid Rule Formula in Excel for the Work Problem. 74 Figure 79. Simpson 1/3 Rule in Excel for the Work Problem. Figure 80. Simpson 3/8 Rule in Excel for the Work Problem. iv. Pick a best result from each of the methods. v. Compute for the percentage of error of each segment from the 3 methods to the best results. Figure 81. Computing % Error in Excel for the Work Problem. b. Interpolation Using interp1 and ppval in MATLAB 75 The interp1 function is often used to interpolate data points given as two vectors, one containing values of the independent variable and the other containing 1-dimensional values of the dependent variable. For function values of more than one dimension, the interp2, interp3, or interpn function should be used instead. There are several ways of using interp1—interpolating over a specified domain, interpolating using a particular method, generating an interpolating polynomial, among others. The syntax is as follows. YInterpolated = interp1(XData,YData,XDomain) YInterpolated = interp1(XData,YData,XDomain, method) PiecewisePolynomial = interp1(XData,YData,method,'pp') The arguments for the method field are 'nearest' (nearest neighbor interpolation), 'linear' (linear interpolation, which is the default), 'spline' (cubic spline interpolation), 'pchip' (piecewise cubic Hermite interpolation), 'cubic' (Same as 'pchip'), and 'v5cubic' (cubic interpolation as used in MATLAB 5). To generate an interpolating piece-wise polynomial structure (of any name, not necessarily pp), use the string 'pp'. The interpolating polynomial generated by interp1 can be evaluated by the function ppval if a domain vector were to be specified. The result is a vector containing the interpolated values over the specified domain. The syntax is as follows. YEvaluated = ppval(Polynomial,XDomain) Fpp = interp1(X,F,'pchip','pp')'; Ffit = ppval(Fpp,Xfit); Fcospp = interp1(X,Fcos,'pchip','pp')'; Fcosfit = ppval(Fcospp,Xfit); Figure 82. Interpolating Using interp1 and ppval for the Work Problem (M-File). In the work problem, the data given—X, F for force versus x-displacement and X, Fcos for tangential force versus x-displacement—were interpolated into the piecewise cubic Hermite polynomials Fpp and Fcospp. They were subsequently evaluated as Ffit and Fcosfit, respectively, over the domain XFit. c. Numerical Integration in MATLAB The trapezoid rule, Simpson's 1/3 rule, and Simpson's 3/8 rule were programmed in MATLAB with the help of for loops, as shown in Figure 83. The basic rules were used instead of the composite rules, even though the latter might be more efficient to execute compared to repeating a simple rule in a loop, because the composite rules would not work well on 76 intervals of different sizes. Since we weren't crunching a lot of numbers, we stayed with a more versatile albeit a bit slower executing code for the time being. The results of the trapezoid rule function were compared to those of the built-in trapz function and were found to be identical, as seen in Figure 83. MATLAB also has a built-in quad function for numerically integrating an already-defined function using adaptive Simpson quadrature. For this problem, a spline-fit function of the experimental data were used with the quad function, and the number of functon evaluations used was output along with the integration result, as seen in Figure 85. function [sum] = trapezoid(X,Y) temp = 0; Xsize = size(X); for j = 1:Xsize(2) - 1 temp = temp + 0.5 * (X(j + 1) - X(j)) * (Y(j) + Y(j + 1)); end sum = temp; function [sum] = simpsons13(X,Y) temp = 0; Xsize = size(X); for j = 1:2:Xsize(2) - 2 temp = temp + 1 / 6 * (X(j + 2) - X(j)) * (Y(j) + 4 * Y(j + 1) + Y(j+2)); end sum = temp; function [sum] = simpsons38(X,Y) temp = 0; Xsize = size(X); for j = 1:3:Xsize(2) - 3 temp = temp + 1 / 8 * (X(j + 3) - X(j)) * (Y(j) + 3 * Y(j + 1) + 3 * Y(j + 2) + Y(j + 3)); end sum = temp; Figure 83. MATLAB Implementations of the Trapezoid Rule, Simpson's 1/3 Rule, and Simpson's 3/8 Rule. 4. Results and Conclusion a. Solutions 77 Figure 84. Excel Results and Some MATLAB Results for the Work Problem. {Prob1a} work as sum:(F * dx), Trapezoid Rule Results for 1, 2, 3, 6, 30, and 60 segments, respectively: P1aTrap1 = 75 P1aTrap2 = 247.5000 P1aTrap3 = 260 P1aTrap6 = 305 P1aTrap30 = 314.1000 P1aTrap60 = 314.3844 Simpson's 1/3 Rule Results for 2, 6, 30, and 60 segments, respectively: P1aThird2 = 305 P1aThird6 = 320 P1aThird30 = 314.4880 P1aThird60 = 314.4792 Simpson's 3/8 Rule Results for 3, 6, 30, and 60 segments, respectively: P1aEighth3 = 283.1250 P1aEighth6 = 312.1875 P1aEighth30 = 314.4754 P1aEighth60 = 314.4789 MATLAB trapz Trapezoid Rule Results for 6 and 60 segments, respectively: P1aTrapz6 = 305 P1aTrapz60 = 314.3844 Respectively, MATLAB quad Adaptive Simpson Quadrature Integration Result for 78 and Number of Function Evaluations on the Linear Interpolant Function: P1aQuad = 314.4792 P1aQuadCount = 109 {Prob1b} work as sum:(F * cos(theta) * dx), Trapezoid Rule Results for 1, 2, 3, 6, 30, and 60 segments, respectively: P1bTrap1 = 5.3055 P1bTrap2 = 133.1903 P1bTrap3 = 124.9755 P1bTrap6 = 119.0893 P1bTrap30 = 119.1858 P1bTrap60 = 119.1888 Simpson's 1/3 Rule Results for 2, 6, 30, and 60 segments, respectively: P1bThird2 = 175.8185 P1bThird6 = 117.1272 P1bThird30 = 119.1865 P1bThird60 = 119.1898 Simpson's 3/8 Rule Results for 3, 6, 30, and 60 segments, respectively: P1bEighth3 = 139.9343 P1bEighth6 = 117.3266 P1bEighth30 = 119.1638 P1bEighth60 = 119.1918 MATLAB trapz Trapezoid Rule Results for 6 and 60 segments, respectively: P1bTrapz6 = 119.0893 P1bTrapz60 = 119.1888 Respectively, MATLAB quad Adaptive Simpson Quadrature Integration Result for and Number of Function Evaluations on the Linear Interpolant Function: P1bQuad = 119.1898 P1bQuadCount = 101 Figure 85. MATLAB Results for the Work Problem. b. Comparisons and Discussion 79 An issue that has emerged from comparing the different numerical integration solutions is that we do not really know which solution might be the most accurate. Solutions developed from only a few intervals can be considered less accurate, in average, due to the large amount of errors intrinsic in calculations using fewer data points than is available, as seen in Figure 84 and 85. On the other hand, as far as we can tell, the magnitude of the force and its direction seem to vary haphazardly. Therefore, whether we fit a function over the entire data set or in a piece-wise fashion, whether linear interpolants or higher-order polynomials are used, there is no model to judge the fit beyond the available data. In fact, what the trapezoid rule does is essentially fitting each data interval using a linear interpolant, while the Simpson's rules fit sets of three or four data at a time using a higher order polynomial. In short, we want to use as many data points as possible, which helps with any of the methods employed, but beyond that, it becomes a matter of opinion since we don't have any idea, experimentally or theoretically, regarding how the actual process behaves (linearly, cubically, perhaps exponentially, etc.) and the variance of the experimental data—whether there is a pattern to every change or are most of the variations random. 80 E. Solving Ordinary Differential Equations Numerically A differential equation is a mathematical equation for an unknown function of one or several variables that relates the values of the function itself and its derivatives of various orders. Differential equations play a prominent role in engineering, physics, economics, and other disciplines. An ordinary differential equation is an equation containing derivatives of a single variable. Its order is the order of the highest derivative it contains. Given sufficient initial conditions, the underlying function and all its derivatives can be found using numerical methods. 1. Methods a. Euler's, Heun's, and Runge-Kutta The Rutta-Kutta method essentially uses a higher-order derivative as a linear approximation for extending a lower-order derivative from one point to the next. As shown in Figure 88, higher-order Runge-Kutta methods use interim points to calculate slopes, which are averaged before taking a step from one point to the next. Euler's method and Heun's method are first and second-order, respectively, forms of the Rutta-Kutta method, as seen in Figure 86 and 87. Figure 86. Euler's Method. 81 Figure 87. Heun's Method. Figure 88. Fourth Order Runge-Kutta Method. 2. Problem a. Pendulum Motion 82 Figure 89. Pendulum Motion Problem. Given: Find: the angle of the pendulum as a function of time for the first 18 secons after release 83 3. Implementations a. Built-In ODE Solvers in MATLAB MATLAB provides a number of routines or solvers, based on different numerical methods, for solving ordinary differential equations, some of which are listed in Table 9. ode45, ode23, and ode113 are usually used on non-stiff problems. For stiff-problems, ode15s, ode23s, ode23t, and ode23tb should be used due to the inefficiencies of the first three solvers mentioned. ode15i solves ODEs in the implicit form f(t, y, y') = 0, whereas all the other solvers works on the explicit form y' = f(t, y) only. All of them can solve a system of ODEs specified as a function that returns a column vector, each of whose rows evaluates an equation in the appropriate form for the particular solver being used. ode45 ode23 ode113 ode15s ode23s ode23t ode23tb ode15i based on Runge-Kutta (4,5) formula, the Dormand-Prince pair Runge-Kutta (2,3) pair of Bogacki and Shampine variable order Adams-Bashforth-Moulton PECE solver variable-order solver based on the numerical differentiation formulas (NDFs); optionally uses the backward differentiation formulas, BDFs (also known as Gear's method) modified Rosenbrock formula of order 2 an implementation of the trapezoidal rule using a "free" interpolant an implementation of TR-BDF2, an implicit Runge-Kutta formula with a first stage that is a trapezoidal rule step and a second stage that is a backward differentiation formula of order 2 variable order BDF method Table 8. Some of the MATLAB ODE Solvers. In a stiff problem, solutions sometimes change very quickly compared to the interval of integration, but its long-term trend, which is usually of interest, changes much more slowly. Methods not designed for stiff problems become inefficient on intervals where the solutions change slowly because they would still be using time steps small enough to resolve the fastest possible change. For example, as seen in Figure 90, there are non-stiff and stiff solutions to van der Pol equations. In the former case, changes are relatively even throughout. In the latter case, there are long intervals of relatively slow changes punctured by short intervals of very drastic changes. 84 Figure 90. Non-Stiff (Left) and Stiff (Right) Problems. The syntax of ode15i and that of the other ODE solvers are as follows. Note that for ode15i, the initial values are specified as separate arguments. For the other solvers, the InitPoint argument should be a vector. The optional options argument sets tolerances, step size, and other properties of the solver's behavior. [TValues,YValues] = ode15i(OdeHandle,TDomainInterval,InitY,InitYFirstDeriv,options) [TValues,YValues] = OtherSolver(OdeHandle,TDomainInterval,InitPoint,options) Also notice that the ODE function's handle, not the function itself, must be passed to the solver, as shown in Figure 91. The handle is usually generated by preceding a function name with an @ symbol. It may also be bound to a variable or precede an anonymous function expression. [T45,Y45] = ode45(@systemFn,range,initOde); [T15s,Y15s] = ode15s(@systemFn,range,initOde); [T23,Y23] = ode23(@systemFn,range,initOde); [T23t,Y23t] = ode23t(@systemFn,range,initOde); [T23tb,Y23tb] = ode23tb(@systemFn,range,initOde); Figure 91. Using MATLAB ODE Solvers for the Pendulum Motion Problem (M-File). The solutions using some of the MATLAB numerical solvers were plotted. In this case, they are quite close to one another and all correctly converge to zero oscillation as time passes, as seen in Figure 92. 85 Figure 92. Using MATLAB ODE Solvers for the Pendulum Motion Problem (Figure). 4. Results and Conclusions a. Solutions As shown in Figure 93, the solutions agree with what we know about the actual process, in which the pendulum oscillates in a sinusoidal fashion but eventually comes to rest as friction dampens its motion over time. The angular displacement, velocity, and acceleration appears to be out of phase of one another by 90 degrees, thus consistent with the changing direction of the restoring force of gravity with respect to the path of the pendulum, and also 86 consistent with the conservation of kinetic and gravitational potential energy. Figure 93. MATLAB ODE Solver Solutions for the Pendulum Motion Problem. b. Comparisons and Discussion i. Numerical Solutions to Differential Equations The solutions of the MATLAB solvers used—ode45, ode15s, ode23s, ode23t, and ode23tb—were very close to one another, as seen in Figure 93. Moreover, we didn't have any control over the step sizes used. To experiment further, we implemented a most basic Euler's method (Euler1) and some sort of Heun's method (Heun2) to see how they perform. The number of steps used was around 550, similar to that of ode45, ode23s, and ode23tb. As seen in Figure 94, Heun2 did very well, its solutions roughly identical to those of ode45 and ode23tb. Euler1 performed poorly given the initial number of steps; in fact, it did not even show any sign of coming to rest as time progresses. As shown in Figure 95, after decreasing the step size down to 1/10th of the initial size, Euler1's solutions did come close to the results of the other methods, although the discrepancies were still noticeable on the graphs. 87 Figure 94. Euler1 and Heun2 Compared to ode45 and ode23tb at Roughly 550 Steps. 88 Figure 95. Euler1 Converges As Step-Size Decreases. Such dramatic difference between the Euler's method and the Heun's method comes from at least two factors. First, in Heun's method, every derivative is averaged with what it would have been at the next step, and this average is used to re-calculate the next step of the function. No averaging between the current step and any preliminary next step occurs in Euler's method. Second, when implementing Euler1, whatever effect the second derivative has on the function value only comes into play in the subsequent step through the first derivative. With Heun2, the first derivative is adjusted by the second derivative on the same step before being used to calculate a preliminary nextstep, which goes into another round of averaging. Was this adjustment significant? We went back and introduced this second derivative adjustment to the Euler's method, renaming it Euler2, and took it away from Heun2, renaming it Heun1. With ~550 steps, As seen in Figure 96, Euler2 showed trends of decreasing amplitude, although about 1/3 of it still remains at 36 second. As for Heun1, its solutions were slightly less accurate than those of Heun2. It appears that averaging between preliminary steps helps greatly with the convergence of solutions for the problem given, whereas adjusting lower derivatives on the bases of higher derivative values of the same step makes a smaller 89 difference. In fact, averaging between preliminary steps is what some of the MATLAB solver do, although more than once (four rounds for ode45, for example). Figure 96. Euler2 Shows Slight Improvement; Heun1 Shows Little Loss. ii. Future Considerations For numerical integration, using Excel versus MATLAB made little difference. We couldn't compare the different methods used due to the lack of experimental data and theoretical model, but the more data points made available, the more accurate any method becomes. We solved ODEs in MATLAB only but using different algorithms. It appears that averaging between preliminary steps helps a lot in reducing the amount of error of a numerical method. Solving the equations analytically would also have helped, serving as a point of reference for comparing the accuracies of the numerical solutions. 90 References Linear Algebraic Equations, North Carolina State University, College of Engineering, Department of Mechanical & Aerospace Engineering. <http://www.mae.ncsu.edu/homepages/silverberg/linear%20algebraic%20equations.doc>. How to Solve Systems, Math Warehouse. <http://www.mathwarehouse.com/algebra/linear_equation/systems-of-equation/>. Simultaneous Linear Equations, Stat Trek. <http://stattrek.com/matrix-algebra/linear-equations.aspx>. Define and solve a problem by using Solver, Microsoft Excel Excel 2007 Help. MATLAB Online Documentation, The Mathworks Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/for.html>. "Getting Started: What Is MATLAB?". MATLAB Help. The Mathworks Inc. "MATLAB Function Reference: clear". MATLAB Help. The Mathworks Inc. MATLAB Online Documentation, The Mathworks Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/>. "MATLAB Function Reference: inv". MATLAB Help. The Mathworks Inc. MATLAB Online Documentation, The Mathworks Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/for.html>. MATLAB Online Documentation, The Mathworks Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/break.html>. MATLAB Online Documentation, The Mathworks Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/continue.html>. "MATLAB Function Reference: function". MATLAB Help. The Mathworks Inc. "MATLAB Function Reference: subplot". MATLAB Help. The Mathworks Inc. Topics in Applied Math: Methods of Optimization, Andrej Cherkaev, <http://www.math.utah.edu/~cherk/teach/opt/course.html>. Optimization Definition, ME 419 Lecture Notes, Winter 2010, Dr. Tammy Chan. Chemical Engineering Analysis I, Vivek P. Utgikar, Ph.D., University of Idaho, Idaho Falls, <http://www.if.uidaho.edu/~vutgikar/Fall2006/Analysis/Lecture7.pdf>. 91 Optimization Techniques, University of Cambridge, <http://wwwdiva.eng.cam.ac.uk/energy/parksteaching/4m13/handout1.pdf>. Optimization Problem, ME 419 Lecture Notes, Winter 2010, Dr. Tammy Chan. "Display text or array". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/disp.html>. Accessed on 16 February, 2010. "Largest elements in array". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/max.html>. Accessed on 16 February, 2010. "Smallest elements in array". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/min.html>. Accessed on 16 February, 2010. "Mesh plots". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/mesh.html>. Accessed on 16 February, 2010. "Creating Mesh and Surface Plots :: Graphics (MATLAB®)". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/f3-40352.html>. Accessed on 16 February, 2010. "Generate <tt>X</tt> and <tt>Y</tt> arrays for 3-D plots". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html>. Accessed on 16 February, 2010. "Contour plot of matrix". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/contour.html>. Accessed on 16 February, 2010. "Quiver or velocity plot". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/quiver.html>. Accessed on 16 February, 2010. "Retain current graph in figure". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hold.html>. Accessed on 16 February, 2010. "Retain current graph in figure". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/gradient.html>. Accessed on 16 February, 2010. "Find minimum of unconstrained multivariable function using derivative-free method". MATLAB Documentation. The MathWorks, Inc. 92 <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fminsearch.html>. Accessed on 16 February, 2010. "Execute statements if condition is true". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/if.html>. Accessed on 16 February, 2010. "Declare global variables". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/global.html>. Accessed on 16 February, 2010. "About Solver - Excel". Microsoft Office Online. Microsoft Corporation. <http://office.microsoft.com/enus/excel/HP051983681033.aspx>. Accessed on 16 February, 2010. Notes on Differential Equations, Robert E. Terrell, <http://www.math.cornell.edu/~bterrell/dn.pdf>. Numerical Differentiation and Integration, ME 419 Presentation Notes, Winter 2010, Dr. Tammy Chan. Simpson’s 1/3 Rule of Integration, Autar Kaw, <http://numericalmethods.eng.usf.edu/mws/gen/07int/mws_gen_int_txt_simpson13.pdf>. Simpson’s 3/8 Rule, Abramowitz, M. and Stegun, I. A. < http://mathworld.wolfram.com/Simpsons38Rule.html>. Ordinary differential equation <http://www.answers.com/topic/ordinary-differential-equation>. ODEsPar2, ME 419 Presentation Notes, Winter 2010, Dr. Tammy Chan. "1-D data interpolation (table look up)". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/interp1.html>. Accessed on 9 March, 2010. "Evaluate piecewise polynomial". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ppval.html>. Accessed on 9 March, 2010. "Ordinary Differential Equations :: Calculus". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-662913.html>. Accessed on 9 March, 2010. "Solve initial value problems for ordinary differential equations". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/ ref/ode45.html>. Accessed on 9 March, 2010. 93 "Function Handles :: Classes (Data Types)". MATLAB Documentation. The MathWorks, Inc. <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f2-38133.html>. Accessed on 9 March, 2010. "The Trapezoidal Rule". <http://www.mathcs.emory.edu/ccs/ccs215/integral/node3.html>. 94 Index 3-D View .......................................... 6, 55, 56 extrema ............................................... 53, 54 analytically ..................................... 27, 29, 90 extremum ............................................ 54, 63 array.... 16, 17, 18, 19, 20, 21, 23, 42, 58, 59, 60, 61 figure ....................................... 40, 45, 46, 62 Array Editor ........................................... 5, 17 bicycle truss ............................................... 71 branch.................................................. 24, 67 chart .................................................... 29, 55 clabel ................................................... 61, 62 clear ............................................... 15, 45, 46 close ................................... 27, 33, 51, 85, 87 Command Window ................ 5, 6, 16, 20, 60 concatenate ............................................... 18 contour .................................... 55, 61, 62, 64 control ........................................... 16, 24, 87 declaring ................................................ 9, 22 delete......................................................... 15 derivative ........................... 31, 32, 54, 81, 89 differential equation.................................. 81 direct method ...................................... 54, 63 disp ............................................ 5, 16, 17, 21 element ................................... 19, 20, 21, 42 elimination......................... 36, 37, 41, 47, 52 Euler........................................... 6, 81, 87, 89 Fill .................................................... 5, 13, 14 fminsearch......... 6, 59, 60, 63, 64, 67, 68, 71 for 5, 6, 7, 8, 9, 15, 16, 18, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 46, 47, 48, 49, 51, 52, 53, 54, 55, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 73, 74, 75, 76, 77, 78, 79, 81, 83, 84, 85, 86, 87, 89, 90 formula .11, 14, 27, 31, 32, 39, 58, 72, 73, 84 function .... 11, 15, 18, 22, 23, 27, 31, 32, 42, 43, 45, 53, 54, 58, 59, 61, 63, 64, 66, 67, 68, 73, 76, 77, 80, 81, 83, 84, 85, 89 Gaussian ........................................ 20, 35, 42 Gaussian elimination ..................... 20, 35, 42 global ............................................. 22, 23, 53 gradient ............................. 53, 58, 59, 63, 64 gradient method ................................. 53, 63 graphing .................................. 33, 34, 60, 71 Heun .................................... 6, 81, 82, 87, 89 hold.................................... 12, 25, 41, 61, 62 if 5, 11, 14, 16, 18, 19, 24, 25, 31, 34, 41, 42, 54, 55, 59, 60, 61, 67, 68, 71, 76 indeterminate structure...................... 49, 52 interp1 ............................................. 6, 75, 76 95 interpolant ........................................... 80, 84 Newton-Raphson .......... 8, 27, 29, 31, 32, 33 interpolation .............................................. 76 non-stiff ..................................................... 84 inv .............................................................. 42 numerical integration.................... 72, 80, 90 inverse ............. 35, 36, 41, 42, 46, 48, 49, 52 ODE.............................. 6, 7, 8, 84, 85, 86, 87 iteration ............................................... 67, 69 ODE solver ................................................. 85 legend ........................................................ 56 ode113....................................................... 84 linear algebra ............... 34, 46, 47, 48, 49, 51 ode15i.................................................. 84, 85 linear equation .............................. 34, 35, 39 ode15s ........................................... 84, 85, 87 local ......................................... 53, 54, 59, 68 ode23................................................... 84, 85 loop .................................... 24, 49, 51, 66, 76 ode23s ................................................. 84, 87 mass-spring.......................... 5, 37, 41, 42, 51 ode23t ........................................... 84, 85, 87 matrix . 17, 18, 20, 35, 36, 37, 40, 41, 46, 48, 49, 51, 54, 59 ode23tb ............................... 7, 84, 85, 87, 88 matrix inverse ............................................ 37 maxima .......................................... 53, 63, 64 maximum ........................... 21, 54, 59, 67, 68 mesh .................................................... 60, 61 ode45............................. 7, 84, 85, 87, 88, 90 optimization ............................ 53, 59, 67, 71 ordinary differential equation............. 81, 84 partial derivative ....................................... 54 meshc................................................... 60, 61 plot ....5, 6, 25, 27, 29, 42, 43, 44, 45, 46, 55, 61, 62, 64 meshgrid .............................................. 59, 61 ppval ................................................ 6, 75, 76 meshz............................................. 60, 61, 62 quad .................................................... 77, 78 M-file ......................................................... 21 quiver................................................... 61, 62 minima ..................................... 53, 63, 65, 66 remove ...................................................... 15 minimum ............... 21, 54, 59, 63, 65, 67, 68 root-finding ............................................... 53 minverse .............................................. 40, 41 Runge-Kutta .............................. 6, 81, 82, 84 mmult .................................................. 40, 41 select ................................. 11, 12, 14, 41, 55 96 sensitivity ............................................. 69, 71 trapezoid rule ................................ 76, 77, 80 Solver .. 5, 6, 7, 39, 40, 47, 51, 52, 57, 58, 63, 65, 67, 68, 69, 71, 87 trapz .................................................... 77, 78 Solver Parameters ..................................... 58 van der Waals ............................ 8, 28, 32, 33 spreadsheet ......................................... 11, 52 variable 15, 16, 17, 18, 21, 22, 23, 41, 54, 60, 76, 81, 84, 85 stiff ............................................................. 84 work problem ............................................ 76 subplot ........................... 5, 25, 43, 44, 45, 46 surface chart .............................................. 55 tolerance.............................................. 59, 68 97