Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Excel Fundamentals

Similar presentations


Presentation on theme: "Chapter 2 Excel Fundamentals"— Presentation transcript:

1 Chapter 2 Excel Fundamentals
Introduction to Excel Chapter 2 Excel Fundamentals Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

2 The Excel 2007 Interface Office Button
Engineering Computation: An Introduction Using MATLAB and Excel

3 Features of the Excel 2007 Interface
The Office Button: This button is contained in all Microsoft Office 2007 products. Clicking on the Office Button in Excel opens up a menu box where you can perform tasks such as creating, opening, saving, printing, and ing a spreadsheet. The Office Button also contains a link for setting custom options or adding additional features to a spreadsheet Engineering Computation: An Introduction Using MATLAB and Excel

4 Features of the Excel 2007 Interface
The Quick Access Toolbar: This is where you can open a new or existing spreadsheet, and save, print, and a spreadsheet. It also contains the “undo” and “re-do” tools. The Title Window: The title of the Excel spreadsheet appears in this window. Knowing the title can be convenient when simultaneously working with several spreadsheets. Engineering Computation: An Introduction Using MATLAB and Excel

5 Features of the Excel 2007 Interface
The Ribbon: The main toolbar where most of the commands required to complete the tasks to create and edit the spreadsheet reside. Commands are tabulated by logical groups. The most commonly accessed commands are under the “Home” tab. The tools available in the Ribbon depend on the activity that is currently being worked on, so the tabs change as activities change. Within each tab, tools are grouped by category with the most commonly used tools displayed. Engineering Computation: An Introduction Using MATLAB and Excel

6 Features of the Excel 2007 Interface
The Workbook Window: This is the core of the spreadsheet where data and formulas reside. The Workbook Window is divided up into “cells”. Cells are addressed by their column and row. For example, the cell in the upper most left corner is in column “A” and row “1” and is addressed as cell A1. Cells are “activated” for entering data and editing by click on the cell. The active cell will have a bold box around it and its column and row will be highlighted. Engineering Computation: An Introduction Using MATLAB and Excel

7 Features of the Excel 2007 Interface
The Active Cell Address: This window displays the active cell or range of active cells. It is convenient to use when selecting or editing large ranges of data. The Formula Window: This window displays the formula or data entered into the active cell. Formulas and data can be entered or edited in this window. Engineering Computation: An Introduction Using MATLAB and Excel

8 The Excel 2007 Interface Tabs
Engineering Computation: An Introduction Using MATLAB and Excel

9 Features of the Excel 2007 Interface
The Worksheet Tabs: These tabs allow you to select between any of the worksheets that may be in your spreadsheet or workbook. Each sheet may contain independent calculations or may be linked via the data or formulas. By right-clicking on the worksheet name, you can move, copy, delete, hide, unhide, insert, or rename a worksheet. The arrow icons to the right of the worksheet tabs allow you to scroll through the tabs when there are too many to display. The icon to the right of the worksheet tabs allows you to insert a new blank worksheet. Engineering Computation: An Introduction Using MATLAB and Excel

10 Features of the Excel 2007 Interface
The Status Bar: This area is used to display information such as cell count, permission status, and macro recording status. The information displayed can be controlled by right-clicking on the status bar and selecting from the menu. The View Toolbar: This toolbar allows you to change the appearance of the workbook window. By changing from “Normal” to “Page Layout” mode you can see what the spreadsheet will look like when printed while still building or editing the spreadsheet. Engineering Computation: An Introduction Using MATLAB and Excel

11 Features of the Excel 2007 Interface
The Zoom Slider: This slider tool allows you to zoom out or in on the workbook window from 10% to 400%. It is very useful to zoom in when working on a laptop computer. Engineering Computation: An Introduction Using MATLAB and Excel

12 Chapter 2 Tutorials Section 2.2: Entering and Formatting Data
Section 2.3: Entering and Formatting Formulas Section 2.4: Using Built-in Functions Section 2.5: Performing Logical Tests using the IF Statement Section 2.6: Using Lookup Tables Section 2.7: Interpolating with Excel Engineering Computation: An Introduction Using MATLAB and Excel

13 2.2: Entering and Formatting Data
You will learn how to create and format a data table, as well as how to sort data Engineering Computation: An Introduction Using MATLAB and Excel

14 2.3: Entering and Formatting Formulas
In this tutorial, we will use Excel to perform repetitive calculations Engineering Computation: An Introduction Using MATLAB and Excel

15 2.4: Using Built-in Functions
Built-in functions are used to create this table of trig functions Engineering Computation: An Introduction Using MATLAB and Excel

16 2.5: Performing Logical Tests using the IF Statement
The IF statement allows for logic to be built into spreadsheet calculations. You will also learn how to apply Conditional Formatting commands. Engineering Computation: An Introduction Using MATLAB and Excel

17 2.6: Using Lookup Tables A lookup table allows tabulated data to be retrieved and used in calculations Engineering Computation: An Introduction Using MATLAB and Excel

18 2.7: Interpolating with Excel
A limitation of using lookup tables is that values that do not exactly match tabulated values are rounded down. For example, if we wanted to know the population of this town in 1956, the lookup command would round the year down to 1950 and report a population of 3012. A better estimate can be made by interpolating between the values for 1950 and 1960. Engineering Computation: An Introduction Using MATLAB and Excel

19 Introduction to MATLAB
Chapter 3 MATLAB Fundamentals Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

20 MATLAB INTERFACE Engineering Computation: An Introduction Using MATLAB and Excel

21 Command Window This is the command prompt – MATLAB commands are entered here Engineering Computation: An Introduction Using MATLAB and Excel

22 Command Window MATLAB commands enter at the prompts can be divided into two categories: Interactive commands, in which we directly enter the instructions into the command window, and File commands, in which we call up a series of commands stored in a MATLAB file The interactive mode is useful for quick computations, testing commands, or called up stored values More complex command sequences are stored in files for easy retrieval Engineering Computation: An Introduction Using MATLAB and Excel

23 Interactive Commands MATLAB can be used like a calculator, returning the answer for mathematical expressions: Note that MATLAB rounded the answer of the second calculation to 5 digits Engineering Computation: An Introduction Using MATLAB and Excel

24 Number Format By default, MATLAB uses a “short” format to display results. Entering the command format long causes all stored digits to be displayed: The command format short switches the output back to the default format More specific formats can be specified, but the default (short) format is sufficient for most calculations Engineering Computation: An Introduction Using MATLAB and Excel

25 Variables In the previous examples, the answer was stored in MATLAB with the variable name ans Often, we want to store our input and output values with our own variable names Let’s calculate the volume of a sphere. We will call the diameter of the sphere dia: Engineering Computation: An Introduction Using MATLAB and Excel

26 Variables When the expression is entered, the value of the variable is echoed to the screen: Note that here the “=“ sign is called an assignment operator The variable (dia) is assigned a value of 3 Engineering Computation: An Introduction Using MATLAB and Excel

27 Variables Now let’s assign a new variable Vol to the value calculated from the volume formula: Again, the variable’s value is printed to the screen Engineering Computation: An Introduction Using MATLAB and Excel

28 Workspace Window The Workspace Window shows all currently assigned variables, and their current values Note the columns for Min and Max: MATLAB is especially good for working with arrays, and treats a scalar as a 1 X 1 array Engineering Computation: An Introduction Using MATLAB and Excel

29 Command History Window
Your most recent entries to the Command Window are stored in the Command History Window, making it easy to retrace your steps Engineering Computation: An Introduction Using MATLAB and Excel

30 Changing a Variable Let’s change the value of the diameter of the sphere to 6 inches: Note that the value of Vol has not changed. Unlike a spreadsheet, where all cells containing formulas update automatically, in a programming language the variables are not reassigned unless we issue instructions to reassign them Engineering Computation: An Introduction Using MATLAB and Excel

31 Updating the Volume We could re-enter the formula for Vol, but here is a handy shortcut: From the command prompt, clicking the up arrow key allows you to scroll through the most recent entries. Two clicks of the key displays the assignment of Vol, and pressing Enter reassigns its value. Engineering Computation: An Introduction Using MATLAB and Excel

32 Suppressing Screen Display
At the end of a command, adding a semicolon causes the display to the screen to be skipped: Semi-colons are entered at the ends of most lines in MATLAB files, since we usually don’t want intermediate results displayed to the screen Engineering Computation: An Introduction Using MATLAB and Excel

33 Displaying Variable Values
Entering a variable name at the command prompt displays its value to the screen: Engineering Computation: An Introduction Using MATLAB and Excel

34 Variable Names MATLAB variable name are case sensitive! This is very important to remember. Suppose we enter the volume formula as: We get an error, since MATLAB does not recognize Dia. If fact, we could assign different variables the names dia, DIA, Dia, etc., and MATLAB would treat them as unrelated variables Engineering Computation: An Introduction Using MATLAB and Excel

35 Clearing Variables To clear the value of a variable from memory, use the “clear” command: To clear all values, use “clear all” Clearing variables is a good idea at the beginning of programs to ensure that results from previous calculations are not used accidentally (especially with arrays - more on this later) Engineering Computation: An Introduction Using MATLAB and Excel

36 Hierarchy of Operations
Note that our equation for volume required parentheses only around “dia/2”: The exponent operation is done first. Therefore, without the parentheses, the number 2 would be cubed first. MATLAB, like Excel and other computation software, performs calculations in this order: exponentials; multiplication/division; addition/subtraction Engineering Computation: An Introduction Using MATLAB and Excel

37 Formulas in MATLAB Adding parentheses, even when not required, can often help you to organize formulas Spaces are ignored, and can also be used to make formulas more readable Engineering Computation: An Introduction Using MATLAB and Excel

38 Functions in MATLAB There are many built-in functions in MATLAB. As an example, consider sin: The value in parentheses is the argument of the function; many functions required multiple arguments, separated by commas Engineering Computation: An Introduction Using MATLAB and Excel

39 Help With Functions To learn more about a function, type “help” followed by the function name: From the “see also” section, we discover that there is a function called sind, which finds the sine of an angle that is input in degrees rather than radians Engineering Computation: An Introduction Using MATLAB and Excel

40 More Help You can type “help” at the command prompt to call up a menu of help topics Also, clicking the Help button opens a window where you can browse topics or search for particular keywords Engineering Computation: An Introduction Using MATLAB and Excel

41 MATLAB Files The interactive mode is good for quick calculations, but frequently used and/or complex algorithms are stored in files MATLAB uses a file extension of .m, and MATLAB files are often called “m-files” Before getting started with m-files, it is important to consider the locations where your files will be stored Engineering Computation: An Introduction Using MATLAB and Excel

42 Current Directory At the top of the screen is the name of the current directory, where by default your new m-files will be stored. A list of MATLAB files in the current directory can be displayed by clicking the “Current Directory” tab (this window can be toggled between the Workspace and Current Directory) Engineering Computation: An Introduction Using MATLAB and Excel

43 Current Directory You may want to store your MATLAB files for each class or project in a specific folder If so, create the directory in Windows and then browse to it from the MATLAB interface to set it as the current directory Engineering Computation: An Introduction Using MATLAB and Excel

44 Path Files that you create in the new folder will run as long as that folder is set as the current directory in MATLAB However, if another folder is set as the current directory, files from the folder that you just created will not run unless its address is added to the MATLAB path The path is a list of locations that MATLAB searches to find files Engineering Computation: An Introduction Using MATLAB and Excel

45 Path When you enter a command at the prompt, MATLAB looks for a file matching the command name, beginning with the first location in the path. To add you new folder to the Path, select File: Set Path… Engineering Computation: An Introduction Using MATLAB and Excel

46 Path Select Add Folder… Browse to your desired folder and click OK…
Engineering Computation: An Introduction Using MATLAB and Excel

47 Path Click Save and Close. Note that your new folder is now the first location searched by MATLAB Engineering Computation: An Introduction Using MATLAB and Excel

48 M-File Example Consider our sphere example. Let’s find the weight of the sphere by calculating the volume, and then multiplying by the specific weight of the sphere’s material Since we plan to repeat this calculation repeatedly, we will write the formulas in an M-File Engineering Computation: An Introduction Using MATLAB and Excel

49 m-file Example We open the m-file Editor by clicking on this icon:
In the Editor, the lines are automatically numbered. This is very helpful in debugging Note that we have left a semi-colon off the second line, so that the weight will be printed to the screen Engineering Computation: An Introduction Using MATLAB and Excel

50 m-file Example The m-file is saved to the Current Directory, with the name “WtSphere.m” (the .m is added automatically) Engineering Computation: An Introduction Using MATLAB and Excel

51 m-file Example After assigning values to the diameter dia and the specific weight SpWt, typing the name of the file executes it: Engineering Computation: An Introduction Using MATLAB and Excel

52 Adding Comments Text following a % sign in a m-file is added to document the program. Adding comments is important for being able to comprehend and debug a program Engineering Computation: An Introduction Using MATLAB and Excel

53 Context-Specific Help
The MATLAB Editor often displays help when it detects possible errors. In this case, we meant to leave off the semicolon, so we can ignore the message Engineering Computation: An Introduction Using MATLAB and Excel

54 MATLAB Functions In addition to the built-in functions of MATLAB, users can write their own functions Functions are m-files, with a special first line: For our sphere, the output variable will be WT, the weight. The function name will be WtSphere, and the input variables will be the dia and SpWt Therefore, the first line will be: function Wt = WtSphere(dia,SpWt) Engineering Computation: An Introduction Using MATLAB and Excel

55 Function Example Here is the rest of the function file:
Note that we added a semicolon to the last line; the output variable (WT) will be printed to the screen when we execute the function Engineering Computation: An Introduction Using MATLAB and Excel

56 Function Example From the command prompt, when we call for the function, we must enter the arguments of dia and SpWt: The comments immediately following the first line are displayed when we ask for help with this function: Engineering Computation: An Introduction Using MATLAB and Excel

57 Why Use Functions? At first glance, it might appear that the function is exactly the same as the M-File, with only an extra line added. So why use the function? When we called the first M-file, we defined the diameter and specific weight before we called the M-file. In other words, variables stored in memory were passed into the M-file For example, suppose we clear all the variables before running the function: Engineering Computation: An Introduction Using MATLAB and Excel

58 Why Use Functions? We note that dia and SpWt, variables used within the function, are not stored in memory. Only the temporary variable ans is stored: With a function, only the arguments are passed into the file, and only the outputs are passed out. This means that in a long program, we don’t have to worry about overwriting previously assigned variables. This makes functions more flexible for including in more lengthy algorithms. Engineering Computation: An Introduction Using MATLAB and Excel

59 Flow Charts, Loop Structures
Chapter 4 MATLAB Programming Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

60 Flowcharts Flowcharts are diagrams that illustrate the paths followed in a sequence of computations Flowcharts are a great tool for planning complex algorithms Flowcharts are also very useful for documenting and explaining an algorithm, even relatively simple ones For many of the simple programs we will write, drawing a flowchart may seem to be unnecessary, but learning to create and read flow charts is a valuable skill Engineering Computation: An Introduction Using MATLAB and Excel

61 Example Flowchart In this example, many subroutines are used
Often, a complex program is organized into a series of subroutines Notice the decisions points (diamonds) and loops – several subroutines are repeated many times Engineering Computation: An Introduction Using MATLAB and Excel

62 Flowcharts Flowcharts are often used to illustrate process sequences in manufacturing operations and decision-making sequences in management Consider the flowchart of a company’s product design process: Engineering Computation: An Introduction Using MATLAB and Excel

63 Typical Flowchart Symbols
These symbols are not always used, but the diamond-shaped Decision Point can be considered a universal standard Engineering Computation: An Introduction Using MATLAB and Excel

64 The for Loop in MATLAB Also called a do loop in other languages
Used when you want the calculations to be performed a defined number of times In this example, the calculations are performed 10 times Engineering Computation: An Introduction Using MATLAB and Excel

65 The for Loop in MATLAB In MATLAB, a for loop begins with the statement indicating how many times the statements in the loop will be executed A counter is defined within this statement Examples: for k = 1:100 (counter = k, the loop will be executed 100 times) for i = 1:2:7 (counter = i, the counter will be incremented by a value of 2 each time until its value reaches 7. Therefore, the loop will be executed 4 times (i = 1,3,5, and 7) Engineering Computation: An Introduction Using MATLAB and Excel

66 The for Loop in MATLAB The loop ends with an end statement
In M-files, the MATLAB editor will automatically indent text between the for and end statements: Can you determine what the variable x will be after running this M-file? Engineering Computation: An Introduction Using MATLAB and Excel

67 for Loop Example The first time through the loop, j = 1
Because of the single value in parentheses, x will be a one-dimensional array x(1) will be set equal to 5*1 = 5 The second time through the loop, j = 2 x(2) will be set equal to 5*2 = 10 This will be repeated until j = 10 and x(10) = 50 Engineering Computation: An Introduction Using MATLAB and Excel

68 for Loop Example x will be a one-dimensional array (a row matrix) with 10 elements: Engineering Computation: An Introduction Using MATLAB and Excel

69 Condensed Form of for Loop Flowchart
Note the use of the connector symbol where paths join Good practice to add connectors to flowcharts of MATLAB programs: a connector corresponds to an end statement for m = 1:10 (Calculations) Engineering Computation: An Introduction Using MATLAB and Excel

70 for Loop in Interactive Mode
Loop commands can be entered directly from the command prompt The calculations are not performed until the end statement is entered Engineering Computation: An Introduction Using MATLAB and Excel

71 for Loop in Interactive Mode
Remember that if you leave off the semi-colon, the results of the calculations will be written to the screen in every loop: Engineering Computation: An Introduction Using MATLAB and Excel

72 for Loop Examples What result will be output to the screen in each of the following examples? y = 0; for k = 1:5 y = y + k; end y Engineering Computation: An Introduction Using MATLAB and Excel

73 for Loop Examples y = 0; for k = 2:2:8 y = y + k; end y
Engineering Computation: An Introduction Using MATLAB and Excel

74 for Loop Examples for k = 1:5 y(k)=k^2; end y
Engineering Computation: An Introduction Using MATLAB and Excel

75 for Loop Examples for j = 1:3 for k = 1:3 T(j,k) = j*k; end T
Engineering Computation: An Introduction Using MATLAB and Excel

76 for Loop Example Consider this equation:
Plot this equation for values of x from -10 to 10 We will use a for loop to calculate and store x and y values in one-dimensional arrays Engineering Computation: An Introduction Using MATLAB and Excel

77 for Loop Example for i = 1:21 x(i) = -10 +(i-1); y(i) = 2^(0.4*x(i)) + 5; end After running these lines of code, two one-dimensional arrays, x and y, have been created, each with 21 elements Engineering Computation: An Introduction Using MATLAB and Excel

78 Plot Command The stored arrays can be plotted with the command:
plot(x,y) Any two one-dimensional arrays can be plotted, as long as they are exactly the same size The plot will be created in a new window We will learn how to format MATLAB plots later Engineering Computation: An Introduction Using MATLAB and Excel

79 for and while Loops in MATLAB
A for loop will be executed a fixed number of times A while loop will continue to be repeated until some condition is satisfied Examples: Consider an amount of money deposited in an interest-bearing account If we want to calculate the value in the account after 10 years, then we would use a for loop If we want to determine how long it will take until the account reaches $100,000, then we would use a while loop Engineering Computation: An Introduction Using MATLAB and Excel

80 Flow Chart of while Loop
The first line of this loop is: while (condition) Last line is: end (calculations) Condition true? Yes No Engineering Computation: An Introduction Using MATLAB and Excel

81 Condensed Form of while Loop Flowchart
while [condition] (Calculations) Engineering Computation: An Introduction Using MATLAB and Excel

82 Example Consider this loop: How many times will the loop be executed?
k = 0; while k < 10 k = k + 2 end How many times will the loop be executed? Initially, k = 0, so the loop is entered Pass #1: k = 2, so execution continues Pass #2: k = 4, so execution continues Pass #3: k = 6, so execution continues Pass #4: k = 8, so execution continues Pass #5, k = 10, so k is not less than 10 and execution ends Engineering Computation: An Introduction Using MATLAB and Excel

83 while Example Suppose you borrow $10,000 at an interest rate of 6%, compounded monthly. Therefore, each month, the amount owed increases by 0.5% (6% divided by 12) and decreases by the amount of the monthly payment that you make How many months will it take to completely pay back the loan, if the monthly payment is $500 $200 $100 Engineering Computation: An Introduction Using MATLAB and Excel

84 Flow Chart of Example Define Payment P Balance B = 10,000 Months m = 0
while B > 0 Output m, B B = B*(1.005) B = B – P m = m + 1 Engineering Computation: An Introduction Using MATLAB and Excel

85 m-File Note the use of the input command: P is assigned the value entered at the prompt given in single quotes Engineering Computation: An Introduction Using MATLAB and Excel

86 Results Payment = $500: The loan would be repaid in 22 months
After the 22nd payment, the balance of $437 would be returned to the borrower Engineering Computation: An Introduction Using MATLAB and Excel

87 Results Payment = $200 Payment = $100
Engineering Computation: An Introduction Using MATLAB and Excel

88 Results Try Payment = $45:
The calculations will continue until you press ctrl+C to stop execution Engineering Computation: An Introduction Using MATLAB and Excel

89 Results Check m and B after stopping the calculations:
After making payments for more than 1,000,000 years, you owe more money than MATLAB can calculate. This won’t look good on your credit report! Engineering Computation: An Introduction Using MATLAB and Excel

90 Infinite Loops When using a while loop, there is a danger of encountering an infinite loop Since termination of the loop is dependent upon achieving some condition (in this case, a balance of less than or equal to zero), it is possible that the condition will never be reached, and therefore the looping will continue endlessly In our example, the interest after the first month was $50 (1/2% of $10,000). If the payment was less than $50, then the balance increased every month Engineering Computation: An Introduction Using MATLAB and Excel

91 Practice What are the values of A and m after execution of these MATLAB commands: m = 0; A = 20; while A <= 50 A = A + 5; m = m + 1; end A m Engineering Computation: An Introduction Using MATLAB and Excel

92 Practice What are the values of A and m after execution of these MATLAB commands: m = 0; A = 100; while A > 15 A = A/2; m = m + 1; end A m Engineering Computation: An Introduction Using MATLAB and Excel

93 Practice What are the values of A and m after execution of these MATLAB commands: m = 0; A = 10; while A > 0 A = sqrt(A); m = m + 1; end A m Infinite Loop: the square root will never reach zero Engineering Computation: An Introduction Using MATLAB and Excel

94 Chapter 4 MATLAB Programming
Logical Structures Chapter 4 MATLAB Programming Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

95 Logical if Statements We previously examined if statements in Excel:
IF(condition, value if true, value if false) Since there are different values corresponding to true and false conditions, this type of logic is termed if-else MATLAB has several types of if constructs, beginning with the most basic – a simple if statement Engineering Computation: An Introduction Using MATLAB and Excel

96 if Statement The simple if statement specifies that a command or group of commands will be executed only if a condition exists If the condition does not exist, then the command(s) are simply bypassed, and the execution of the program continues All if statements must have an end statement as well Engineering Computation: An Introduction Using MATLAB and Excel

97 Example Let’s consider the example of grades again
With a if statement, we can mark a passing grade: Note that nothing is printed if the grade is not passing g = input( 'Enter numerical grade '); if g >= 60 grade = 'P' end Engineering Computation: An Introduction Using MATLAB and Excel

98 Flowchart Engineering Computation: An Introduction Using MATLAB and Excel

99 Example >> Grades Enter numerical grade 75 grade = P
Engineering Computation: An Introduction Using MATLAB and Excel

100 if-else Statement This form is similar to the Excel IF statement in that two alternative paths are presented If the condition is true, then one set of commands is executed. If the condition is not true (else), then another set of commands is executed The same result can be achieved by “stacking” simple if statements, but this form is more compact Also, it guarantees that one of the alternative paths is followed Engineering Computation: An Introduction Using MATLAB and Excel

101 Example Adding to the previous commands, we can designate a grade as either passing or failing Note that one of the two options must be chosen g = input( 'Enter numerical grade '); if g >= 60 grade = 'P' else grade = 'F' end Engineering Computation: An Introduction Using MATLAB and Excel

102 Flowchart Note that one of the output paths must be followed
Engineering Computation: An Introduction Using MATLAB and Excel

103 Example >> Grades Enter numerical grade 75 grade = P
F >> Engineering Computation: An Introduction Using MATLAB and Excel

104 if-elseif Statement This structure allows for more than two paths to be considered More compact structure than nested if statements As soon as a condition is satisfied, then the flow of calculations proceeds to the end statement Engineering Computation: An Introduction Using MATLAB and Excel

105 Example Grades example modified to report letter grades:
g = input( 'Enter numerical grade '); if g >= 90 grade = 'A' elseif g >= 80 grade = 'B' elseif g >= 70 grade = 'C' elseif g >= 60 grade = 'D' else grade = 'F' end Engineering Computation: An Introduction Using MATLAB and Excel

106 Flowchart Engineering Computation: An Introduction Using MATLAB and Excel

107 Example >> Grades Enter numerical grade 85 grade = B
F Engineering Computation: An Introduction Using MATLAB and Excel

108 Summary if statement: execute a command or set of commands if a condition is true, otherwise skip the commands if-else statement: execute one set of commands if a condition is true, execute a different set of commands if the condition is false if-elseif-else: allows the checking of multiple conditions Engineering Computation: An Introduction Using MATLAB and Excel

109 Combining Loops and Logic
Chapter 4 MATLAB Programming Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

110 Combining Loops and Logic
Complex programs usually contain a both loops and logical statements to control the sequence of calculations As an example, let’s consider this example: We want to create an identity matrix (a square array with all ones as diagonal elements, zeros as off-diagonal elements) for a given size. For size = 3, our matrix would be: Engineering Computation: An Introduction Using MATLAB and Excel

111 Example There is a built-in MATLAB command “eye” that creates an identity matrix, but we will ignore that for this example We will call the matrix A, so we need to define each element A(m,n) where m and n both range from 1 to the specified size This will require two nested for loops For each element, a conditional statement is required: if m = n, then A(m,n) = 1, else A(m,n) = 0 Engineering Computation: An Introduction Using MATLAB and Excel

112 Example Can you de-scramble these lines of code to create an identity matrix and print it to the screen? A(m,n) = 0; for m = 1:Size end Size = 10; A A(m,n) = 1; else if m == n for n = 1:Size Engineering Computation: An Introduction Using MATLAB and Excel

113 Flow Chart Engineering Computation: An Introduction Using MATLAB and Excel

114 Solution Size = 10; for m = 1:Size for n = 1: Size if m == n
A(m,n) = 1; else A(m,n) = 0; end A Engineering Computation: An Introduction Using MATLAB and Excel

115 Example Engineering Computation: An Introduction Using MATLAB and Excel

116 Example Let’s set the Size to 3 and repeat: No change! What happened?
Engineering Computation: An Introduction Using MATLAB and Excel

117 Example A was stored as a a 10 X 10 matrix in memory before the m-file was modified When the new file was executed, the elements of A up to (3,3) were overwritten; the rest were unchanged Good practice to clear your variables (especially arrays) at the beginning of an m-file: Engineering Computation: An Introduction Using MATLAB and Excel

118 Example Now it works: Engineering Computation: An Introduction Using MATLAB and Excel

119 Example (Example 4.2) In many textbook problems, a triangle is encountered: Note that the hypotenuse (5) is a perfect square: an integer that is the square root of another integer (25) Many calculations are made simple for this configuration: cosθ = 4/5; sinθ = 3/5, etc. θ 3 4 5

120 Problem Description Can we find the other perfect squares for integer side lengths x and y from 1 to 25? h = hypotenuse θ y x h Engineering Computation: An Introduction Using MATLAB and Excel

121 Program Planning We will need to use two nested loops, since we have two independent variables: x and y Things to consider: How will we identify perfect squares mathematically? Do we want to store the perfect squares that we find, and/or do we want to print them to the screen or a file? Do we want to count the number of perfect square combinations found? Engineering Computation: An Introduction Using MATLAB and Excel

122 Begin Flow Chart with Loop Statements
How do we determine if h is an integer? Consider the MATLAB function floor: >> help floor FLOOR Round towards minus infinity. FLOOR(X) rounds the elements of X to the nearest integers towards minus infinity. for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2) Engineering Computation: An Introduction Using MATLAB and Excel

123 Check for Perfect Square
We can compare h and floor(h) directly in an if statement: if h == floor(h) If this statement is true, then we will print the values of x, y, and h to the screen If it is false, then we will do nothing Engineering Computation: An Introduction Using MATLAB and Excel

124 Engineering Computation: An Introduction Using MATLAB and Excel

125 MATLAB Code for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2);
What type of conditional statement do we need? if if-else if-elseif Engineering Computation: An Introduction Using MATLAB and Excel

126 MATLAB Code A simple if statement works here – we either do the next steps or we skip them for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end Engineering Computation: An Introduction Using MATLAB and Excel

127 MATLAB Code Close both loops with end statements for x = 1:25
for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end Engineering Computation: An Introduction Using MATLAB and Excel

128 Results Save file as “PerSquares” and run: >> PerSquares x = 3
y = 4 h = 5 (Screen output continues for many lines) Engineering Computation: An Introduction Using MATLAB and Excel

129 Add Formatting to Output
for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) end More about the fprintf command later Engineering Computation: An Introduction Using MATLAB and Excel

130 Results >> PerSquares >> How would we add a counter to report the number of combinations found? How do we eliminate duplicates? (such as 3, 4, 5; 4, 3, 5) Engineering Computation: An Introduction Using MATLAB and Excel

131 Counter Added m = 0; for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel

132 Eliminating Duplicates
The first time though the x-loop, x = 1 and y = 1:25: x = 1 y = 1,2,3,4….25 The second time though the x-loop, x = 2 and y = 1:25: x = 2 But since we have already looked at the combination x = 1, y = 2, we do not want to look at x = 2, y = 1 Engineering Computation: An Introduction Using MATLAB and Excel

133 Eliminating Duplicates
If we start the y-loop at 2 when x = 2: x = 2 y = 2,3,4,5….25 And start the y-loop at 3 when x = 3: x = 3 y = 3,4,5,6….25 And similar for the other values of x, then we have eliminated duplicate combinations Engineering Computation: An Introduction Using MATLAB and Excel

134 y-Loop Adjusted m = 0; for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel

135 Results For you to think about:
>> PerSquares Combinations found = 11 >> For you to think about: How would we eliminate combinations that are multiples of other combinations? (Example: 6, 8, 10 is a multiple of 3, 4, 5 – forms a similar triangle) Engineering Computation: An Introduction Using MATLAB and Excel

136 The fprintf Command This command writes formatted output to the screen
The format of the command is: fprintf(fid, ’Text to be written, including conversion specifications for any variables to be printed’, variables) The file ID (fid) is omitted for output to the screen Conversion specifications are instructions for how the variables are to be formatted, inserted at the points where the variables are to be written Engineering Computation: An Introduction Using MATLAB and Excel

137 Conversion Specifications
Conversion specifications begin with a % symbol Next comes the number of digits and decimal places Last is designator of format type. Most common are: f = fixed number of decimal places E or e = exponential notation i = integer Engineering Computation: An Introduction Using MATLAB and Excel

138 Examples >> fprintf('Pi = %8.3f',pi) Pi = 3.142
Text to be written to the screen, including the conversion specification for the variable (pi) pi is output over 8 spaces, including 3 decimal places Engineering Computation: An Introduction Using MATLAB and Excel

139 Examples >> fprintf('Pi = %e',pi) Pi = 3.141593e+000
Note that the number of digits and the number of decimal places are optional pi is output in exponential notation, with the number of digits corresponding to the default “short” format Engineering Computation: An Introduction Using MATLAB and Excel

140 Examples >> fprintf('\nPi = %.4f\n',pi) Pi = 3.1416 >>
The characters \n within the output string start a new line pi is output to 4 decimal places Engineering Computation: An Introduction Using MATLAB and Excel

141 Examples >> m = 12; >> fprintf('\n\nThe value of m is %i\n\n',m) The value of m is 12 >> m is output as an integer Engineering Computation: An Introduction Using MATLAB and Excel

142 Writing to a File Before writing to a file, you must first open a file and assign it to “fid” (file ID): Example: fid = fopen('amtable','wt'); 'wt' indicates write access; text file format. If the file does not exist, it will be created. If it already exists, its contents will be overwritten 'at' instead of 'wt' indicates that an existing file will be appended – the new results will be added to the end of an existing file Engineering Computation: An Introduction Using MATLAB and Excel

143 Modifications to “PerSquares” File:
New file “output.txt” opened for write access m = 0; fid = fopen('output.txt','wt'); fprintf(fid,' x y h\n'); fprintf(fid,' === === ===\n'); for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf(fid,'%5i %5i %5i\n',x,y,h); m = m + 1; end fprintf('\n Combinations found = %i\n',m) Column headers written to file Integer triangles written to file Number of triangles found written to screen Engineering Computation: An Introduction Using MATLAB and Excel

144 Output The table is now printed to the file “output,” which can be opened in Word or Notepad, or imported into Excel Engineering Computation: An Introduction Using MATLAB and Excel

145 MATLAB Troubleshooting
Chapter 4 MATLAB Programming Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

146 Troubleshooting Examples
We want to plot this equation for time values from zero to 10 seconds: for k = 0:10 t = k; y = 200*exp(-3*t); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

147 Result This file will run, with the following plot produced:
Engineering Computation: An Introduction Using MATLAB and Excel

148 Problem The plot command creates a graph from two vectors
In this case, our variables to be plotted, t and y, are scalars Therefore, there is only a single point to be plotted Engineering Computation: An Introduction Using MATLAB and Excel

149 Troubleshooting Examples
Modified to store results in vectors Is this file OK? for k = 0:10 t(k) = k; y(k) = 200*exp(-3*t); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

150 Result Error message: Note that it is OK for the loop counter to begin at zero (for k = 0:10), but the array index cannot be zero Engineering Computation: An Introduction Using MATLAB and Excel

151 Troubleshooting Examples
Modified so that the array indices begin with one Is this file OK? for k = 1:10 t(k) = k; y(k) = 200*exp(-3*t); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

152 Result Error message What is this message telling us?
Engineering Computation: An Introduction Using MATLAB and Excel

153 Problem This message is harder to interpret, but relates to the fact that t has been assigned as an array, and is now being used as a scalar ARRAY SCALAR t(k) = k; y(k) = 200*exp(-3*t); Engineering Computation: An Introduction Using MATLAB and Excel

154 Troubleshooting Examples
Modified so that reference to t is written as an array Is this file OK? for k = 1:10 t(k) = k; y(k) = 200*exp(-3*t(k)); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

155 Result File runs; here is the plot
Note that the first point plotted is for t = 1 second, not t = 0 Engineering Computation: An Introduction Using MATLAB and Excel

156 Troubleshooting Examples
Modified so that time begins with zero. The for loop executes 11 times rather than 10 to include both endpoints Is this file OK? for k = 1:11 t(k) = k-1; y(k) = 200*exp(-3*t(k)); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

157 Result File runs; here is the plot Note y  0 at t = 2 seconds
We have now solved the problem as presented. Let’s now modify our solution so that the time domain is from 0 to 2 seconds, and include more points to produce a smooth curve Note y  0 at t = 2 seconds Engineering Computation: An Introduction Using MATLAB and Excel

158 Modifying Time Domain If we want to plot 101 points (for k = 1:101) for a time domain of zero to 2 seconds, what will the expression for t(k) be? for k = 1:101 t(k) = ? Engineering Computation: An Introduction Using MATLAB and Excel

159 Modifying Time Domain for k = 1:101 t(k) = ?
The interval between time steps will be (2 seconds) / (100 steps) = 0.02 seconds/step The first value of time t(1) = 0 = k-1 So t(k) = (k-1)*(0.02) Check: t(101) = 100*0.02 = 2 seconds  Engineering Computation: An Introduction Using MATLAB and Excel

160 Troubleshooting Examples
Is this file OK? for k = 1:101 t(k) = (k-1)*(0.02); y(k) = 200*exp(-3*t(k)); end plot (t,y) Engineering Computation: An Introduction Using MATLAB and Excel

161 Result File runs; here is the plot
Engineering Computation: An Introduction Using MATLAB and Excel

162 Troubleshooting Examples
Here is the m-file that we wrote earlier to create an identity matrix. Can you find three errors? Size = 5; for k = 1:Size for l = 1: size if k = l A(k,l) = 1; else A(k,l) = 0; end End A Engineering Computation: An Introduction Using MATLAB and Excel

163 Error #1 This is a common error: when comparing two values in the if statement, you must use a double equal sign (==) rather that a single equal sign, since that is the assignment operator Engineering Computation: An Introduction Using MATLAB and Excel

164 Error #2 The last end statement is not recognized because it is capitalized. Note that the Editor shows the other for, if, else, and end statements in blue Engineering Computation: An Introduction Using MATLAB and Excel

165 Error #3 We are still missing one end statement. Every loop and if statement must have an end statement. Add an end after line 7 (following if-else) Engineering Computation: An Introduction Using MATLAB and Excel

166 Indenting Helps Troubleshooting
Note the indenting that the Editor does automatically: Engineering Computation: An Introduction Using MATLAB and Excel

167 Error #4 In line 3, “size” is not recognized. Remember that MATLAB variables are case-sensitive. Change to “Size” Engineering Computation: An Introduction Using MATLAB and Excel

168 Now it Works Engineering Computation: An Introduction Using MATLAB and Excel

169 Troubleshooting MATLAB Files
Although MATLAB’s error messages can help you find problems, it is much more efficient to plan programs carefully and add comment lines to help you later Engineering Computation: An Introduction Using MATLAB and Excel

170 Types of Graphs, Plotting with Excel
Chapter 5 Plotting Data Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

171 Introduction Creating graphs is an important communications skill for all engineers and students Graphs can: Allow visualization of large data sets Show trends in data Show cause-and-effect relationships To begin, we will look at different types of graphs (note: graphs are called “Charts” in Excel, “Plots” in MATLAB) Engineering Computation: An Introduction Using MATLAB and Excel

172 XY (Scatter) Plots Most important type of graph used in engineering
An independent variable (x) is plotted on the horizontal axis, and a dependent variable (y) is plotted on the vertical axis We say that we are plotting “y versus x” Often, more than one dependent variable are plotted on the same axes. This allows comparisons to be made Engineering Computation: An Introduction Using MATLAB and Excel

173 An XY (Scatter) Graph Dependent Variable (y) Independent Variable (x)
Engineering Computation: An Introduction Using MATLAB and Excel

174 Two Curves on Same Axes Allow Comparisons
Engineering Computation: An Introduction Using MATLAB and Excel

175 Lines and Markers on XY Graphs
Equations should be plotted with smooth curves, without point markers – the points used to create the curve are not significant Measured data points are significant, and should be shown with markers (the name “scatter plot” comes from the scattered appearance of a large number of data points on a graph) Engineering Computation: An Introduction Using MATLAB and Excel

176 Measured Data Points Engineering Computation: An Introduction Using MATLAB and Excel

177 Lines and Markers on XY Graphs
With measured data, adding a line is almost always done. The line is typically: A theory curve, which shows how well the data points agree with theoretical values, or A fit line (called a trend line in Excel), which is a curve based on the values of the data points. We will explore curve-fitting later in this chapter. Engineering Computation: An Introduction Using MATLAB and Excel

178 Measured Data with Theory Curve
Engineering Computation: An Introduction Using MATLAB and Excel

179 Pie Charts Less typical than XY-charts in engineering
Not a particularly efficient chart – data can easily be shown in a table Easy to understand, can be effective when presenting to a non-technical audience Engineering Computation: An Introduction Using MATLAB and Excel

180 Pie Chart Engineering Computation: An Introduction Using MATLAB and Excel

181 Bar Graph Data is represented by side-by-side bars, with bar heights proportional to data values Excel nomenclature: “Bar chart” applies when bars are horizontal, “Column chart” applies when bars are vertical More common usage: “Bar graph” is used to describe either orientation Bar graphs allow easy side-by-side comparisons between data sets Engineering Computation: An Introduction Using MATLAB and Excel

182 Bar Graph Engineering Computation: An Introduction Using MATLAB and Excel

183 Bar Graph with Two Data Sets
Engineering Computation: An Introduction Using MATLAB and Excel

184 Histogram Special type of bar graph
Applied to continuous data sets that can be sorted into “bins” For example, if we ask students how much time they spent on a given assignment, we could group their answers into bins such as less than one hour, between one and two hours, between two and three hours, etc. When we create the bar graph, the bars should be as wide as the bins Engineering Computation: An Introduction Using MATLAB and Excel

185 Histogram Note that the bars touch each other – each bar spans the width of the bin Engineering Computation: An Introduction Using MATLAB and Excel

186 Pareto Diagram Often used in quality control
Used to present categorical data – for example, if we track the number of service visits to a car dealer, we might categorize them by the type of problem In the Pareto diagram, the categories are sorted by the number of data points in each, from high to low A bar graph shows the relative frequency of each category A line shows the cumulative percentage for each category Engineering Computation: An Introduction Using MATLAB and Excel

187 Pareto Diagram Line shows cumulative percentage. For example, first three categories account for almost 80% of all visits Bar heights show relative frequency of each type of problem Engineering Computation: An Introduction Using MATLAB and Excel

188 XY Graphing Tutorial Graph response of spring-mass-damper system
Before beginning this exercise, some background is helpful Engineering Computation: An Introduction Using MATLAB and Excel

189 Spring-Mass System This mass is hanging from a spring, at rest. The displacement, y, is zero at this position At time t = 0, the mass is pulled to the initial displacement yo and released The mass will then oscillate up and down Engineering Computation: An Introduction Using MATLAB and Excel

190 Spring-Mass System The time required for the mass to make one complete cycle is called the period of oscillation The inverse of the period is the natural frequency of the system, in units of cycles per time or radians per time. The natural frequency is a function of the spring stiffness and the mass Theoretically, the mass will continue to oscillate indefinitely, since there are no forces to stop it Engineering Computation: An Introduction Using MATLAB and Excel

191 Spring-Mass-Damper System
In reality, we know that the oscillations will get smaller with time, even if only due to internal forces in the spring The presence of a damper will cause the oscillations to get smaller at a much faster rate Examples of dampers: Shock absorbers on cars, storm door closers Engineering Computation: An Introduction Using MATLAB and Excel

192 Spring-Mass-Damper System
The damping coefficient is a measure of the effectiveness of the damper If the damping coefficient is less than one, we say the system is under damped, and will oscillate If the damping coefficient is one, then the system is critically damped and the mass will settle back to its original position without oscillating Engineering Computation: An Introduction Using MATLAB and Excel

193 Spring-Mass-Damper System
In future courses, you will learn to formulate and solve the differential equation defining the system’s response For the under damped system, the solution is: Engineering Computation: An Introduction Using MATLAB and Excel

194 Graphing Response Given values for natural frequency, damping coefficient, and initial displacement, graph displacement y versus time t What time steps should you use? What time domain should you use? Trial and error: Need small enough time steps to produce a smooth curve and pick up all oscillations. Need to pick a time domain sufficient to show response adequately Engineering Computation: An Introduction Using MATLAB and Excel

195 Graphing Response Time domain = 0 to 1 seconds
Can’t tell much – need to increase time Engineering Computation: An Introduction Using MATLAB and Excel

196 Graphing Response Time domain = 0 to 5 seconds
Much better – shows that period is about 1 second; oscilations have been mostly damped out by 5 seconds Now we need to make it look nice Engineering Computation: An Introduction Using MATLAB and Excel

197 Finished Graph Engineering Computation: An Introduction Using MATLAB and Excel

198 Curve Fitting, Good Graphing Practices
Chapter 5 Plotting Data Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

199 Curve Fitting Often, we have data points and we want to find an equation that “fits” the data Simplest equation is that of a straight line Engineering Computation: An Introduction Using MATLAB and Excel

200 Curve Fitting Example A spring is placed between two flat plates and force is slowly applied to the upper plate, causing the spring to compress. When the force reaches a pre-load value of 25 N, the location of the upper plate is recorded. As the upper plate continues to move, the distance that the top plate moves, d, and the force required to move the plate, F, are recorded. As soon as the upper plate has moved 10 mm, the test is ended. Engineering Computation: An Introduction Using MATLAB and Excel

201 Curve Fitting Example Data from the test is shown here. The slope of the load-displacement curve is called the spring constant. Engineering Computation: An Introduction Using MATLAB and Excel

202 Curve Fitting Example Data from a test – how do we find the slope?
We could draw in a line by hand and estimate its slope by estimating the coordinates of two points Engineering Computation: An Introduction Using MATLAB and Excel

203 Curve Fitting Example How do we find the line that best fits the data?
Find the equation of the line that minimizes the sum of the squares of the differences between the values predicted from the equation and the actual data values Why do we square the differences? Because we are interested in the magnitudes of the differences. If one point is above the line and other is below it, we don’t want these difference to cancel each other Engineering Computation: An Introduction Using MATLAB and Excel

204 Curve Fit Parameters In Excel, we can choose to have the equation of the best-fit line (the trendline) displayed in the form where m = the slope of the line and b = the intercept of the line with the y-axis Engineering Computation: An Introduction Using MATLAB and Excel

205 Equation of Trendline In this example, the slope of the line (the stiffness of the spring) equals 72.3 N/mm When the deflection (x) equals zero, the force (y) equals 23.1 pounds. This is consistent with our nominal pre-load of 25 pounds Engineering Computation: An Introduction Using MATLAB and Excel

206 Correlation Coefficient
The correlation coefficient (R2) is a measure of how well the trendline fits the data A value of one represents a perfect fit In our example, the line fit is very good Engineering Computation: An Introduction Using MATLAB and Excel

207 Curve Fitting Example Consider these five data points:
Engineering Computation: An Introduction Using MATLAB and Excel

208 Linear Curve Fit Poor Fit
Engineering Computation: An Introduction Using MATLAB and Excel

209 Try Second–Order Polynomial Fit
Better, but still not very good Engineering Computation: An Introduction Using MATLAB and Excel

210 Third-Order Polynomial Fit
Perfect Fit! These point were calculated from the equation: Engineering Computation: An Introduction Using MATLAB and Excel

211 Correlation Coefficient
A “good” fit to data is relative In the case of the spring example, the data should fit a mathematical model, and so an R2 value of close to one is expected For other cases, a much lower R2 value is expected Consider a comparison of final exam scores in a class vs. homework averages We would expect that students who do well on HW will generally do well on the final exam, but there will be exceptions Engineering Computation: An Introduction Using MATLAB and Excel

212 Exam vs. HW Example Note the presence of “outliers” – data points that don’t fit the trend However, there is clearly a trend in the data Engineering Computation: An Introduction Using MATLAB and Excel

213 Exponential and Power Equations
Consider this equation: Here is a graph of the equation: Engineering Computation: An Introduction Using MATLAB and Excel

214 Exponential Equation If we plot the ln(y) instead of y, then we have the equation of a straight line Engineering Computation: An Introduction Using MATLAB and Excel

215 Exponential Equation This plot is not particularly useful, since it requires us to read the ln of the dependent variable y, instead of y itself Engineering Computation: An Introduction Using MATLAB and Excel

216 Exponential Equation A better way is to display the y values on a logarithmic scale: Engineering Computation: An Introduction Using MATLAB and Excel

217 Exponential Equation We call this a semi-log plot since one of the axes is logarithmic Note that we have used a base-10 scale: remember that a logarithm can be converted to a logarithm of another base by multiplying by a constant: Therefore, the equation will produce a straight line on semi-log axes regardless of the base of the logarithmic scale. Base 10 normally used – easiest to read Logarithmic scales can be specified in Excel and MATLAB Engineering Computation: An Introduction Using MATLAB and Excel

218 Power Equation Consider the equation for the volume of a sphere: Plot:
Engineering Computation: An Introduction Using MATLAB and Excel

219 Power Equations If we plot the log(y) and log(x), then we have the equation of a straight line Engineering Computation: An Introduction Using MATLAB and Excel

220 Power Equations This is called a log-log plot, since both axes are logarithmic Engineering Computation: An Introduction Using MATLAB and Excel

221 In-Class Exercise (Problem 5.17)
Estimate the area of each quarter-circle by counting squares. For partial squares, estimate to 0.1 square Engineering Computation: An Introduction Using MATLAB and Excel

222 Example r = 4: 0.6 square 0.9 square 0.2 square 0.8 square 0.3 square
8 complete squares 0.9 square 0.6 square 0.2 square 0.8 square 0.3 square 0.7 square Total = 12.4 squares Therefore, area of complete circle = 49.6 squares Engineering Computation: An Introduction Using MATLAB and Excel

223 Example Plot area vs. radius
Curve fit to estimate equation for area as a function of radius How well does our estimate match the actual equation? Engineering Computation: An Introduction Using MATLAB and Excel

224 Good Graphing Practices
Graphs are an important tool for communicating information Following a few simple rules can greatly improve the quality of your graphs This is a bad graph! Engineering Computation: An Introduction Using MATLAB and Excel

225 Always Include a Title The title can be above the graph, or below (especially if a figure number is included) Engineering Computation: An Introduction Using MATLAB and Excel

226 Add Axis Labels, Including Units
Size of label font and number font should be large enough to be easily read Engineering Computation: An Introduction Using MATLAB and Excel

227 Background/Gridlines
The background should not be distracting – a plain white background is good Gridlines are very useful, but should allow the data curve(s) to stand out – gray gridlines are a good choice Engineering Computation: An Introduction Using MATLAB and Excel

228 Data Curves For equations, plot smooth curves with no data markers
With multiple curves, color is good, but remember that the graph may be reproduced in black and white Engineering Computation: An Introduction Using MATLAB and Excel

229 A Good Graph! Engineering Computation: An Introduction Using MATLAB and Excel

230 Plotting Data with MATLAB
Chapter 5 Plotting Data Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

231 MATLAB Plotting Commands
plot: Creates an XY graph from two arrays fplot: Creates an XY graph of a MATLAB function for a specified range of the independent variable Engineering Computation: An Introduction Using MATLAB and Excel

232 plot Command General form: plot(x,y) where x and y are two one-dimensional arrays of the same size If more than one curve is to be plotted, the additional x and y arrays are included in the command: plot(x1,y1,x2,y2) Another way to plot two curves on the same graph is to use the hold command: hold on plots the new data on the current graph hold off causes the next plot to be opened in a new window (this is the default – each plot command opens a new window) Engineering Computation: An Introduction Using MATLAB and Excel

233 fplot Command General form: fplot(‘function_name’,[ll ul])
where ll and ul = lower limit and upper limit, respectively, of the argument of the function Example: to plot the sin function for values of angles from 0 to 2π, fplot(‘sin’, [0 2*pi]) Engineering Computation: An Introduction Using MATLAB and Excel

234 Editing MATLAB Plots Interactive editing tools, similar to Excel’s, are available by selecting Edit Plot With editing activated, right-clicking most plot elements produces a menu of editing tools Engineering Computation: An Introduction Using MATLAB and Excel

235 Editing MATLAB Plots The Property Editor is another option for accessing interactive editing tools Engineering Computation: An Introduction Using MATLAB and Excel

236 Editing MATLAB Plots If a graph is to be produced repeatedly, then some editing commands can be added directly to the MATLAB code: Engineering Computation: An Introduction Using MATLAB and Excel

237 Editing MATLAB Plots One way to generate the MATLAB code for formatting is to edit the plot as desired manually, and then selecting “Show M-Code” from the right-click menu. Engineering Computation: An Introduction Using MATLAB and Excel

238 Editing MATLAB Plots A new m-file will be generated and opened in the Editor – desired lines can be copied and pasted into the m-file used to develop the graph data. Engineering Computation: An Introduction Using MATLAB and Excel

239 Chapter 6 Finding the Roots of Equations
The Bisection Method Chapter 6 Finding the Roots of Equations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

240 Finding Roots of Equations
In this chapter, we are examining equations with one independent variable. These equations may be linear or non-linear Non-linear equations may be polynomials or generally non-linear equations A root of the equation is simply a value of the independent variable that satisfies the equation Engineering Computation: An Introduction Using MATLAB and Excel

241 Classification of Equations
Linear: independent variable appears to the first power only, either alone or multiplied by a constant Nonlinear: Polynomial: independent variable appears raised to powers of positive integers only General non-linear: all other equations Engineering Computation: An Introduction Using MATLAB and Excel

242 Finding Roots of Equations
As with our method for solving simultaneous non-linear equations, we often set the equation to be equal to zero when the equation is satisfied Example: If we say that then when f(y) =0, the equation is satisfied Engineering Computation: An Introduction Using MATLAB and Excel

243 Solution Methods Linear: Easily solved analytically
Polynomials: Some can be solved analytically (such as by quadratic formula), but most will require numerical solution General non-linear: unless very simple, will require numerical solution Engineering Computation: An Introduction Using MATLAB and Excel

244 The Bisection Method In the bisection method, we start with an interval (initial low and high guesses) and halve its width until the interval is sufficiently small As long as the initial guesses are such that the function has opposite signs at the two ends of the interval, this method will converge to a solution Example: Consider the function Engineering Computation: An Introduction Using MATLAB and Excel

245 Bisection Method Example
Consider an initial interval of ylower = -10 to yupper = 10 Since the signs are opposite, we know that the method will converge to a root of the equation The value of the function at the midpoint of the interval is: Engineering Computation: An Introduction Using MATLAB and Excel

246 Bisection Method Example
The method can be better understood by looking at a graph of the function: Interval Engineering Computation: An Introduction Using MATLAB and Excel

247 Bisection Method Example
Now we eliminate half of the interval, keeping the half where the sign of f(midpoint) is opposite the sign of f(endpoint) In this case, since f(ymid) = -6 and f(yupper) = 64, we keep the upper half of the interval, since the function crosses zero in this interval Engineering Computation: An Introduction Using MATLAB and Excel

248 Bisection Method Example
Now we eliminate half of the interval, keeping the half where the sign of f(midpoint) is opposite the sign of f(endpoint) In this case, since f(ymid) = -6 and f(yupper) = 64, we keep the upper half of the interval, since the function crosses zero in this interval Engineering Computation: An Introduction Using MATLAB and Excel

249 Bisection Method Example
The interval has now been bisected, or halved: New Interval Engineering Computation: An Introduction Using MATLAB and Excel

250 Bisection Method Example
New interval: ylower = 0, yupper = 10, ymid = 5 Function values: Since f(ylower) and f(ymid) have opposite signs, the lower half of the interval is kept Engineering Computation: An Introduction Using MATLAB and Excel

251 Bisection Method Example
At each step, the difference between the high and low values of y is compared to 2*(allowable error) If the difference is greater, than the procedure continues Suppose we set the allowable error at As long as the width of the interval is greater than 0.001, we will continue to halve the interval When the width is less than 0.001, then the midpoint of the range becomes our answer Engineering Computation: An Introduction Using MATLAB and Excel

252 Bisection Method Example
Excel solution: Initial Guesses Evaluate function at lower and mid values. Is interval width narrow enough to stop? If signs are same (+ product), eliminate lower half of interval. Engineering Computation: An Introduction Using MATLAB and Excel

253 Bisection Method Example
Next iteration: Evaluate function at lower and mid values. New Interval (if statements based on product at the end of previous row) If signs are different (- product), eliminate upper half of interval. Is interval width narrow enough to stop? Engineering Computation: An Introduction Using MATLAB and Excel

254 Bisection Method Example
Continue until interval width < 2*error (16 iterations) Answer: y = 0.857 Engineering Computation: An Introduction Using MATLAB and Excel

255 Bisection Method Example
Or course, we know that the exact answer is 6/7 ( ) If we wanted our answer accurate to 5 decimal places, we could set the allowable error to This increases the number of iterations only from 16 to 22 – the halving process quickly reduces the interval to very small values Even if the initial guesses are set to -10,000 and 10000, only 32 iterations are required to get a solution accurate to 5 decimal places Engineering Computation: An Introduction Using MATLAB and Excel

256 Bisection Method Example - Polynomial
Now consider this example: Use the bisection method, with allowed error of Engineering Computation: An Introduction Using MATLAB and Excel

257 Bisection Method Example - Polynomial
If limits of -10 to 0 are selected, the solution converges to x = -2 Engineering Computation: An Introduction Using MATLAB and Excel

258 Bisection Method Example - Polynomial
If limits of 0 to 10 are selected, the solution converges to x = 4 Engineering Computation: An Introduction Using MATLAB and Excel

259 Bisection Method Example - Polynomial
If limits of -10 to 10 are selected, which root is found? In this case f(-10) and f(10) are both positive, and f(0) is negative Engineering Computation: An Introduction Using MATLAB and Excel

260 Bisection Method Example - Polynomial
Which half of the interval is kept? Depends on the algorithm used – in our example, if the function values for the lower limit and midpoint are of opposite signs, we keep the lower half of the interval Engineering Computation: An Introduction Using MATLAB and Excel

261 Bisection Method Example - Polynomial
Therefore, we converge to the negative root Engineering Computation: An Introduction Using MATLAB and Excel

262 In-Class Exercise Draw a flow chart of the algorithm used to find a root of an equation using the bisection method Write the MATLAB code to determine a root of within the interval x = 0 to 10 Engineering Computation: An Introduction Using MATLAB and Excel

263 Input lower and upper limits low and high
Define tolerance tol Input lower and upper limits low and high while high-low > 2*tol mid = (high+low)/2 Evaluate function at lower limit and midpoint: fl = f(low), fm = f(mid) Keep lower half of range: high = mid fl*fm > 0? Keep upper half of range: low = mid NO YES Display root (mid)

264 MATLAB Solution Consider defining the function
as a MATLAB function “fun1” This will allow our bisection program to be used on other functions without editing the program – only the MATLAB function needs to be modified Engineering Computation: An Introduction Using MATLAB and Excel

265 MATLAB Function Check values at x = 0 and x = 10:
function y = fun1(x) y = exp(x) - 15*x -10; Check values at x = 0 and x = 10: >> fun1(0) ans = -9 >> fun1(10) 2.1866e+004 Different signs, so a root exists within this range Engineering Computation: An Introduction Using MATLAB and Excel

266 Set tolerance to 0.00001; answer will be accurate to 5 decimal places
Engineering Computation: An Introduction Using MATLAB and Excel

267 Engineering Computation: An Introduction Using MATLAB and Excel

268 Engineering Computation: An Introduction Using MATLAB and Excel

269 Engineering Computation: An Introduction Using MATLAB and Excel

270 Engineering Computation: An Introduction Using MATLAB and Excel

271 Engineering Computation: An Introduction Using MATLAB and Excel

272 Engineering Computation: An Introduction Using MATLAB and Excel

273 Find Root >> bisect Enter the lower limit 0 Enter the upper limit 10 Root found: Engineering Computation: An Introduction Using MATLAB and Excel

274 What if No Root Exists? Try interval of 0 to 3: >> bisect
Enter the lower limit Enter the upper limit Root found: This value is not a root – we might want to add a check to see if the converged value is a root Engineering Computation: An Introduction Using MATLAB and Excel

275 Modified Code Add “solution tolerance” (usually looser than convergence tolerance): Add check at end of program: Engineering Computation: An Introduction Using MATLAB and Excel

276 Check Revised Code >> bisect Enter the lower limit 0 Enter the upper limit 3 No root found Engineering Computation: An Introduction Using MATLAB and Excel

277 Numerical Tools Of course, Excel and MATLAB have built-in tools for finding roots of equations However, the examples we have considered illustrate an important concept about non-linear solutions: Remember that there may be many roots to a non-linear equation. Even when specifying an interval to be searched, keep in mind that there may be multiple solutions (or no solution) within the interval. Engineering Computation: An Introduction Using MATLAB and Excel

278 Newton’s Method, Root Finding with MATLAB and Excel
Chapter 6 Finding the Roots of Equations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

279 Review: Classification of Equations
Linear: independent variable appears to the first power only, either alone or multiplied by a constant Nonlinear: Polynomial: independent variable appears raised to powers of positive integers only General non-linear: all other equations Engineering Computation: An Introduction Using MATLAB and Excel

280 Review: Solution Methods
Linear: Easily solved analytically Polynomials: Some can be solved analytically (such as by quadratic formula), but most will require numerical solution General non-linear: unless very simple, will require numerical solution Engineering Computation: An Introduction Using MATLAB and Excel

281 Review: The Bisection Method
In the bisection method, we start with an interval (initial low and high guesses) and halve its width until the interval is sufficiently small As long as the initial guesses are such that the function has opposite signs at the two ends of the interval, this method will converge to a solution Engineering Computation: An Introduction Using MATLAB and Excel

282 Newton’s Method Newton’s Method (also know as the Newton-Rapshon Method) is another widely-used algorithm for finding roots of equations In this method, the slope (derivative) of the function is calculated at the initial guess value and projected to the x-axis The corresponding x-value becomes the new guess value The steps are repeated until the answer is obtained to a specified tolerance Engineering Computation: An Introduction Using MATLAB and Excel

283 Newton’s Method y(xi) Tangent Line: Slope = y’(xi) Initial guess xi
Engineering Computation: An Introduction Using MATLAB and Excel

284 Newton’s Method New guess for x: xn = xi - y(xi)/y’(xi) y(xi) xi
Engineering Computation: An Introduction Using MATLAB and Excel

285 Newton’s Method Example
Find a root of this equation: The first derivative is: Initial guess value: x = 10 Engineering Computation: An Introduction Using MATLAB and Excel

286 Newton’s Method Example
For x = 10: This is the new value of x Engineering Computation: An Introduction Using MATLAB and Excel

287 Newton’s Method Example
y = 1350 y’ = 580 New x-value = Initial guess = 10 Engineering Computation: An Introduction Using MATLAB and Excel

288 Newton’s Method Example
For x = : Engineering Computation: An Introduction Using MATLAB and Excel

289 Newton’s Method Example
y = y’ = Initial value = New x-value = Engineering Computation: An Introduction Using MATLAB and Excel

290 Newton’s Method Example
Continue iterations: Method quickly converges to this root Engineering Computation: An Introduction Using MATLAB and Excel

291 Newton’s Method Example
To find the other roots, use different initial guess values Engineering Computation: An Introduction Using MATLAB and Excel

292 Newton’s Method Example
Three roots found: x = x = x = Engineering Computation: An Introduction Using MATLAB and Excel

293 Newton’s Method - Comments
Usually converges to a root much faster than the bisection method In some cases, the method will not converge (discontinuous derivative, initial slope = 0, etc.) In most cases, however, if the initial guess is relatively close to the actual root, the method will converge Don’t necessarily need to calculate the derivative: can approximate the slope from two points close to the x-value. This is called the Secant Method Engineering Computation: An Introduction Using MATLAB and Excel

294 In-Class Exercise Draw a flow chart of Newton’s Method
Write the MATLAB code to apply Newton’s Method to the previous example: Engineering Computation: An Introduction Using MATLAB and Excel

295 Define converge tolerance tol
Input initial guess x Calculate f(x) while abs(f(x)) > tol Calculate slope fpr(x) x = x – f(x)/fpr(x) Calculate f(x) Output root x Engineering Computation: An Introduction Using MATLAB and Excel

296 MATLAB Code MATLAB functions defining the function and its derivative:
Engineering Computation: An Introduction Using MATLAB and Excel

297 MATLAB Code Engineering Computation: An Introduction Using MATLAB and Excel

298 MATLAB Results >> Newton Enter initial guess 10 Root found: Root found: Root found: Engineering Computation: An Introduction Using MATLAB and Excel

299 Excel and MATLAB Tools Bisection method or Newton’s method can be easily programmed However, Excel and MATLAB have built-in tools for finding roots of equations Engineering Computation: An Introduction Using MATLAB and Excel

300 Excel and MATLAB Tools General non-linear equations: Excel: Goal Seek, Solver MATLAB: fzero Polynomials: MATLAB: roots Graphing tools are also important to locate roots approximately Engineering Computation: An Introduction Using MATLAB and Excel

301 Excel Tools We have seen how to use Solver for a system of equations; we can easily apply it to find roots of a single equation There is a tool in Excel even easier to use for a single equation: Goal Seek With Goal Seek, we instruct Excel to change the value of a cell containing the independent variable to cause the value of the cell containing the function to equal a given value Engineering Computation: An Introduction Using MATLAB and Excel

302 Goal Seek Example Engineering Computation: An Introduction Using MATLAB and Excel

303 Goal Seek Example Engineering Computation: An Introduction Using MATLAB and Excel

304 fzero Example The MATLAB function fzero finds the root of a function, starting with a guess value Example: function fun1 defines this equation: Engineering Computation: An Introduction Using MATLAB and Excel

305 fzero Example The function fzero has arguments of the name of the function to be evaluated and a guess value: >> fzero('fun1',10) ans = 5.6577 Or the name of function to be evaluated and a range of values to be considered: >> fzero('fun1',[4 10]) Engineering Computation: An Introduction Using MATLAB and Excel

306 fzero Example If a range is specified, then the function must have opposite signs at the endpoints > fzero('fun1',[0 10]) ??? Error using ==> fzero at 292 The function values at the interval endpoints must differ in sign. Engineering Computation: An Introduction Using MATLAB and Excel

307 Graphing to Help Find Roots
Making a graph of the function is helpful to determine how many real roots exist, and the approximate locations of the roots Example: Consider these two equations: How many roots does each have? Engineering Computation: An Introduction Using MATLAB and Excel

308 Graphing to Help Find Roots
Equation 1: Equation 2: 3 real roots 1 real root Engineering Computation: An Introduction Using MATLAB and Excel

309 roots Example For polynomials, the MATLAB function roots finds all of the roots, including complex roots The argument of roots is an array containing the coefficients of the equation For example, for the equation the coefficient array is [3, -15, -20, 50] Engineering Computation: An Introduction Using MATLAB and Excel

310 roots Example >> A = [3, -15, -20, 50]; >> roots(A) ans = Engineering Computation: An Introduction Using MATLAB and Excel

311 roots Example Now find roots of Two complex roots
>> B = [3, -5, -20, 50]; >> roots(B) ans = i i Two complex roots Engineering Computation: An Introduction Using MATLAB and Excel

312 Summary The bisection method and Newton’s method (or secant method) are widely-used algorithms for finding the roots of equations When using any tool to find the roots of non-linear equations, remember that multiple roots may exist The initial guess value will affect which root is found Engineering Computation: An Introduction Using MATLAB and Excel

313 Chapter 7 Matrix Mathematics
Matrix Operations Chapter 7 Matrix Mathematics Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 313

314 Matrix Mathematics Matrices are very useful in engineering calculations. For example, matrices are used to: Efficiently store a large number of values (as we have done with arrays in MATLAB) Solve systems of linear simultaneous equations Transform quantities from one coordinate system to another Several mathematical operations involving matrices are important Engineering Computation: An Introduction Using MATLAB and Excel 314

315 Review: Properties of Matrices
A matrix is a one-or two dimensional array A quantity is usually designated as a matrix by bold face type: A The elements of a matrix are shown in square brackets: Engineering Computation: An Introduction Using MATLAB and Excel 315

316 Review: Properties of Matrices
The dimension (size) of a matrix is defined by the number of rows and number of columns Examples: 3 × 3: ×4: Engineering Computation: An Introduction Using MATLAB and Excel 316

317 Review: Properties of Matrices
An element of a matrix is usually written in lower case, with its row number and column number as subscripts: In MATLAB, an element is designated by the matrix name with the row and column numbers in parentheses: A(1,2) Engineering Computation: An Introduction Using MATLAB and Excel 317

318 Matrix Operations Matrix Addition
Multiplication of a Matrix by a Scalar Matrix Multiplication Matrix Transposition Finding the Determinate of a Matrix Matrix Inversion Engineering Computation: An Introduction Using MATLAB and Excel 318

319 Matrix Addition Vectors must be the same size in order to add
To add two vectors, add the individual elements: Matrix addition is commutative: A + B = B + A Engineering Computation: An Introduction Using MATLAB and Excel 319

320 Multiplication of a Matrix by a Scalar
To multiple a matrix by a scalar, multiply each element by the scalar: We often use this fact to simplify the display of matrices with very large (or very small) values: Engineering Computation: An Introduction Using MATLAB and Excel 320

321 Multiplication of Matrices
To multiple two matrices together, the matrices must have compatible sizes: This multiplication is possible only if the number of columns in A is the same as the number of rows in B The resultant matrix C will have the same number of rows as A and the same number of columns as B Engineering Computation: An Introduction Using MATLAB and Excel 321

322 Multiplication of Matrices
Consider these matrices: Can we find this product? What will be the size of C? Yes, 3 columns of A = 3 rows of B 2 X 2: 2 rows in A, 2 columns in B Engineering Computation: An Introduction Using MATLAB and Excel 322

323 Multiplication of Matrices
Easy way to remember rules for multiplication: These values must match Size of Product Matrix Engineering Computation: An Introduction Using MATLAB and Excel 323

324 Multiplication of Matrices
Element ij of the product matrix is computed by multiplying each element of row i of the first matrix by the corresponding element of column j of the second matrix, and summing the results This is best illustrated by example Engineering Computation: An Introduction Using MATLAB and Excel 324

325 Example – Matrix Multiplication
Find We know that matrix C will be 2 × 2 Element c11 is found by multiplying terms of row 1 of A and column 1 of B: Engineering Computation: An Introduction Using MATLAB and Excel 325

326 Example – Matrix Multiplication
Element c12 is found by multiplying terms of row 1 of A and column 2 of B: Engineering Computation: An Introduction Using MATLAB and Excel 326

327 Example – Matrix Multiplication
Element c21 is found by multiplying terms of row 2 of A and column 1 of B: Engineering Computation: An Introduction Using MATLAB and Excel 327

328 Example – Matrix Multiplication
Element c22 is found by multiplying terms of row 2 of A and column 2 of B: Engineering Computation: An Introduction Using MATLAB and Excel 328

329 Example – Matrix Multiplication
Solution: Engineering Computation: An Introduction Using MATLAB and Excel 329

330 Practice Problems Find C = AB
Engineering Computation: An Introduction Using MATLAB and Excel 330

331 Practice Problems Find C = AB
Engineering Computation: An Introduction Using MATLAB and Excel 331

332 Practice Problems Find C = AB
Engineering Computation: An Introduction Using MATLAB and Excel 332

333 Matrix Multiplication
In general, matrix multiplication is not commutative: AB ≠ BA Engineering Computation: An Introduction Using MATLAB and Excel 333

334 Transpose of a Matrix The transpose of a matrix by switching its row and columns The transpose of a matrix is designated by a superscript T: The transpose can also be designated with a prime symbol (A’). This is the nomenclature used in MATLAB Engineering Computation: An Introduction Using MATLAB and Excel 334

335 Determinate of a Matrix
The determinate of a square matrix is a scalar quantity that has some uses in matrix algebra. Finding the determinate of 2 × 2 and 3 × 3 matrices can be done relatively easily: The determinate is designated as |A| or det(A) 2 × 2: Engineering Computation: An Introduction Using MATLAB and Excel 335

336 Determinate of a Matrix
Examples: Engineering Computation: An Introduction Using MATLAB and Excel 336

337 Determinate of a Matrix
3 × 3: Similar for larger matrices, but easier to do with MATLAB or Excel Engineering Computation: An Introduction Using MATLAB and Excel 337

338 Inverse of a Matrix Some square matrices have an inverse
If the inverse of a matrix exists (designated by -1 superscript), then where I is the identity matrix – a square matrix with 1’s as the diagonal elements and 0’s as the other elements Engineering Computation: An Introduction Using MATLAB and Excel 338

339 Inverse of a Matrix The inverse of a 2X2 matrix is easy to find:
Engineering Computation: An Introduction Using MATLAB and Excel 339

340 Inverse of a Matrix Example: find inverse of A:
Engineering Computation: An Introduction Using MATLAB and Excel 340

341 Check Result Engineering Computation: An Introduction Using MATLAB and Excel 341

342 Practice Problem Find A-1, check that A A-1 = I
Engineering Computation: An Introduction Using MATLAB and Excel 342

343 Inverse of a Matrix Note from the formula for the inverse of a 2 × 2 matrix that if the determinate equals zero, then the inverse is undefined This is true generally: the inverse of a square matrix exists only of the determinate is non-zero Engineering Computation: An Introduction Using MATLAB and Excel 343

344 Matrix Mathematics in MATLAB and Excel
Chapter 7 Matrix Mathematics Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

345 Review: Multiplication of Matrices
To multiple two matrices together, the matrices must have compatible sizes: This multiplication is possible only if the number of columns in A is the same as the number of rows in B The resultant matrix C will have the same number of rows as A and the same number of rows as B Engineering Computation: An Introduction Using MATLAB and Excel

346 Review: Multiplication of Matrices
Easy way to remember rules for multiplication: These values must match Size of Product Matrix Engineering Computation: An Introduction Using MATLAB and Excel

347 Review: Multiplication of Matrices
Element ij of the product matrix is computed by multiplying each element of row i of the first matrix by the corresponding element of column j of the second matrix, and summing the results In general, matrix multiplication is not commutative: AB ≠ B A Engineering Computation: An Introduction Using MATLAB and Excel

348 Practice Problem Find C = A B (2 X 4) X (4 X 3) = (2 X 3)
Engineering Computation: An Introduction Using MATLAB and Excel

349 Review: Transpose The transpose of a matrix by switching its row and columns The transpose of a matrix is designated by a superscript T: The transpose can also be designated with a prime symbol (A’). This is the nomenclature used in MATLAB Engineering Computation: An Introduction Using MATLAB and Excel

350 Review: Determinate The determinate of a square matrix is a scalar quantity that has some uses in matrix algebra. Finding the determinate of 2 × 2 and 3 × 3 matrices can be done relatively easily: The determinate is designated as |A| or det(A) 2 × 2: Engineering Computation: An Introduction Using MATLAB and Excel

351 Review: Inverse Some square matrices have an inverse
If the inverse of a matrix exists (designated by -1 superscript), then where I is the identity matrix – a square matrix with 1’s as the diagonal elements and 0’s as the other elements The inverse of a square matrix exists only of the determinate is non-zero Engineering Computation: An Introduction Using MATLAB and Excel

352 Matrix Operations in Excel
Excel has commands for: Multiplication (mmult) Transpose (transpose) Determinate (mdeterm) Inverse (minverse) Important to remember that these commands apply to an array of cells instead of to a single cell When entering the command, you must identify the entire array where the answer will be displayed Engineering Computation: An Introduction Using MATLAB and Excel

353 Excel Matrix Multiplication
Repeat previous problem – first enter the two matrices: Engineering Computation: An Introduction Using MATLAB and Excel

354 Excel Matrix Multiplication
Good practice to label the matrices: Engineering Computation: An Introduction Using MATLAB and Excel

355 Excel Matrix Multiplication
Shading and borders help the matrices stand out: Engineering Computation: An Introduction Using MATLAB and Excel

356 Excel Matrix Multiplication
Array of cells for the product must be selected – in this case, a 2 × 3 array: Engineering Computation: An Introduction Using MATLAB and Excel

357 Excel Matrix Multiplication
The MMULT function has two arguments: the ranges of cells to be multiplied. Remember that the order of multiplication is important. Engineering Computation: An Introduction Using MATLAB and Excel

358 Excel Matrix Multiplication
Using the Enter key with an array command only returns an answer in a single cell. Instead, use Ctrl + Shift + Enter keys with array functions Engineering Computation: An Introduction Using MATLAB and Excel

359 Excel Matrix Multiplication
Answer cells formatted: Engineering Computation: An Introduction Using MATLAB and Excel

360 Excel Transpose Use Ctrl + Shift + Enter to input command
Engineering Computation: An Introduction Using MATLAB and Excel

361 Excel Determinate Since determinate is a scalar, select a single cell and use Enter to input command Engineering Computation: An Introduction Using MATLAB and Excel

362 Excel Matrix Inversion
Remember that only square matrices can have inverses Engineering Computation: An Introduction Using MATLAB and Excel

363 Excel Matrix Inversion
Ctrl + Shift + Enter to input command Engineering Computation: An Introduction Using MATLAB and Excel

364 Check: A X A-1 = I, the identity matrix:
Engineering Computation: An Introduction Using MATLAB and Excel

365 Matrix Operations in MATLAB
Matrices are easily handled in MATLAB We will look at commands for: Multiplication Transpose Determinate Inverse Engineering Computation: An Introduction Using MATLAB and Excel

366 MATLAB Matrix Input Recall that to enter matrices in MATLAB, the elements are enclosed in square brackets Spaces or commas separate element within a row; semi-colons separate rows >> G = [2 5 8; ; 3 1 2] G = Engineering Computation: An Introduction Using MATLAB and Excel

367 MATLAB Matrix Multiplication
>> G = [2 5 8; ; 3 1 2] G = >> H = [4 5; 6 12; 1 1] H = Matrix multiplication symbol is same as for scalar multiplication (*): >> L = G*H L = Engineering Computation: An Introduction Using MATLAB and Excel

368 Repeat Earlier Example
Find C = A B >> A = [ ; ]; >> B = [2 3 1;0 1 0; ; 2 2 1]; >> C = A*B C = Engineering Computation: An Introduction Using MATLAB and Excel

369 MATLAB Transpose The transpose command switches rows and columns of a matrix: >> A = [10 6; 12 9; 1 3; 0 1] A = >> B = transpose(A) B = Engineering Computation: An Introduction Using MATLAB and Excel

370 MATLAB Transpose Shortcut: The prime symbol (') after a matrix also performs the tranposition: >> A = [10 6; 12 9; 1 3; 0 1] A = >> B = A' B = Engineering Computation: An Introduction Using MATLAB and Excel

371 MATLAB Determinate The det command finds the determinate of a square matrix: >> A = [2 5 6; ; 3 2 2] A = >> B = det(A) B = 53 Engineering Computation: An Introduction Using MATLAB and Excel

372 MATLAB Inversion The inv command finds the inverse of a square matrix:
>> B = inv(A) B = Engineering Computation: An Introduction Using MATLAB and Excel

373 Check: >> C = A*B C = 1.0000 0 -0.0000 0.0000 1.0000 -0.0000
Product of a matrix and its inverse is the identity matrix Engineering Computation: An Introduction Using MATLAB and Excel

374 MATLAB Matrix Inversion
Another example: A = >> B = inv(A) Warning: Matrix is singular to working precision. B = Inf Inf Inf Can you guess why this matrix has no inverse? What is the determinate of A? Engineering Computation: An Introduction Using MATLAB and Excel

375 MATLAB Matrix Inversion
Note that the third row of the matrix is simply the first row multiplied by a constant (2). When this happens, the matrix is singular and has no inverse. Also, notice that the determinate of the matrix is zero: >> det(A) ans = Engineering Computation: An Introduction Using MATLAB and Excel

376 Linear Simultaneous Equations
Consider an equation with three unknowns x, y, and z If the equation contains only linear terms of x, y, and z – that is, only constants multiplied by each variable – and constants, then the equation is linear If the equation contains any terms such as x2, cos(x), ex, etc., then the equation is non-linear Engineering Computation: An Introduction Using MATLAB and Excel

377 Linear Simultaneous Equations
Example of a linear equation: With what we know about multiplying matrices, we can write this equation as: (1 X 3) X (3 X 1) = (1 x 1) Engineering Computation: An Introduction Using MATLAB and Excel

378 Linear Simultaneous Equations
Let’s add a second equation: We can add this to our previous matrix equation by adding a second row to the first matrix and to the product: (2 X 3) X (3 X 1) = (1 x 2) Engineering Computation: An Introduction Using MATLAB and Excel

379 Linear Simultaneous Equations
Finally, let’s add a third equation: Our matrix equation is now: (3 X 3) X (3 X 1) = (1 x 3) Engineering Computation: An Introduction Using MATLAB and Excel

380 Linear Simultaneous Equations
We will use matrix mathematics to solve the equations for x, y, and z The first step in solving a series of linear simultaneous equations is to write them in matrix form For n simultaneous equations and n unknowns: where A is the coefficient matrix (n × n); X is the matrix of unknowns (n × 1), and C is the constant matrix (n × 1) Engineering Computation: An Introduction Using MATLAB and Excel

381 Linear Simultaneous Equations
Recall that if there are more unknowns then equations, then we cannot find a unique solution If there are more equations than unknowns, then some equations must be redundant If there are exactly the same number of equations and unknowns, then there may be a unique solution. In this case the coefficient matrix will be square Engineering Computation: An Introduction Using MATLAB and Excel

382 Practice Write these four equations in matrix form:
Engineering Computation: An Introduction Using MATLAB and Excel

383 Solution In Chapter 8, we will learn how to find the unknowns a, b, c, and d with matrix methods Engineering Computation: An Introduction Using MATLAB and Excel

384 Linear Simultaneous Equations
Chapter 8 Solving Simultaneous Equations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

385 Review: Linear Simultaneous Equations
If equations contain only linear terms of the independent variables – that is, only constants multiplied by each variable – and constants, then the equation is linear If the equation contains any terms such as x2, cos(x), ex, etc., then the equation is non-linear Consider these two linear equations: Engineering Computation: An Introduction Using MATLAB and Excel

386 Solution to Simultaneous Equations
Are there values of x and y that fit both equations? That is, are there values of x and y that simultaneously satisfy both equations? For two equations, it is easy to find the solution by substitution: Write the second equation as: Engineering Computation: An Introduction Using MATLAB and Excel

387 Solution by Substitution
Substitute the second equation into the first: Solve for x: Substitute x into the second equation: Engineering Computation: An Introduction Using MATLAB and Excel

388 Graphical Solution For equations with two variables, a graphical solution is possible For each equation, plot two points to define a line If the lines intersect, then the intersection point is a solution to both equations Engineering Computation: An Introduction Using MATLAB and Excel

389 Graphical Solution Equation 1 Equation 2
Engineering Computation: An Introduction Using MATLAB and Excel

390 Review: Equations in Matrix Form
The first step in using matrix methods to solve a series of linear simultaneous equations is to write them in matrix form For n simultaneous equations and n unknowns: where A is the coefficient matrix (n × n); X is the matrix of unknowns (n × 1), and C is the constant matrix (n × 1) Engineering Computation: An Introduction Using MATLAB and Excel

391 Review: Linear Simultaneous Equations
Recall that if there are more unknowns then equations, then we cannot find a unique solution If there are more equations than unknowns, then some equations must be redundant If there are exactly the same number of equations and unknowns, then there may be a unique solution. In this case the coefficient matrix will be square Engineering Computation: An Introduction Using MATLAB and Excel

392 Solution of System of Linear Equations
Multiply both sides of the equation by the inverse of the coefficient matrix. Remember that the order of multiplication is important. Since the inverse of a matrix times that matrix is equal to the identity matrix, Engineering Computation: An Introduction Using MATLAB and Excel

393 Solution of System of Linear Equations
Since the identity matrix times another matrix is equal to that matrix, Therefore, we can find the unknown variables by multiplying the inverse of the coefficient matrix by the constant matrix Engineering Computation: An Introduction Using MATLAB and Excel

394 Example – 2 Equations Let’s use the matrix approach to solve the equations of the earlier example: The first step is to write the equations in matrix form: Engineering Computation: An Introduction Using MATLAB and Excel

395 Example – 2 Equations Next, we need to find the inverse of the A matrix: Engineering Computation: An Introduction Using MATLAB and Excel

396 Example – 2 Equations To find x and y, multiply the inverse of A by C:
Engineering Computation: An Introduction Using MATLAB and Excel

397 MATLAB Solution >> A = [2 3;-4 1]; >> C = [14;28]; >> X = inv(A)*C X = -5 8 >> Engineering Computation: An Introduction Using MATLAB and Excel

398 Another Example Consider these two equations: MATLAB:
>> X = inv(A)*C Warning: Matrix is singular to working precision. X = Inf Engineering Computation: An Introduction Using MATLAB and Excel

399 What’s Wrong? Solve with substitution: Second equation in terms of y:
Substitute into first equation: Engineering Computation: An Introduction Using MATLAB and Excel

400 What’s Wrong? Solve: Any value of x will satisfy this equation
Engineering Computation: An Introduction Using MATLAB and Excel

401 Graphical Solution Engineering Computation: An Introduction Using MATLAB and Excel

402 Interpretation of Solution
The second equation is equal to the first equation multiplied by a constant Therefore, both equations are the same, as noted by the fact that they define the same line Any point on the line will satisfy both equations Therefore, there are an infinite number of solutions to these equations Engineering Computation: An Introduction Using MATLAB and Excel

403 A Third Example Consider these two equations: MATLAB:
>> X = inv(A)*C Warning: Matrix is singular to working precision. X = Inf Engineering Computation: An Introduction Using MATLAB and Excel

404 What’s Wrong? Solve with substitution: Second equation in terms of y:
Substitute into first equation: Engineering Computation: An Introduction Using MATLAB and Excel

405 What’s Wrong? Solve: No value of x will satisfy this equation
Engineering Computation: An Introduction Using MATLAB and Excel

406 Graphical Solution Engineering Computation: An Introduction Using MATLAB and Excel

407 Interpretation of Solution
The graphical solution shows that the two equations define parallel lines Since parallel lines never intersect, there is no point that satisfies both equations Therefore, there is no solution to these equations Note that MATLAB (or Excel) solution will result in the same error – the inverse of the coefficient matrix does not exist Engineering Computation: An Introduction Using MATLAB and Excel

408 Summary If the inverse of the coefficient matrix exists, then there is a solution, and that solution is unique If the inverse does not exist, then there are two possibilities: The equations are incompatible, and so there are no solutions, or At least two of the equations are redundant, and so there are more unknowns than unique equations. Therefore, there are an infinite number of solutions Engineering Computation: An Introduction Using MATLAB and Excel

409 Example – 3 Equations Write these equations in matrix form:
Engineering Computation: An Introduction Using MATLAB and Excel

410 Example – 3 Equations MATLAB solution:
>> C = [-30; 11; 42]; >> X = inv(A)*C X = 7.0000 5.0000 >> Engineering Computation: An Introduction Using MATLAB and Excel

411 Excel Solution Enter coefficient and constant matrices:
Engineering Computation: An Introduction Using MATLAB and Excel

412 Excel Solution Label and highlight cells for matrix of unknown variables: Engineering Computation: An Introduction Using MATLAB and Excel

413 Excel Solution Enter formula to invert A matrix and multiply the result by the C matrix. This can be done in two steps or with nested commands as shown here: Engineering Computation: An Introduction Using MATLAB and Excel

414 Excel Solution Apply formula to the selected array of cells by pressing Ctrl + Shift + Enter: Engineering Computation: An Introduction Using MATLAB and Excel

415 Non-Linear Simultaneous Equations
Chapter 8 Solving Simultaneous Equations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

416 Review: Linear Equations in Matrix Form
The first step in using matrix methods to solve a series of linear simultaneous equations is to write them in matrix form For n simultaneous equations and n unknowns: where A is the coefficient matrix (n × n); X is the matrix of unknowns (n × 1), and C is the constant matrix (n × 1) Engineering Computation: An Introduction Using MATLAB and Excel

417 Review: Linear Simultaneous Equations
Recall that if there are more unknowns then equations, then we cannot find a unique solution If there are more equations than unknowns, then some equations must be redundant If there are exactly the same number of equations and unknowns, then there may be a unique solution. In this case the coefficient matrix will be square Engineering Computation: An Introduction Using MATLAB and Excel

418 Solution of System of Linear Equations
We can find the unknown variables by multiplying the inverse of the coefficient matrix by the constant matrix Engineering Computation: An Introduction Using MATLAB and Excel

419 Summary – Linear Equations
If the inverse of the coefficient matrix exists, then there is a solution, and that solution is unique If the inverse does not exist, then there are two possibilities: The equations are incompatible, and so there are no solutions, or At least two of the equations are redundant, and so there are more unknowns than unique equations. Therefore, there are an infinite number of solutions Engineering Computation: An Introduction Using MATLAB and Excel

420 Non-Linear Equations If any of the equations are non-linear, then the matrix method will not work Example: Consider these two equations: The x2 term in the first equation prevents the use of a matrix solution Engineering Computation: An Introduction Using MATLAB and Excel

421 Excel Solver Solver is an Excel Add-In that can find solutions to many problems with multiple independent variables The first step is to check that Solver is installed If so, it will appear in the Data group of the ribbon: Engineering Computation: An Introduction Using MATLAB and Excel

422 Installing Solver If Solver is not present on the ribbon, start by clicking the Office Button… And selecting Excel Options… Engineering Computation: An Introduction Using MATLAB and Excel

423 Installing Solver Choose Add-Ins… And click Go beside Excel Add-Ins…
Engineering Computation: An Introduction Using MATLAB and Excel

424 Installing Solver Check Solver and click OK
If Solver has not been installed, click Yes to install it now Engineering Computation: An Introduction Using MATLAB and Excel

425 Using Solver Solver attempts to set the value of a target cell to its minimum, its maximum, or a specific value, By changing one or more input cells (independent variables, While maintaining specified constraints (optional) Engineering Computation: An Introduction Using MATLAB and Excel

426 Solver Example Consider this equation:
Use Solver to find values of x for which y is minimized y is equal to exactly 50 y is maximized, within limits of x from 0 to 10 Engineering Computation: An Introduction Using MATLAB and Excel

427 Solver Example To better understand this problem, consider this plot of y vs. x: Engineering Computation: An Introduction Using MATLAB and Excel

428 Solver Example Label a cell for the independent variable x and enter the formula for y in another cell: Engineering Computation: An Introduction Using MATLAB and Excel

429 Solver Example Start Solver. For the first part of the problem we want to minimize y (Target Cell C4) by changing x (cell C2): Engineering Computation: An Introduction Using MATLAB and Excel

430 Solver Example The answer is that when x = 2, y = 16, the minimum value of y that is possible: Engineering Computation: An Introduction Using MATLAB and Excel

431 Solver Example Next, find the value of x for which y = 80:
Engineering Computation: An Introduction Using MATLAB and Excel

432 Solver Example But we can see from the graph that there are two solutions to the problem This is typical for non-linear problems; multiple solutions are possible The solution found often depend on the initial guess entered before running Solver Engineering Computation: An Introduction Using MATLAB and Excel

433 Solver Example Try x = -10 as the initial guess and run Solver again:
Engineering Computation: An Introduction Using MATLAB and Excel

434 Solver Example Now try to maximize y:
Engineering Computation: An Introduction Using MATLAB and Excel

435 Solver Example Since the value of y increase to infinity for both increasing and decreasing values of x, there are no maxima values to be found However, we can constrain the problem by requiring the input value of x to be between 0 and 10: Engineering Computation: An Introduction Using MATLAB and Excel

436 Solver Example We find that when x = 10, y = 80. This is the maximum value that y can have, subject to the constraints on x. Engineering Computation: An Introduction Using MATLAB and Excel

437 Solver Example However, even this solution is affected by the initial guess. For example, if we try x = as the initial value: Then we get a different solution, although the value of y is clearly not maximized: Engineering Computation: An Introduction Using MATLAB and Excel

438 Solver Example It is important to realize that Solver finds local maximum and minimum values Allowable x-values Engineering Computation: An Introduction Using MATLAB and Excel

439 Simultaneous Equation Example
Back to our earlier example - consider these two equations: Can we find values of x and y that satisfy both equations? Engineering Computation: An Introduction Using MATLAB and Excel

440 Simultaneous Equation Example
With non-linear simultaneous equations, the first step is to write the equations with all of the variables and constants on the same side of the equal sign We give the resulting expressions variable names (f1 and f2 here): When both f1 and f2 are zero, then the equations are satisfied Engineering Computation: An Introduction Using MATLAB and Excel

441 Simultaneous Equation Example
Start by labeling two cells for the input variables (x and y) Label two cells for f1 and f2, and enter their formulas: Engineering Computation: An Introduction Using MATLAB and Excel

442 Simultaneous Equation Example
Remember that Solver must have a single target cell: we cannot specify that both f1 and f2 are to be zero We could specify that the sum of f1 and f2 be zero; however, this would not guarantee that both are zero as one could be positive and the other negative If we square both values, then both these values must be greater than or equal to zero If the sum of the squares equals zero, then both f1 and f2 must be zero Engineering Computation: An Introduction Using MATLAB and Excel

443 Simultaneous Equation Example
Add cells for the squares and their sum. The sum (cell C7) will be the Target Cell in the Solver setup: Engineering Computation: An Introduction Using MATLAB and Excel

444 Simultaneous Equation Example
Engineering Computation: An Introduction Using MATLAB and Excel

445 Simultaneous Equation Example
Solver has found a solution: x is about -1 and y is about 0 Engineering Computation: An Introduction Using MATLAB and Excel

446 Simultaneous Equation Example
These are the exact values for the solution: Engineering Computation: An Introduction Using MATLAB and Excel

447 Simultaneous Equation Example
Try different guess values of x and y: Engineering Computation: An Introduction Using MATLAB and Excel

448 Simultaneous Equation Example
A second solution if found: x = 1.5 and y = 12.5 Engineering Computation: An Introduction Using MATLAB and Excel

449 Simultaneous Equation Example
A graphical solution is possible with two equations. Notice that the curves intersect in two places Engineering Computation: An Introduction Using MATLAB and Excel

450 Simultaneous Equation Example
Zooming in, we can see the solutions that we found with Solver Engineering Computation: An Introduction Using MATLAB and Excel

451 Simultaneous Equation Example
Now try these equations (only the second is changed) Engineering Computation: An Introduction Using MATLAB and Excel

452 Simultaneous Equation Example
In this case, no solution can be found Engineering Computation: An Introduction Using MATLAB and Excel

453 Simultaneous Equation Example
Graphing the equations shows that they do not intersect Engineering Computation: An Introduction Using MATLAB and Excel

454 Summary Excel Solver can be used to numerically find maxima, minima, and specific values of a target cell by varying one or more input cells, with or without additional constraints Solver can also find solutions of simultaneous non-linear equations Important to recognize that multiple solutions may exist for non-linear problems Engineering Computation: An Introduction Using MATLAB and Excel

455 Flow Charts, Loop Structures
Chapter 9 Numerical Integration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

456 Concepts From Calculus
Two fundamental operations: Differentiation Integration Differentiation: finding the rate of change (derivative) relative to a variable Integration: summing rates of change over an interval We will illustrate with linear position, velocity, and acceleration of a particle Engineering Computation: An Introduction Using MATLAB and Excel

457 Linear Motion Consider this particle (note: in mechanics, the term particle does not relate to size. A particle is simply a body for which we can neglect rotational motions. With this definition, a car or even a planet can be considered a particle). It moves along a straight line. Its position is measured from some reference point. x Engineering Computation: An Introduction Using MATLAB and Excel

458 Linear Motion As the particle moves a distance Δx during a time period Δt, we say that the average rate of change of the position is Δx /Δt The velocity, the instantaneous rate of change, is found by taking the limit as Δt approaches zero: x Δx Engineering Computation: An Introduction Using MATLAB and Excel

459 Linear Motion We say that the velocity is the derivative of position with respect to time Similarly, the acceleration of the particle is the instantaneous rate of change of velocity, or acceleration is the derivative of velocity with respect to time: Engineering Computation: An Introduction Using MATLAB and Excel

460 Linear Motion Now let’s work the other way: if we know that our speed over a period of time, can we determine how far we have gone? Start with the equation for velocity: This can be rewritten as: Engineering Computation: An Introduction Using MATLAB and Excel

461 Linear Motion So over a very small period of time dt, the change of position dx will be the velocity times dt To get the change of position over a larger time interval, we sum (integrate) v times dt for all of the small time intervals: Engineering Computation: An Introduction Using MATLAB and Excel

462 Graphical Interpretations
Consider position x plotted vs. time t The change in x divided by the change in t is the average rate of change over that time interval: Δx Δt Engineering Computation: An Introduction Using MATLAB and Excel

463 Graphical Interpretations
As the interval time becomes infinitesimally small, the rate of change becomes the slope of the curve at a specific point in time Slope = derivative of x with respect to t t Engineering Computation: An Introduction Using MATLAB and Excel

464 Graphical Interpretations
Now consider a graph of velocity vs time The change in position over a small time interval dt is v times dt v dt Engineering Computation: An Introduction Using MATLAB and Excel

465 Graphical Interpretations
The change in position is the sum of these small areas – the integral of velocity over the time interval t1 t2 Engineering Computation: An Introduction Using MATLAB and Excel

466 Graphical Interpretations
The derivative of a function is the slope of the curve of that function at a particular point The integral of a function is the area under the curve of that function for a given interval Engineering Computation: An Introduction Using MATLAB and Excel

467 Derivatives of Polynomials
In calculus classes, you have learned (or will learn) how to differentiate many types of functions Polynomials are simplest to differentiate: for each term, reduce the exponent of the variable by one, and modify the term by the original exponent Example: Engineering Computation: An Introduction Using MATLAB and Excel

468 Integrals of Polynomials
To integrate a polynomial, reverse the process: for each term, add one to the exponent of the variable and divide the term by the new exponent Note the constant term C that must be added. This term will depend on a boundary condition Engineering Computation: An Introduction Using MATLAB and Excel

469 Definite Integrals The previous integral, with no limits given, is called an indefinite integral, a general solution When upper and lower limits are defined, this is classed a definite integral To evaluate a definite integral, substitute the upper and lower limits into the general solution and subtract the value at the lower limit from that of the upper limit Engineering Computation: An Introduction Using MATLAB and Excel

470 Definite Integrals Example:
Note that the constant C was ignored, its value at the lower limit is the same as at the upper limit, and so is cancelled in the subtraction Engineering Computation: An Introduction Using MATLAB and Excel

471 Numerical Integration
We can get an approximate value of a definite integral of any function with a numerical approach The key is to remember that the value of the integral is simply the area under the function’s curve Engineering Computation: An Introduction Using MATLAB and Excel

472 Numerical Integration
Here is the area under the curve for our example, The total area is 16 (units depend on the units of x and y) Engineering Computation: An Introduction Using MATLAB and Excel

473 Numerical Integration
Consider the two values of x shown here. To find the area under the curve between these two points, we will approximate this portion of the curve with a straight line segment Engineering Computation: An Introduction Using MATLAB and Excel

474 Numerical Integration
A trapezoidal area is formed: Engineering Computation: An Introduction Using MATLAB and Excel

475 Numerical Integration Example
We will use four intervals of x, each one unit wide Values of y at the interval endpoints: y = -3 y = 24 y = 9 y = 0 Engineering Computation: An Introduction Using MATLAB and Excel

476 Numerical Integration Example
Areas: Sum = 18 Engineering Computation: An Introduction Using MATLAB and Excel

477 Numerical Integration Example
Notice that our trapezoids over estimate the positive area and under estimate the negative areas Engineering Computation: An Introduction Using MATLAB and Excel

478 Numerical Integration Example
Using more intervals improves the accuracy: Sum = 16.5 Engineering Computation: An Introduction Using MATLAB and Excel

479 Numerical Integration Example
How do we know when we have used enough intervals? (Assuming that we don’t know the exact answer, which is probably why we are using a numerical solution) Try more intervals until the solution converges to a value This makes a MATLAB solution a good choice – we can change the number of intervals easily Engineering Computation: An Introduction Using MATLAB and Excel

480 Numerical Integration Application: Normal Distributions
Chapter 9 Numerical Integration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

481 Review: Numerical Integration
When evaluating a definite integral, remember that we are simply finding the area under the curve between the lower and upper limits This can be done numerically by approximating the area with a series of trapezoids Engineering Computation: An Introduction Using MATLAB and Excel

482 Review: Trapezoid Area
A trapezoidal area is formed: Engineering Computation: An Introduction Using MATLAB and Excel

483 Other Numerical Integration Methods
Higher-order functions allow fewer intervals to be used for similar accuracy For example, Simpson’s Rule uses 2nd order polynomial approximations to determine the area With the speed of modern computers, using these more efficient algorithms is usually not necessary – the trapezoid method with more intervals is sufficient Engineering Computation: An Introduction Using MATLAB and Excel

484 Application – Normal Distribution
The standard deviation is a commonly-used measure of the variability of a data population or sample A higher standard deviation means that there is greater variability If we assume that the population or standard is distributed as a normal distribution, then we can obtain a lot of useful information about probabilities Engineering Computation: An Introduction Using MATLAB and Excel

485 Normal Distribution Many numerical populations can be approximated very closely by a normal distribution Examples: Human heights and weights Manufacturing tolerances Measurement errors in scientific experiments The population is characterized by its mean and standard deviation Engineering Computation: An Introduction Using MATLAB and Excel

486 Normal Distribution The probability density function of the normal distribution can show a graphical view of how the population is distributed The probability density function (pdf) is given by this equation: Engineering Computation: An Introduction Using MATLAB and Excel

487 Example Consider a population with a mean of 10 and a standard deviation of 1. Here is the pdf: Peak occurs at mean value of x (10) Frequency values approach zero for x-values far away from the mean Engineering Computation: An Introduction Using MATLAB and Excel

488 Effect of Standard Deviation
What if the standard deviation is 1.5 instead of 1? Here is the new pdf, compared with the original: Note the “wider” shape, as values are more spread out from the mean when the standard deviation is greater σ = 1.0 σ = 1.5 Engineering Computation: An Introduction Using MATLAB and Excel

489 Notes About the Probability Density Function
The curve is symmetric about the mean Although the curve theoretically extends to infinity in both directions, the function’s values approach zero and can be ignored for x-values far away from the mean The area under the curve is equal to one – this corresponds to 100% of the population having x-values greater than - and less than + The percentage of the population between other limits can be computed by integrating the function between those limits Engineering Computation: An Introduction Using MATLAB and Excel

490 The Standard Normal Distribution
The pdf can be standardized by introducing a new variable Z, the standard normal random variable: The Z-value is simply the number of standard deviations from the mean. Negative values indicate that the data point is below the mean, positive values indicate that the data point is above the mean Engineering Computation: An Introduction Using MATLAB and Excel

491 Examples For a population with a mean of 30 and a standard deviation of 2, what is the Z-value for: x = 27 Z = -1.5 (1.5 standard deviations below the mean) x = 34 Z = +2.0 (2.0 standard deviations above the mean) x = 30 Z = 0 Engineering Computation: An Introduction Using MATLAB and Excel

492 Standard Normal Distribution
Using the Z-values, we can write the equation for the probability density function as: This form is especially useful in that the same probability density graph applies to all normal distributions (next slide) Engineering Computation: An Introduction Using MATLAB and Excel

493 Standard Normal Distribution
Engineering Computation: An Introduction Using MATLAB and Excel

494 Integration of Standard Normal Distribution Function
As we have stated, the area under the curve from - to + is equal to one Often, we want to find the area from - to a specific value of Z For example, suppose we want to find the percentage of values that are less than one standard deviation above the mean This will be Engineering Computation: An Introduction Using MATLAB and Excel

495 Integration of Standard Normal Distribution Function
This integral is known as the cumulative standard normal distribution This integral does not have a closed-form solution, and must be evaluated numerically There are tables of the results in most statistics books Engineering Computation: An Introduction Using MATLAB and Excel

496 Typical Table of Integral Values
Second decimal place of Z-value Z-value to one decimal place Engineering Computation: An Introduction Using MATLAB and Excel

497 Integral Value for Z = 1.00 Integral = 0.841
This means that 84.1% of all values will be less than (mean + 1 standard deviation) Engineering Computation: An Introduction Using MATLAB and Excel

498 Graphical Interpretation of Answer
Engineering Computation: An Introduction Using MATLAB and Excel

499 In-Class Exercises Consider a sample of concrete test specimens with a mean compressive strength of 4.56 ksi and a standard deviation of ksi Using tables of the cumulative standard normal distribution, find: The percentage of tests with strength values less than 3.50 ksi The percentage of tests with strength values greater than 5.0 ksi The strength value that 99.9% of tests will exceed Engineering Computation: An Introduction Using MATLAB and Excel

500 1. Percentage of Values Less Than 3.5 ksi
Z = (3.5 – 4.56)/0.482 = (round to -2.20) From table: 0.0139, or 1.4% of values are less than 3.5 ksi. Engineering Computation: An Introduction Using MATLAB and Excel

501 2. Percentage of Values Greater Than 5 ksi
Z = (5.0 – 4.56)/0.482 = (round to 0.91) From table: of the total values are less than 5 ksi, so = , or 18.1% of values are greater than 3.5 ksi. Engineering Computation: An Introduction Using MATLAB and Excel

502 2. Percentage of Values Greater Than 5 ksi
Note that Z = Rather than rounding off, we can get a slightly more accurate answer by linear interpolation of the table values: Cumulative density = Engineering Computation: An Introduction Using MATLAB and Excel

503 3. Strength Value That 99.9% of Tests Will Exceed
We want to find a value that 0.1% (0.001) of tests are below From the table, find the Z-value corresponding to a cumulative density of 0.001 Z is approximately (note that to 4 decimal places, Z = and Z = have the same value of ) Engineering Computation: An Introduction Using MATLAB and Excel

504 3. Strength Value That 99.9% of Tests Will Exceed
Z = -3.10 So the value that 99.9% of tests will exceed is 3.10 standard deviations below the mean: Therefore, 99.9% of tests will exceed a value of 3.07 ksi. If we set this value as the lower limit, then an average of one of every 1000 batches of concrete will not meet the specification Engineering Computation: An Introduction Using MATLAB and Excel

505 Application with MATLAB
Calculating the integral directly will eliminate the need to use the tables Since we cannot begin our integration at -, what value of lower limit should we use? How many intervals do we need to use to get acceptable precision for our answers? We will experiment with different values for the lower limit and number of intervals Engineering Computation: An Introduction Using MATLAB and Excel

506 Function normdist function SUM = normdist(limit, k) lower = -limit; upper = limit; inc = (upper-lower)/k; SUM = 0; x(1) = lower; y(1) = 1/sqrt(2*pi)*exp(-x(1)^2/2); for i = 2:(k+1) x(i) = x(i-1)+inc; y(i) = 1/sqrt(2*pi)*exp(-x(i)^2/2); SUM = SUM + .5*(y(i) + y(i-1))*(x(i) -x(i-1)); end k = number of increments Making “limit” an argument of the function allows us to examine the effect of using different values Engineering Computation: An Introduction Using MATLAB and Excel

507 Evaluation of Limits, Number of Increments
>> format long >> normdist(3,100) ans = >> normdist(3,1000) >> normdist(6,1000) >> normdist(6,10000) ans = >> normdist(6,100) >> normdist(5,100) Engineering Computation: An Introduction Using MATLAB and Excel

508 Conclusions Limit = 6 (6 standard deviations) gives accuracy to eight decimal places Number of increments less important: similar results for 100, 1000, and increments Use lower limit of -6 standard deviations, 1000 increments Engineering Computation: An Introduction Using MATLAB and Excel

509 Modified Function normdist
function SUM = normdist(Z) % Calculates the % of population with values less than Z lower = -6; upper = Z; k = 1000; inc = (upper-lower)/k; SUM = 0; x(1) = lower; y(1) = 1/sqrt(2*pi)*exp(-x(1)^2/2); for i = 2:(k+1) x(i) = x(i-1)+inc; y(i) = 1/sqrt(2*pi)*exp(-x(i)^2/2); SUM = SUM + .5*(y(i) + y(i-1))*(x(i) -x(i-1)); end Engineering Computation: An Introduction Using MATLAB and Excel

510 Check >> normdist(0) ans = Should be 0.50 since curve is symmetric >> normdist(1) Checks with value from table Engineering Computation: An Introduction Using MATLAB and Excel


Download ppt "Chapter 2 Excel Fundamentals"

Similar presentations


Ads by Google