111
AE 303 Computer Applications and Systems Modeling An International Experience in Germany The University of Hohenheim Stuttgart Germany August 4 22, 2002 Bill Batchelor 219b Davidson Hall Iowa State University Ames, IA 50011 Phone 515-294-9906 Fax 515-294-2552 Email [email protected]

Upload VBA Lesson_1

Embed Size (px)

Citation preview

Page 1: Upload VBA Lesson_1

AE 303 Computer Applications and

Systems Modeling

An International Experience in Germany

The University of Hohenheim

Stuttgart Germany August 4 – 22, 2002

Bill Batchelor 219b Davidson Hall

Iowa State University Ames, IA 50011

Phone 515-294-9906 Fax 515-294-2552

Email [email protected]

Page 2: Upload VBA Lesson_1

2

Page 3: Upload VBA Lesson_1

3

Table of Contents

Topic Supporting Programs

Page

Lesson 1: Introduction to Numerical Methods Lab 1: Introduction to VBA

Lesson 1.xls 4

Lesson 2: Roots of Equations Lab 2: Estimation of bacteria levels in the Skunk River

Lesson 2.xls 21

Lesson 3: Solving systems of equations using Gauss elimination Lab 3: Gauss elimination with partial pivoting

Lab #3-Gauss.xls

33

Lesson 4: Matrix inversion using Excel Lab 4: Data Encryption

Lab #4-Encryption.xls

40

Lesson 5: Linear Regression Lab 5: Sleepy Student Sensor

Lab #5-Sleepy.xls Sensor#1.dat Sensor#2.dat Sensor#3.dat Sensor#4.dat

51

Lesson 6: Polynomial Regression

63

Lesson 7: Time Value of Money

68

Lesson 8: Present Worth Analysis

81

Lesson 9: Annual Cash Flow Analysis

87

Lesson 10: User Inter face in Excel and VBA Lab 10: User Interfaces in Excel

91

VBA Reference Guide 98 Programs You Should Turn In

Exercise #1-{your name}.xls Exercise #5-{your name}.xls Exercise #6-{your name}.xls

Lab #1-{your name}.xls Lab #2-{your name}.xls Lab #3-{your name}.xls Lab #4-{your name}.xls Lab #10-{your name}.xls

Page 4: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

4

Lesson 1 Introduction to Numerical Methods

Introduction Mathematical models are equations that describe the behavior of a system. Engineers often develop mathematical models of systems as part of the design process. Mathematical models help us to determine our level of understanding of the underlying chemical, physical or biological principles governing system behavior. They can also be used to predict the behavior of a system, or to optimize design parameters of a system. More recently, mathematical models have been embedded into real time control systems to adjust control inputs to optimize system performance.

Model of a System A simple example of a mathematical model describing the behavior of a system is the equation that governs the velocity of a falling parachute. Examine the free body diagram shown below.

In this example, we are interested in determining the velocity of the person falling to the earth using a parachute. The force on the person can be characterized as

Where F = sum of all forces acting on the body m = mass a = acceleration

Fup

Fdown

amF *

Page 5: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

5

This equation can be rewritten in the form of a differential equation, since acceleration (a) is the rate of change of velocity, or dV/dt:

The sum of the forces acting on the body is the difference between the upward and downward forces acting on the body. The upward force on the parachute can be characterized as

Fup = - c * V Where c = drag coefficient of the parachute V = velocity of the parachute The downward force on the body can be characterized by

Fdown = m * g

Where m = mass of the body g = force of gravity The mathematical model that describes the velocity of the body can be developed by combining these equations to give

Or

Eq. 1

mF

dtdV

mcVmg

dtdV

mcV

gdtdV

Page 6: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

6

Analytical Solution Equation 1.1 can be solved analytically. An analytical solution means that we can integrate the equation using standard differential equation techniques to derive an equation that explicitly computes the velocity of the parachute. By integrating Equation 1, we get the following analytical solution

Where V(t) is the velocity at time t g = gravity m = mass c = drag coefficient of the parachute t = time Let’s assume that when the person jumps from the plane at time t=0, the velocity is 0 m/s. Let’s also assume that the person has a mass of 68.1 kg, and the drag coefficient of the parachute is 12.5 kg/s. We can now plug in different values for time and develop a curve describing the velocity of the parachute as a function of time. This analytical solution is shown in the figure below. You can easily observe that at time t=0, the velocity of the parachute is 0 m/s. You can also observe that as time increases, the parachute reaches a terminal velocity of about 50 m/s.

mtc

ec

mgtV*

1*)(

Analytic Solution for Terminal Velocity

0

10

20

30

40

50

60

0 10 20 30 40 50 60

Time, s

Velo

city Analytical Solution

Page 7: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

7

Numer ical Solution In the real world, the equations that govern complex systems are often to complex to be solved using analytical techniques. Sometimes simplifications are made to equations in order to solve them. Simplifications, however, come at some expense in that they no longer truly represent the behavior of the system. Numerical methods provide us a way to solve many equations that cannot be solved with analytical techniques. There are many different numerical techniques that can be used to solve many classes of problems. Some of these methods will be covered in this course. Let’s look at a simple example of a numerical method to solve the parachute problem outlined above. Let’s begin with equation 1, which is a simple differential equation that describes the acceleration, or change in velocity (dV) with respect to time (dt).

Based on your knowledge of calculus you know that geometrically dV/dt is the change in velocity divided by the change in time. In the figure below is a plot of velocity versus time. The derivative dV/dt is simply the slope of the velocity curve between two points. Since slope is simply rise divided by run between two points, we can develop a numerical representation of dV/dt.

Substituting the numerical definition of dV/dt into Equation 1give the following

Eq. 2

We can now rearrange Equation 2 to solve for the velocity at time t+dt by

Eq. 3

mcV

gdtdV

Vt

Vt+dt

Vel

ocity

, m/s

Time, s

t t+dt

tdttVV

runrise

dtdV tdtt

)(

ttdtt V

mc

gtdtt

VV*

)(

tdttVmc

gVV ttdtt

Page 8: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

8

In order to solve this equation, we need to know the initial velocity at time t, and we need to select a timestep, dt. Let’s assume that at time t=0, the velocity = 0 m/s. Let’s now solve Equation 3 using a time step dt = 2 seconds. Let’s also assume that the person has a mass of 68.1 kg, and the drag coefficient of the parachute is 12.5 kg/s. Plugging these parameters into Equation 3, we can compute the velocity at time t=2 seconds by

Now that we know the velocity at time t=2 seconds, we can use this value to iterate the equation and compute the velocity at time t=4 seconds by

The Table below shows the numerical solution for each time step. It also shows the analytical solution computed using Equation 1 for each value of time. The error column shows the percent difference between the numerical and analytical solution. It is computed by

Vel, m/s Vel, m/s Time, s Numeric Analytic Error

0 0.00 0.00 0.00 2 19.60 16.40 3.20 4 32.00 27.77 4.24 6 39.86 35.64 4.21 8 44.82 41.10 3.73

10 47.97 44.87 3.10 12 49.96 47.49 2.47 14 51.22 49.30 1.92 16 52.02 50.56 1.46 18 52.52 51.43 1.09 20 52.84 52.03 0.81

dtVmc

gVV ttt 002

smVt /6.1920*1.685.12

8.902

dtVmc

gVV ttt 224

smVt /0.3226.19*1.685.12

8.96.194

100*valueAnalytical

valueNumericalvalueAnalyticalerror

Page 9: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

9

The error between the analytical, or true solution, and the numerical solution is proportional to the step size, dt, used to compute the numerical solution. The smaller the step size, the more accurate the numerical solution. However, the smaller the step size, the more calculations that have to be made to develop the velocity curve, so it costs more in terms of computer time to solve this problem.

Page 10: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

10

Exercise 1 1. Open the spreadsheet called Lesson 1.xls. The tab labeled “analytic” shows the

analytical solution to the parachute problem. The tab labeled “numeric 1” shows a comparison of the numeric and analytical solution. The tab labeled “numeric 2” shows a comparison of the analytical solution to a numerical solution using a step size of 2 seconds and a variable step size that you can enter yourself. In the tab labeled “numeric 2”, play around with different step sizes by varying the step size in cell J15 (green color). In the space below, describe the behavior of the velocity vs time curve for different numerical step sizes. Discuss the error between the numerical and analytical solutions for different numerical step sizes.

Page 11: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

11

2. A water storage tank contains water at a depth y, where y=0 when the tank is half full.

Water is withdrawn at a constant flow rate Q to meet the city’s demands. The water volume is recharged at a sinusoidal rate 3Qsin2t. The following equation can be written for this system:

Where V = volume of the tank Q = flowrate of water withdrawn from the tank, m3/d A = cross sectional area of the tank, m3 t = time, days y = height of water above the center of the tank, m dy/dt = rate of change in height of water above center of tank, m 2A. Develop a spreadsheet using Microsoft Excel to solve for the height of y using a numerical approach from t=0 to t=5 days with a stepsize of 0.5 days. Assume that A = 1200 m2 and Q = 400 m3/day. Store the spreadsheet in a file called Exercise#1-{your name}.xls. 2B. In your spreadsheet, plot y (water height) vs time over the 5 day time interval. The answer is shown in Fig. 1. In the space below, write a description of the predicted system behavior. What does the graph say about the system performance? What would happen as time increases above 10 days?

AQ

tAQ

dtdy 2sin3

Y

Water level at center of tank

Figure 1. Height of Water vs Numeric Step Size for Problem 1.13

-1

0

1

2

3

0 2 4 6 8 10

Time, days

Hei

ght,

m

Step = 0.5

Page 12: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

12

2C. In a second plot, compare the numeric estimation of y using step sizes of 0.5, 1, 2, and 3 days over a period of 80 days. The answer is shown in Fig. 2. In the space below, write a paragraph describing what each of these 4 graphs say about the system behavior. What is the effect of the numerical step size on the predicted system behavior? Which step size seems to give the most believable answer?

Figure 2. Comparison of Step Sizes for Problem 1.13

-6

-4

-2

0

2

4

6

8

10

12

14

16

0 20 40 60 80 100

Time, d

Y, m

Step = 0.5Step = 1.0Step = 2.0Step = 3.0

Page 13: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

13

Laboratory 1 Introduction to Visual Basic for Applications (VBA)

Introduction Visual Basic for Applications (VBA) is a programming language that Microsoft has embedded into their Microsoft Office suite of programs, including Excel, Word and Access. In this course, we will focus on developing VBA programs inside of Microsoft Excel. This programming language will allow you to develop powerful spreadsheets to solve problems that would be difficult to solve using a spreadsheet alone. VBA is a subset of the Visual Basic programming language, also marketed by Microsoft. Visual Basic (VB) is a very powerful programming language that can interface with other Microsoft products. Once you learn VBA. It is used widely in engineering companies. By learning VBA, you will find it easy to extend your knowledge into VB if your company programs in Visual Basic. Note that when Microsoft Excel is installed onto a computer, VBA is not loaded as a default option. After opening a blank Excel spreadsheet, you many need to “turn on” the VBA option using the “Add In” feature. Go to the “Tools” menu at the top of the screen and select the “Add Ins” menu selection. You will then see many additional “tools” that can be loaded into your default Excel template. You should click on all the “VBA” add-ins to turn them on forever in your default Excel template.

Objectives The objective of this lab is to demonstrate several useful Microsoft Excel functions, and to teach you some basic Visual Basic Application (VBA) commands. Your task is to develop a VBA program to compute the analytical and numerical solution for the falling parachute problem outlined in Lesson 1.

Procedures Step 1: Open a new spreadsheet in Excel and set up Inputs (Fields B9-B13) on the spreadsheet as shown below: Row Number

Column Column

A B 9 Mass, kg 68.1 10 Drag

Coefficient 12.5

11 Gravity, m/s2 9.8 12 Final time (Tf) 50 13 Time Step

(dT) 2

Page 14: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

14

Step 2: We now need a way to transfer the variable values between the spreadsheet and a VBA program. We will do this by defining a group of cells in Excel as an array of cells, or a variable. This variable and the cells associated with it are then available to be directly used in VBA code for either data input or data output. Define a variable called Analytical that covers the range $A$20:$B$150. This will be a group of cells where the VBA program will write output to. From the menu, click the following sequence of menu items: Insert > Name > Define. Click the mouse in the top blank, and type in Analytical. This defines the name of a group of cells that can be used as a reference in VBA code. Click in the bottom blank, delete the default cell reference that shows up, and then use the mouse to highlight the cells on the spreadsheet you want to be defined using the name Analytical. You should select cells A20:B150 with the mouse. You can always modify this range in the future using the same menu. Step 3: In Cell A19, type in the word Time, s. Step 4: In Cell B19, type in the word Velocity, m/s. Step 5: It is now time to create a visual basic for application program to compute the velocity of the parachute as a function of time. From the menu, select the following: Tools > Macro > Visual Basic Editor. You are now in the VBA editor. On the left, you should have a blue highlight on the Sheet 1 Object. The program you type to the right will be associated with Sheet 1 of the workbook. From the VBA menu, select the following: Insert> Module to begin a new VBA module (program). Step 6: Now, type in the program. The program code and a description of each command is shown below. The actual code is bold, and an explanation of the command or code follows. Sub analytic()

The Sub command defines a subroutine, or program in VBA. We are calling this subroutine Analytic, which will be defined as a Macro in Excel. The parentheses () at the end of the command means we are not passing any parameters into the subroutine. Note that when you type in the Sub command, the End Sub command will show up by default. Don’t erase this!

Dim V(1000), M, g, c, T, Tf, dT As Double

The Dim command defines variables and arrays. Every variable must be defined. V(1000) defines a 1-dimensional array that will store up to 1000 values. A 2-dimensional array may be defined as V(10,100). The other variables, M, g, c, T, Tf, and dT are additional variables we will use later in the program. The command As Double sets these variables as double precision. Thus, the program

Page 15: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

15

uses two computer “words” to maintain the values of the variables. This will be described later in the course.

' -------------- READ IN INPUT VALUES ------------------- g = Range(" b11" ).Value c = Range(" b10" ).Value M = Range(" B9" ).Value Tf = Range(" B12" ).Value dT = Range(" B13" ).Value

These commands set the variable values to values entered in the spreadsheet called Sheet1. For instance, the command g = Range(" b11" ).Value sets the VBA program variable g to the number in cell B11 of the spreadsheet. The command term Range tells VBA where the cell is located, and the .Value extension tells VBA to use the value in the cell.

' -------------- Solve the Function at discrete time steps ------- Range(" Analytical" ).ClearContents j = 1 For T = 0 To Tf Step dT V(j) = g * M / c * (1 - Exp(-c / M * T)) Range(" Analytical" ).Cells(j, 1).Value = T Range(" Analytical" ).Cells(j, 2).Value = V(j) j = j + 1 Next T

The command Range(" Analytical" ).ClearContents tells VBA to clear the contents in the cells defined as Analytical in the Excel spreadsheet. (See Step 2 above where you defined these variables). Note that the For-Next loop syntax is similar to FORTRAN. The value of T will be incremented from 0 to Tf in increments of dT. In this loop, we will compute the value of velocity for each user defined step increment (dT) over the range of time the user defined (Tf, or final time). The variable j is used as a simple counter for the index of the velocity array. Note the equation for V(j) follows the equation outlined in class. The next 2 lines of code write the values of time (T) and velocity (Vj) back to the spreadsheet. The command Range(“Analytical”) tells VBA to write the values of T in Cells(j,1) in the cells defined as “Analytical” (See step 2 above for definition of Analytical). The Cells component of the command is very powerful. The basic format of this command Cells(j,k), which is defined as Cells(row, column). The row is defined as the counter j, and we are setting the column k to 1 for T and 2 for V(j). The rows and columns are relative to the rows and columns defined in Excel for the variable Analytical. Thus, row 1 column 1 of Analytical corresponds to the cell A20 in the spreadsheet. Following this logic, Row 1 column 2 corresponds to A21, etc.

Page 16: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

16

End Sub All subroutines end with this command, which VBA automatically places in the

file. Step 7: Now, on the bottom toolbar, click on the Microsoft Excel button or the Microsoft Visual… button to switch between the spreadsheet and the program. Step 8: It is now time to add a button on the spreadsheet to run the VBA program. Follow the menu sequence View > Toolbars > Forms. This will pop up a toolbar with several icons on it. Select the “button” button (the square button shape) and then use the left mouse button to drag a rectangular shape anywhere on the spreadsheet. A menu will then pop up and ask you which Macro to assign to the button. Select the Macro you just developed, called Analytic. Select “OK” to end the creation of a button. The button you just created may be highlighted. Click anywhere on the spreadsheet to “unselect” the button and make it active. Step 9: You can now run the program from within the VBA program editor. Press the F8 function key on your keyboard to step through the program in the debug mode. As you step through the program, you can move the mouse over different variables and you will see the value of the variable pop up. This is a very powerful way to trace your program and debug your program. To terminate the debugging process, go to the “Run” menu and select the “Reset” menu item. Step 10: You may now run the VBA program you just created from the spreadsheet by simply clicking on the button you just created inside the spreadsheet. Practice changing the time step and running the program. Notice that the Range("Analytical").ClearContents command in the program will clear out the old model results each time you run the new model. Step 11: Now you are ready to create a graph showing velocity as a function of time. Using the mouse, select the time and velocity cells for the A19:B150. Note that this includes the headers in row 19, and may include many blank cells in rows above row 45. This is designed so that you can automatically plot any numbers in rows 20-150 in the spreadsheet (ie. Allows you to automatically plot results from step sizes much smaller than 2 s). From the menu, select Insert>Chart>XY (Scatter) and follow the instructions. Place this graph on your worksheet, and change the size, shape, and format to allow you to watch the graph regenerate each time you change a step size and recompute the velocity. Step 12: Using the knowledge that you have just obtained, develop a second worksheet in the same Excel file and solve the parachute problem both analytically and numerically, as we did in class (See Ch. 1 in the text). You should have 4 primary columns of data. Column A should be time, B should be the analytical solution, C should be the numeric solution, and column D should be the root mean square error (RMSE) between analytical

Page 17: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

17

and numeric solutions. In one graph, plot the analytic and numeric solution. In a second graph, plot the RMSE vs time. RMSE can be computed by:

2)( NumericAnalyticalRMSE Step 12. Save your program under your directory and call it Lab #1-{your last name}.xls.

Page 18: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

18

Subroutines Sub analytic() Dim V(1000), M, g, c, T, Tf, dT As Double ' ------ READ IN INPUT VALUES ------------------- g = Range("b11").Value c = Range("b10").Value M = Range("B9").Value Tf = Range("B12").Value dT = Range("B13").Value '------- Solve the Function at discrete time steps ------- Range("Analytical").ClearContents j = 1 For T = 0 To Tf Step dT V(j) = g * M / c * (1 - Exp(-c / M * T)) Range("Analytical").Cells(j, 1).Value = T Range("Analytical").Cells(j, 2).Value = V(j) j = j + 1 Next T Sub Numeric() ' This program computes the velocity as a function of time ‘ for the falling parachute problem using both a numeric ‘ and analytical technique. ' -------- Dimension and Define the Variables ------------ ' Use the Dim command to declare the variables Dim VN(1000), VA(1000), Err(1000) As Double Dim M, g, c, T, Tf, dT As Double ' ---- Read In Input Values and/or Initial Conditions -- 'Variables can be initialized with cell values in the active ‘ worksheet. The following sets the varible g with the value ‘ in cell b11, c with the value in cell b10, etc. g = Range("b11").Value c = Range("b10").Value M = Range("B9").Value

Page 19: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

19

Tf = Range("B12").Value dT = Range("B13").Value ' --- Solve the Function at discrete time steps --------------

Range("Numeric").ClearContents ' Compute VN, VA for Time T=0, V=0 j = 1 T = 0 VN(j) = 0 VA(j) = g * M / c * (1 - Exp(-c / M * T)) Err(j) = ((VN(j) - VA(j)) ^ 2) ^ 0.5 ' Output the velocities to the spreadsheet Range("Numeric").Cells(j, 1).Value = 0 Range("Numeric").Cells(j, 2).Value = VN(j) Range("Numeric").Cells(j, 3).Value = VA(j) Range("Numeric").Cells(j, 4).Value = Err(j) 'Now, compute VN and VA for remainder of time steps j = 2 For T = dT To Tf Step dT 'Compute velocity and error VN(j) = VN(j - 1) + (g - c / M * VN(j - 1)) * dT VA(j) = g * M / c * (1 - Exp(-c / M * T)) Err(j) = ((VN(j) - VA(j)) ^ 2) ^ 0.5 'Output values to spreadsheet Range("Numeric").Cells(j, 1).Value = T Range("Numeric").Cells(j, 2).Value = VN(j) Range("Numeric").Cells(j, 3).Value = VA(j) Range("Numeric").Cells(j, 4).Value = Err(j) j = j + 1 Next T End Sub 'Variable List 'VN - array of velocity computed numerically, m/s 'VA - array of velocity computed analytically, m/s 'ERR - root mean square error between VA and VN, m/s 'M - mass, kg in cell B9

Page 20: Upload VBA Lesson_1

AE 303 Lesson 1 __________________________________________________________________________________

20

'g - gravitational constant, m/s2 in cell B11 'c - drag coefficient in cell B10 'T = time, s 'Tf - Final time of calculation, s in cell B12 'dT - time step for solution, s in cell B13

Page 21: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

21

Lesson 2 Roots of Equations

Introduction One class of engineering problems requires solving for the roots of a function. Consider again the equation governing the velocity of a man falling to the ground with a parachute. The governing equation was derived in Lesson 1 as

Eq. 1

As a parachute designer, your goal is to design a parachute to limit the terminal velocity of the person. From a design standpoint, the drag coefficient, c, is the only parameter in Equation 1 that you can control through the design of the parachute. By making the parachute small, or adding holes in it, you reduce the drag coefficient, thereby increasing the terminal velocity. By making the parachute bigger, or altering its shape, you increase the drag coefficient and thereby reduce the terminal velocity. At question is how to solve for the drag coefficient, c, for a desired terminal velocity, V. Equation 1 can be rearranged by moving the velocity term to the right hand side by

Eq. 2

For a given mass (m) and desired terminal velocity (V) as time approaches a very large value, we can solve for the drag coefficient. Equation 2 is now in the form of a “roots” problem. That is, you need to estimate a value for c that makes the right hand side of the equation equal zero. If this were a polynomial, you could use the binomial theorem to solve for c. However this equation is more complex than a polynomial and it cannot be rearranged to explicitly solve for c. One approach is to simply plot Equation 2 over a wide range of values of c and graphically determine the value of c that makes the value of the function f(c) equal zero. Let’s assume we are designing the parachute for a mass of 68.1 kg, and we want a velocity of 40 m/s after 10 seconds. We can then plug in different values of c and plot f(c) vs c and determine the approximate value of c that makes f(c) = 0. This is shown below:

tmc

ecmg

V 1

Vecmg

cft

mc

10)(

Page 22: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

22

C F(c) 4 34.115 8 17.653 12 6.067 16 -2.269 20 -8.401 Based on this analysis, we can observe that if the drag coefficient is approximately 14.5, the function equals zero. Although you can estimate the root of Equation 1 reasonably well using the graphical approach, it may not be accurate enough for an engineering solution. Another technique that you learned in Calculus is to use “trial and error” to find a value of c to make f(c) equal zero. Using trial and error to search for c, you can get a very accurate estimate of the value of c that makes f(c) equal zero. However, this procedure has to be done by hand, and cannot easily be incorporated into a real-time computer based control system. Numer ical Solution – False Position Method There are many different numerical techniques that use geometry to estimate the root of a function. These methods include Bisection, False Position, Fixed Point Iteration, Newton-Raphson and the Secant method. Numerical techniques are easy to embed in computer-based control programs. They basically work by taking one or more initial estimates of the root and computing better estimates through subsequent iterations. In this short course, we will focus our attention on the False Position method. Let’s now examine how the False Position (FP) method works. Consider the function shown below. For the FP method to work, we must provide two initial guesses of the root, called XL and XU. The only criteria governing the choice of these roots is that XL must be below the real root and XU must be higher than the root. The value of the function evaluated at XL is F(XL) and the value of the function evaluated at XU is F(XU). If F(XL) * F(XU) is negative, then a real root lies between XL and XU. By geometry, a better estimate of the root can be obtained by drawing a straight line between the function at XL and XU and selecting the new root XR as point where this line intersects the X axis. This is shown in the Figure below.

-20-10

010203040

0 10 20 30

Drag Coefficient, cf(c

)

Page 23: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

23

Based on the geometry of the problem, we can develop an equation to compute the new estimate of the root, XR using the method of similar triangles. The first triangle is formed by the points XL, XR and F(XL) while the second triangle is formed by XU, XR and F(XU). We know the values of XL, F(XL), XU and F(XU). We want to compute XR. By similar triangles, we can write the following equation

Eq. 3

Rearranging this relationship to solve for XR gives

Eq. 4

Using Equation 4, we can now compute the new estimate of the root, XR, based on our initial low and high guess of the root. Clearly, this single new estimate of the root a better estimate of the root than XL or XU, however it is not accurate enough for engineering calculations. However, we can now repeat these steps by replacing our original estimate of either XU or XL with the new estimate of the root, XR and solving Equation 4 for a second new estimate of the root. In order to determine if we should replace XL or XU with XR, we must determine if the real root lies in the interval XL to XR or XR to XU. This can be accomplished by taking advantage of the fact that a root lies between two points on a line where the value of the function changes signs. The following rules can be applied to determine how to substitute XR for XL or XU:

XL

XUF(XL)

F(XU)

XR

UR

U

LR

LXX

XFXX

XF )()(

)()()()(

UL

ULUUR XFXF

XXXFXX

Page 24: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

24

A) If the function evaluated at XL multiplied by the function evaluated at XR is negative,

then the root lies between XL and XR, so we set XU = XR. Mathematically, this can be computed by:

If F(XL) * F(XR) < 0 then set XU = XR

B) If the function evaluated at XL multiplied by the function evaluated at XR is positive, then the root lies between XR and XU, so we set XL = XR. Mathematically, this can be computed by:

If F(XL) * F(XR) > 0 then set XL = XR

C) If F(XL) * F(XR) = 0 then the root has been found This is shown in the figure below. Clearly, this newest estimate of the root is better than the previous estimate of the root. The new estimate of the root is moving closer to the actual root of the function. Thus, this method is said to be converging onto the true solution. The more we repeat, or iterate, this method, the more accurate the estimate of the root becomes. Thus, our goal is to iterate the numerical technique until the new estimate of the root converges to a stable value. We now need to establish a convergence criteria so that we know when the answer is accurate enough to terminate the process. There are many different convergence criteria available. The one most often used in numerical techniques is to compute the percent change between the previous and current estimates of the root. When the percent change is below a user defined threshold, then the process is terminated and a root is found. Mathematically, this can be defined as:

XL

XUF(XL)

F(XU)

XR

Page 25: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

25

Where E = percent error XR

i = estimate of the root for the current iteration, i XR

i-1 = estimate of the root for the previous iteration, i-1 100 converts from decimal to percent

100*1

1

iR

iR

iR

XXX

E

Page 26: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

26

Cheat Sheet For False Position Method Step 1: Choose values for XL and XU that bracket the root. This can be verified by multiplying F(XL) * F(XU) to insure the product is negative. Step 2: Estimate the new root by

Step 3: Replace XL or XU with XR

If F(XL) * F(XR) < 0 then set XU = XR If F(XL) * F(XR) > 0 then set XL = XR

Step 4: Compute error between current and previous estimate of the root by

Step 5: Evaluate termination criteria

If E < a user specified value then the root is accurate enough ELSE repeat steps 2-5

)()()()(

UL

ULUUR XFXF

XXXFXX

100*1

1

iR

iR

iR

XXX

E

Page 27: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

27

Example of False Position Method Given: Consider again the problem of designing a drag coefficient for a parachute to limit the velocity of the parachute at a particular point in time. This problem was introduced at the beginning of this lesson. The governing equation is shown below. Let’s assume that the mass of the person and parachute (m) is 68.1 kg and the gravity constant (g) is 9.8 m/s2.

Find: Compute the value of the drag coefficient, c, so that the velocity (v) is 40 m/s after 10 seconds. Solution: Step 1: Choose values for XL and XU that bracket the root. This can be verified by multiplying F(XL) * F(XU) to insure the product is negative. By examining a plot of f(c) vs c, we can see that the root lies around 15. Thus, let XL = 12 and XU = 16. Step 2: Estimate the new root by

The components of this function can be computed for the first iteration by: Plugging these values into Equation 2 gives a root of 14.911313 as shown below

Vecmg

cft

mc

10)(

)()()()(

UL

ULUUR XFXF

XXXFXX

26786.240116

1.68*8.9)(

10*1.68

16

eXF U

0669.640112

1.68*8.9)(

10*1.68

12

eXF L

911313.14)26786.2(0669.6)1612(*26786.2

16RX

Page 28: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

28

Table 1 also shows the results for each iteration of the solution. Step 3: Replace XL or XU with XR

If F(XL) * F(XR) < 0 then set XU = XR If F(XL) * F(XR) > 0 then set XL = XR

We can evaluate the function at XR which was just computed as 14.911303 by plugging in 14.911303 for the coefficient c by

In this iteration, F(XL) * F(XR) = (6.0669) * (-0.2543) = -1.5427. Since this value is negative, we replace XU with XR. So, for iteration 1, the value of XL remains unchanged at 12 and the value for XU is now 14.911303. Since this is the first estimate of the root, Step 4 cannot be applied until the 2nd iteration. Table 1 below shows the results from subsequent iterations of the False Position method.

Iteration XL XU Xr (Root Estimate) Error, E % f(XL) f(XR) f(XL)*f(XR) Comments1 12 16 14.91130318 6.0669 -0.2543 -1.5427 Negative, so replace XU with XR for next iteration2 12 14.9113 14.79419278 0.79160 6.0669 -0.0273 -0.1654 Negative, so replace XU with XR for next iteration3 12 14.79419 14.78169534 0.08455 6.0669 -0.0029 -0.0176 Negative, so replace XU with XR for next iteration4 12 14.7817 14.78036284 0.00902 6.0669 -0.0003 -0.0019 Negative, so replace XU with XR for next iteration5 12 14.78036 14.78022078 0.00096 6.0669 0.0000 -0.0002 Negative, so replace XU with XR for next iteration6 12 14.78022 14.78020564 0.00010 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration7 12 14.78021 14.78020402 0.00001 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration8 12 14.7802 14.78020385 0.00000 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration9 12 14.7802 14.78020383 0.00000 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration

2543.0401911303.14

1.68*8.9)(

10*1.68

911303.14

eXF R

Page 29: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

29

Exercise 2 1. Carry out hand calculations for the first 3 iterations of the False Position method

outlined in the previous example problem. Verify that you can duplicate the results shown in Table 1. Show your work on the next 2 pages. Use the back of these pages for extra room! Note the “FalsePosition” tab in the spreadsheet called “Lesson 2.xls” contains the correct answers as well.

Page 30: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

30

Exer cise 2 Continued

Page 31: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

31

Laboratory 2 Estimation of Bacter ia Levels in the Skunk River

Scope of Work: Advanced Numerical Analysis, Inc. is faced with an environmental problem and we are seeking to subcontract the solution and recommendations to a highly qualified consultant. We routinely monitor the water quality below the Ames municipal waste plant located on the Skunk River, just south of Ames. Environmental regulations require us to limit discharge of bacteria into the river to 9 parts per million (ppm) for safe swimming by humans. Periodically, discharges exceed this rate, and the rate of reduction in bacterial concentration is governed by the equation

tt eec 075.05.1 2570 where c is bacterial concentration (ppm) and t is time in days. We have hired your firm to develop a program to give recommendations to the Ames Municipal Plant on the time required to reduce the bacterial concentration to 9 ppm, making the water safe for swimming. The project will address the following: Task #1. Development of a VBA/Excel program that uses the False Position method to compute the time required to reduce c to 9 ppm. The programs must be well documented and the interface must be easy for us to use. Your program should have the following features: The user should be able to enter two estimates of the root (XL and XU). If there is no

root between these two estimates, the program should warn the user to select different values of XL and XU. You can send the user a warning message by placing the message inside of a message box command in your code. An example is shown below: Response = MsgBox("A Real Root Root Does Not Exist Between Your Estimates")

The user should also be able to enter the acceptable percent error (E) required to terminate the numerical procedure.

The program should print out a table of calculations for each iteration similar to the

table shown for the False Position method in the tab labeled “FalsePosition” in the spreadsheet called “False Position Example.xls”.

The program should print out the final computed value of c to a specific cell in the

spreadsheet.

Page 32: Upload VBA Lesson_1

AE 303 Lesson 2 __________________________________________________________________________________

32

The program should have a spreadsheet that shows a comparison of the estimate of c vs the iteration for each iteration. This graph should be automatically updated as the user changes the model inputs.

Task #2. Store your program in a file called Lab #2-{your name}.xls.

Page 33: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

33

Lesson 3 Solving Systems of Linear Equations

Using Gauss Elimination Introduction Many engineering problems result in systems of linear equations. Consider for example, the following two equations: 3X + 2Y = 18 -X + 2Y = 2 This system of equations is considered “linear” because there are no nonlinear terms (ie. square, cubic, sin, cos, exp, etc) in the equation. Although this system of equations is rather simple, we will use it to demonstrate a powerful numerical technique called Gauss Elimination, that can be used to solve for X and Y. Why not simply use a simple technique, such as plugging these equations into your calculator to compute X and Y? Consider this. Let’s assume that that X and Y are the position of switch settings that are controlled in real time to adjust the steering direction on a Global Positioning Based guidance system on a tractor. In this case, you as the driver would want an automated way to compute X and Y every ½ second to stay on course. If you had to use your calculator to solve this system of equations every ½ second, that would defeat the purpose of an automated steering system. Plus, your fingers would eventually fall off! Numerical solutions are required anytime equations have to be solved in real time in a control system. In fact, your calculator uses numerical methods to compute the solution of equations! Matr ix Formulation This system of equations can be written in matrix form as:

This general form of this equation in matrix notation is [A] {X} = {B} where [A] is the coefficient matrix, {X} is the vector of unknowns and {B} is the vector of constants. The general form of the solution is

218

2123

YX

Page 34: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

34

[A]-1 [A] {X} = [A]-1 {B} Where [A]-1 is called the inverse matrix. The inverse matrix is multiplied on both sides of the equation to directly solve for the unknowns in the {B} vector. If you paid your ISU tuition and took a 3-credit linear algebra course, you would endure countless lectures covering different methods to compute the inverse matrix, [A]-1. Finally, after you are beaten down by the brutality of these methods, you learn that not all matrices can be inverted, and thus, many linear systems of equations cannot be solved using analytical, or traditional, matrix techniques. That’s pretty depressing after you spend all that money to take the course. Gauss Elimination Technique One of the most common numerical techniques used to solve linear systems of equations is Gauss Elimination. Gauss Elimination has two steps:

1) Forward eliminate of unknowns 2) Back substitution

Consider our system of equations

3X + 2Y = 18 Eq. 1

-X + 2Y = 2 Eq. 2 If we multiply Eq. 2 by the value 3 then add Eq. 1 and 2, we eliminate the X term in the new Equation 2’ and thus, can explicitly solve for Y

3X + 2Y = 18 Eq. 1 + -3X + 6Y = 6 Eq. 2

____________ 0X + 8Y = 24 Eq. 2’

Equation 2’ can now be rearranged to directly solve for one of the unknowns, Y = 3. This is called forward elimination. We can now use back substitution to substitute the value Y=3 back into Eq. 1 or the original Eq. 2 to explicitly solve for X by: 3X + 2(3) = 18 X = 4

Page 35: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

35

The concept of forward elimination takes advantage of the fact that linear equations can be multiplied by linear factors or added and subtracted together without altering their solution. Example of Gauss Elimination Eq. 1 3X – 0.1 Y – 0.2 Z = 7.85 Eq. 2 0.1X + 7Y – 0.3 Z = -19.3 Eq. 3 0.3X – 0.2Y + 10 Z = 71.4 Forward Elimination Step Multiply Eq. 1 by 0.1/3 to give Eq. 1’ and subtract Equation 1’ from 2.

Now multiply the original Eq. 1 by 0.3/3 to give Eq. 1’ and subtract Eq. 1’ from Eq. 3

These two steps reduce our system of equations to the following:

Thus, we eliminated X from Equations 2 and 3. We now need to eliminate the Y term from Equation 3 by multiplying Equation 2 by (-019)/(7.0033) and subtracting equation 2 from equation 3

615.7002.1019000.00

85.72.01.0333.0

4.71102.03.0

ZYX

ZYX

ZYX

615.7002.1019000.00

85.72.01.0331.0

3.193.071.0

ZYX

ZYX

ZYX

615.7002.101900.05617.192933.00033.785.72.01.03

ZYZY

ZYX

0843.7002.10

5617.192933.00033.70033.7

19.0615.7002.101900.0

Z

ZY

ZY

Page 36: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

36

This reduces our system of equations to

Back Substitution Step We can now apply step 2 of the Gauss method by solving for Z using equation 3, then back substituting Z into equation 2 to solve for Y, then back substituting Z and Y into Equation 1 to solve for X. From Equation 3,

Z = (70.0843)/(10.02) = 7.00003 Plugging Z into Equation 2, we can solve for Y by 7.0033Y – 0.293333(7.00003) = -19.5617 Y = -2.5 Plugging Z and Y into Equation 1 gives

3X – 0.1(-2.5) – 0.2(7.00003) = 7.85 X = 3.0 Thus, using Gauss Elimination we find that X = 3.0, Y = -2.5 and Z = 7.00003. Gauss Elimination Algor ithm The Gauss Elimination method uses forward elimination as well as back substitution. However, Gauss Elimination can experience problems if the pivot element is 0.0 (you get a divide by zero error) and can have problems with roundoff errors when the equations have coefficients that are different by orders of magnitude. Thus, modern implementation of this technique first rearranges the equations so that there are no zeroes on the diagonal of the matrix representation. It also scales each equation by the largest coefficient to eliminate problems with roundoff error.

0843.7002.105617.192933.00033.785.72.01.03

ZZY

ZYX

Page 37: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

37

Exercise #3 Gauss Elimination for Solving Systems of Linear Equations

Use Gauss Elimination to solve for X1, X2 and X3 in the following system of equations. Show your work below. Substitute your answers back into the original equations to insure you have the correct solution. 4X1 + X2 – X3 = -2 5X1 + X2 + 2X3 = 4 6X1 + X2 + X3 = 5 Solution:

Page 38: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

38

Laborator y #3 Gauss Elimination with Partial Pivoting

Introduction The purpose of this laboratory is for you to develop a spreadsheet that uses a VBA library to compute the solution of a matrix using Gauss Elimination with partial pivoting. The general form of a system of linear equations represented by a matrix is: [A] {X} = {B} Where [A] is the coefficient matrix, {X} is the vector of unknowns and {B} is the vector of constants. The spreadsheet template for this lab is stored in a file called “Lab #3-Gauss.xls”. Open this file and examine the contents carefully. You will see different tables that are to either be entered by the user or computed by the program. In Step 1, the user must enter the dimension of the [A] matrix (ie. number of rows and columns) and a tolerance. In step 2, the user must enter the [A] matrix and {B} vector values for a particular problem. In Step 3, the VBA program is run and the modified [A] matrix and {B} vector are sent from the VBA program back to the spreadsheet after the forward elimination process has been performed. In Step 4, the program writes the solution vector back to the spreadsheet and these can be plugged back into the original equations to insure they are the correct values. Now, open the VBA editor and locate the VBA modules that have been stored with this spreadsheet. You will notice that the first subroutine is called SUB Solve() This is the main subroutine that will read inputs from the spreadsheet, pass these inputs to the GAUSS subroutine, and write all outputs back to the user. This subroutine has intentionally been left blank. The goal of this lab is for you to complete the code in the Solve() subroutine. Notice there are four additional subroutines that are defined below: GAUSS – this is the main subroutine that performs Gauss Elimination with partial pivoting. It calls other subroutines in the numerical library as needed. ELIMINATE – This subroutine conducts forward elimination PIVOT – This subroutine performs pivoting, or rearranges and scales the system of equations to avoid divide by zero errors.

Page 39: Upload VBA Lesson_1

AE 303 Lesson 3 __________________________________________________________________________________

39

SUBSTITUTE – This subroutine performs back substitution and the array X contains the solutions. These four subroutines are complete, and work perfectly. In order to link your main program, SOLVE() to the GAUSS subroutine, all you have to do is use the CALL statement to call the GAUSS subroutine (be sure to pass in the correct arguments). Procedures Develop the code required in the subroutine SOLVE to perform the input, output and call the GAUSS subroutine. Test your program on the matrix problem that you solved by hand in Exercise #3. Test your program on the following bigger matrix:

The correct answer should be:

X1 = 6.1538 X2 = -4.6154 X3 = -1.5385 X4 = -6.1538 X5 = -1.5385 X6 = -1.5385

Save your work as “Lab #3-{your last name}.xls”.

20000000

654321

051

100

020010515010100100000010011010

00111

XXXXXX

Page 40: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

40

Lesson #4 Matr ix Inversion Using Excel

Introduction Consider the following system of linear equations:

This general form of this equation in matrix notation is [A] {X} = {B} where [A] is the coefficient matrix, {X} is the vector of unknowns and {B} is the vector of constants. The general form of the solution is [A]-1 [A] {X} = [A]-1 {B} Where [A]-1 is called the inverse matrix. The inverse of a matrix is defined as a matrix that can be multiplied by the [A] matrix to yield the identity matrix, which is a matrix in which all entries are zero except the diagonal coefficients, which are exactly 1.0. Mathematically, this means [A] [A]-1 = [I] an example of I for a 3x3 matrix is:

The inverse matrix is multiplied on both sides of the equation to directly solve for the unknowns in the {B} vector. If a matrix has an inverse, then this classical analytical approach can be used to solve for the vector of unknowns.

218

2123

2

1XX

100010001

Page 41: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

41

Example of Matr ix Multiplication Consider the following matrix two matrices:

If we multiply the [a] matrix by the [b] matrix, we get the [c] matrix. The entries of the [c] matrix can be computed by the following: c11 = a12 * b11 + a12 * b21 c12 = a11 * b12 + a12 * b22 c21 = a21 * b11 + a22 * b21 c22 = a21 * b12 + a22 * b22 Consider the matrix [A] and its inverse [A]-1

Show that [A] [A]-1 = [I]

Inver ting a Matr ix Using Microsoft Excel Microsoft Excel has several built in features to invert a matrix. The method and commands are outlined on the next page.

2221

1211

2221

1211

2221

1211cccc

bbbb

aaaa

125.15.2

5432 1AA

1001

)1*55.1*4)2*55.2*4()1*35.1*2()2*35.2*2(

125.15.2

5432

Page 42: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

42

Page 43: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

43

Data Secur ity and Encryption Matrices and matrix inversion is widely used in our world to move data or voice signals around electronically in a secure manner. Data is encrypted by multiplying the message by a matrix, then it is unencrypted by multiplying the message by the inverse of the encryption matrix. This technique is used on the internet, in voice communications systems, and for military commands, such as the commands used to fire nuclear missiles. How can we use matrices to encrypt a message? Step 1: First, we assign a numer ic code to each letter in the alphabet: Blank = 0 G = 7 N = 14 U = 21 A = 1 H = 8 O = 15 V = 22 B = 2 I = 9 P = 16 W = 23 C = 3 J = 10 Q = 17 X = 24 D = 4 K = 11 R = 18 Y = 25 E = 5 L = 12 S = 19 Z = 26 F = 6 M = 13 T = 20 Step 2: Convert the message to an uncoded row matr ix. Let’s assume that we want to use a 3x3 matrix for encryption. Let’s also assume that we want to send the message “Meet me on Monday”. Since we are going to use a 3x3 matrix, we convert the text string into groups of 1x3 matrices as shown below: [MEE] [T_M] [E_M] [OND] [AY_] Now create the associated numerical representation for each letter as a series of 1x3 matrices as shown below: [13 5 5] [20 0 13] [5 0 13] [15 14 4] [1 25 0] Step 3: Encode the message We can now multiply each 1x3 matrix with a 3x3 encoding matrix. This scrambles the message in such a way that noone can read it. Let our encoding matrix be

Page 44: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

44

To encode the first 1x3 matrix, [MEE] or [13 5 5], we multiply it by the encoding matrix A as shown below:

Now, the 1x3 matrix [13 5 5] has been encrypted to [13 –26 21], which cannot be translated back to letters due to the negative number. Now let’s encrypt the second 1x3 matrix [T_M] or [20 0 13] following the same approach:

411311221

A

212613

)4*53*52*13()1*51*52*13()1*51*51*13(

411311221

5513

125333

)4*133*02*20()1*131*02*20()1*131*01*20(

411311221

13020

Page 45: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

45

Now let’s encrypt the third matrix [E _ M] or [5 0 13] by

Now encrypt the fourth matrix [O N D] or [15 14 4]

Finally, let’s encrypt the last part of our message, [A Y _] or [1 25 0]

422318

)4*133*02*5()1*131*02*5()1*131*01*5(

411311221

1305

56205

)4*43*142*15()1*41*142*15()1*41*141*15(

411311221

41415

772324

)4*03*252*1()1*01*252*1()1*01*251*1(

411311221

0251

Page 46: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

46

We have now encrypted our message as summarized in the Table shown below. The encrypted message cannot be translated by simple observation because it has been scrambled by matrix multiplication! Original Message Original Message

as Mathematical Representation

Encrypted Message

[M E E] [13 5 5] [13 –26 21] [T _ M] [20 0 13] [33 –53 –12] [E _ M] [5 0 13] [18 –23 –42] [O N D] [15 14 4] [5 –20 56] [A Y _] [1 25 0] [-24 23 77] Step 4. Decode the message with matr ix inversion In order to decode the message, we need to multiply the encrypted message by the inverse of the encryption matrix. This means that the person trying to decode the message must know what the encoding matrix was, and the encoding matrix must have an inverse. The inverse of the encryption matrix, [A] is

We can now decode each 1x3 encrypted matrices by multiplying by the inverse matrix as shown below:

4105618101

1A

EEM55134105618101

212613

ME _13054105618101

422318

Page 47: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

47

We can now peace the decoded 3x1 matrices back together into the original message that says “Meet Me Monday”. Secure Systems The beauty of this encryption technique is that the only way to unscramble the message is to know what the encryption matrix is. Think about this for a minute. If I’m encrypting messages, I can use a 1000 x 1000 matrix as the encryption matrix if I choose to do so. Someone trying to unscramble my message must use a super fast computer and try every combination of matrix sizes, and every combination of matrix coefficients (even up to infinity!) in order to crack the code. While doing this, they would have to be watching the decoded message to see when the message is unscrambled. This drive for security is one of the factors that pushed the government to spend a lot of research money in developing faster computers to increase the rate at which we can “crack the code” of encryption.

MT _130204105618101

125333

DNO414514105618101

56205

_02514105618101

772324 YA

Page 48: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

48

Laborator y #4 Data Encr yption

One of the rising problems in agribusiness companies deals with data encryption for secure electronic data transfer across the world wide web. Consider the problem of a company called mPower3/Emerge (web address is http://www.mpower3.com). They have developed a crop and field database system called xPress that will allow producers, consultants, or vendors conducting business with a producer to enter data about the producer’s operation. The goal of this product is to serve as a central warehouse for producer information to help with organization, record keeping, conservation program compliance and legal defense. One of the problems in storing information across the WWW is data security. Encryption is a technique that involves scrambling a message on the user’s end, sending the scrambled message across the web to the client’s computer, where the information is then unscrambled and stored. This process can be performed using matrix theory. Your assignment is to create a VBA program that allows the user to

input a text message using an input box (InputBox) translate or encode the message into a numeric code group the message into 3x1 matrices encrypt the message using a 3x3 matrix un-encrype the message using the matrix inverse reformulate the original message

Begin with the Lab #4-Encryption.xls spreadsheet. You will note that the encryption matrix [A] and inverse [A]-1 are given, as well as several columns and a button to run your encryption program. The skeleton of the encryption program is also given, with the character to numeric conversion for characters. Your job is to complete this program, and write intermediate calculations back into the spreadsheets in the appropriate columns. Here is what should be contained in the columns: Message – located in cells F9:F100. This column is tied to an internal Excel variable called “Message”. This column should contain the original message. Each row should contain a single character of the message. Transcribe – Located in cells G9:G100. This column is tied to an internal Excel variable called “Transcribe”. It should contain the numeric representation of the message. Each row should contain a single character of the message. Encrypted – Located in cells H9:H100. This column is tied to an internal Excel variable called “Encrypted”. It should contain the encryption associated with each transcribed character.

Page 49: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

49

Decode - Located in cells I9:I100. This column is tied to an internal Excel variable called “Decode”. It should contain the decoded number associated with each encrypted character. Message - located in cells J9:J100. This column is tied to an internal Excel variable called “Message2”. This column should be computed by translating the numbers in the “Decode” column back into characters. Finally, you should put your message back together into a single text string and pass the message back to Excel using a MsgBox. Checking Your Work Check your work carefully. You should try typing in many different messages and insure that the Message columns in cells F9:F100 and J9:J100 match. What to Turn In Save your program in a file called “Lab #4-{your name}.xls.

Page 50: Upload VBA Lesson_1

AE 303 Lesson 4 __________________________________________________________________________________

50

Some Useful Visual Basic for Applications Commands InputBox – sends a message box to the screen and binds the user input message to a variable on the left hand side of the = sign. Example: Dim message as String

message = InputBox(prompt, "Input Message to Encode") Len – Returns the length of a string Example: Dim message as String Message = “Today is Monday”

Length = Len(message) Returns Length as 15

Ucase – converts a string of characters to uppercase characters Example: message = UCase(message) Mid (str ing, position to begin, number of characters to read) – Returns a specific character or group of characters within a text string Example M(i) = Mid(message, 4, 1) Returns the 4th character of the string “message” Example M(i) = Mid(message,4,3) Returns 4th, 4th and 6th characters in the string “message” MsgBox – sends a message box to the user. In the example below, the variable Msg is defined as a text string and contains the message that will be sent to the user in a message box. The variable Style is always set to vbOK, and is the variable that pops up the OK and Cancel button in the message box. The variable Title contains the title that will be located at the top of the message box. Example:

Msg = “Hello World” Style = vbOK Title = “Message Decoded” Response = MsgBox(Msg, Style, Title)

Page 51: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

51

Lesson 5

Linear Regression Introduction Curve fitting is very important to Engineers, who often collect vast quantities of data to define more fundamental relationships to be used for engineering design. We often fit curves to data in order to describe the general trend in data. Least Squares Regression is the most common technique of curve fitting. Least Squares Regression Consider the data shown in the figure below. These data were collected through laboratory trials and each have error associated with it. As an engineer, you would like to fit a line through this data to mathematically describe this relationship. Least squares is the most common technique to compute the coefficients of the best fit line.

What we desire is to develop an equation that gives the best approximation of each y value over the range of x and y values. Thus equation describing the true value of each y point is

Eq. 1

where y = true value of y ao = intercept of the line

0

2

4

6

8

10

12

0 2 4 6 8 10

exaay 10

Page 52: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

52

a1 = slope of the line e = residual error between the linear model and the true y value The Best Fit line is the one that minimizes the square error (ie. e2) between each pair of predicted and measured values of y. Mathematically, we can define the sum of the residual error, Sr as

Eq. 2

Where n is the number of data points. Since yi model = ao + a1 x, we can substitute this into the previous equation to get

Eq. 3 How do you determine the coefficients a0 and a1 for the best fit line? We take the partial derivative of Sr with respect to each coefficient, set the partial derivative to zero, and solve for the coefficients.

Eq. 4

Eq. 5

Now, taking the partial derivative of Sr with respect to a1 gives

Eq. 6

Eq. 7

)1(*21

100

n

iii

r xaayaS

2

110

n

iimeasuredir xaayS

2

1 1mod

2n

i

n

ielimeasurediir yyeS

n

iii

r xaayaS

110

0

2

)(*21

101

i

n

iii

r xxaayaS

i

n

iii

r xxaayaS *2

110

1

Page 53: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

53

Now, set the partial derivatives of Eq. 5 and Eq. 7 to zero gives:

Eq. 8

Eq. 9

Rearranging Eq. 8 and 9 gives

n

ii

n

ii yaxan

11

10 Eq. 10

i

n

ii

n

ii

n

ii yxxax

11

20

1

Eq. 11

This gives us 2 equations and 2 unknowns. Note that we know the x and y values, but we do not know the coefficients a0 and a1. We can now solve Eq. 10 and 11 explicitly for the coefficient a0 and a1 by

Eq. 12

Eq. 13

n

iii

r xaayaS

110

0

20

i

n

iii

r xxaayaS *20

110

1

2

11

2

1111

)(

n

ii

n

ii

n

ii

n

ii

n

iii

xxn

yxyxna

xaya 10

Page 54: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

54

Example: Compute the coefficients of the best-fit line for data shown below.

xi yi xi * yi xi2

1 0.5 0.5 1 2 2.5 5 4 3 2 6 9 4 4.5 16 16 5 3.5 17.5 25 6 6 36 36 7 5.5 38.5 49

Sum = 28 Avg = 4

Sum = 24 Avg = 3.43

Sum = 119.5 Sum = 140

Solution: First, compute columns 3 and 4 and the sum of all columns. Next, plug in the appropriate values into Eq. 12 and 13 to compute a0 and a1.

Thus, the equation of the best-fit line is

2

11

2

1111

)(

n

ii

n

ii

n

ii

n

ii

n

iii

xxn

yxyxna

8392857.0)28()140(7

)24(28)5.119(721a

07142857.0)4(8392857.042857.3

10 xaya

xy 8392857.007142857.0

Page 55: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

55

Quantification of Er ror of Linear Regression The sum of squares of the r esidual, Sr is defined in Eq. 14. This is the error between the predicted y and measured y values squared and summed over all datapoints. If the model fits the data perfectly, Sr would be zero. If the model does not fit the data very well, the Sr value would be very high.

Eq. 14

Where n = number of datapoints yi = measured y values xi = measured x values a0 = intercept of best fit line a1 = slope of best fit line The standard deviation of the best-fit regression line can be computed by Eq. 15

The standard deviation of the regression line can be interpreted in the same was as the standard deviation of a population. Thus, based on Chebyshev’s rule:

A. Approximately 68% of the data points will fall with 1 standard deviation of the line

B. Approximately 95% of the data points will fall with 2 standard deviations of the line

C. Essentially all the measurements will fall with 3 standard deviations of the line

The total sum of squares of the error between the data and the mean of the data by

Eq. 16

St describes the total error (squared) you would have if you represented the relationship between x and y using the mean value of y rather than a regression line.

2

110

n

iimeasuredir xaayS

2/ nSS r

yx

n

iit yyS

1

2)(

Page 56: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

56

The value (St – Sr) is the improvement or reduction in error by describing the relationship of y to x using a regression line rather than just the mean value of y. The Coefficient of Determination, r2, is another way to characterize the error between predicted and measured y values. This can be computed by

Eq. 17 The Coefficient of Determination can be interpreted as the percent of the variation between predicted and measured y values that can be explained by the best-fit regression line. The r2 value ranges from 0-1.0. A value of 0 means that none of the variation can be explained by the regression, where a value of 1.0 means that 100% of the variation can be explained by the line. This means that the line falls through every datapoint.

t

rt

SSSr 2

Page 57: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

57

Exercise 5 The size of a lake depends on accurate estimates of water flow in the river that is being impounded. For some rivers, long historical records of water flow is difficult to obtain. In these cases, meteorological data on precipitation is often used to estimate river flow rate. The following data are available for a river that is to be dammed.

A) Develop an Excel spreadsheet to develop the best-fit line that describes flow as a function precipitation.

B) Compute the standard deviation, Sx/y and the coefficient of determination, r2 of the best fit line

C) Save your spreadsheet in a file called Exercise #5-{your name}.xls Rainfall, cm Flow rate, m3/s

88.9 114.7 101.6 101.6 104.1 104.1 139.7 139.7 132.1 132.1 94.0 94.0

116.8 116.8 121.9 121.9 99.1 99.1

Page 58: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

58

Laboratory 5 Filter ing Data: The Sleepy Student Sensor

Introduction One use of linear or polynomial regression is to filter data that is being read from a sensor in real time. Consider the brain wave function shown in Figure 1. During one phase of deep sleep, the long brain wave produces a voltage that appears as a sine wave. Under some medical conditions, however, there may be distortions in the brain wave that are caused by disorders, as shown in Figure 2. A system is needed to sound an alarm whenever a distorted signal is received. Your task is to develop a program that reads sensor values every second, determines if the reading is distorted and sounds an alarm if the reading is distorted.

Theory It is simple to examine Figure 2 visually and determine when a distortion in the brain wave occurs. The idea behind this alarm system is to use linear regression to predict when a reading is distorted. The algorithm for doing this follows: Step 1: Read in 1st, 2nd and 3rd sensor

readings Step 2: Compute the best-fit line through

the first 3 readings. This will yield an equation Ye = a0 + a1*X

Step 3: Use the best fit line to estimate

the value of the next sensor reading, Ye. Step 4: Read in the 4th sensor value (Ya) and compare it to the estimated value (Ye).

Figure 1. Brain Wave Voltage over Time

-1.50

-1.00

-0.50

0.00

0.50

1.00

1.50

0 500 1000 1500 2000

Cycles

Vol

tage

, mv

Figure 2. Distorted Brain Wave

-2.50-2.00-1.50-1.00-0.500.000.501.001.502.002.50

0 500 1000 1500 2000

Cycles

Vol

tage

, mv

Fit linear regression through first 3readings, then predict the 4th reading

Best Fit L

ine

1 2 3 4

Ye = Estimate of 4th reading

Ya = Actual 4th reading

If ABS(Ye-Ya) < thresholdthen reading is not distorted

Page 59: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

59

Step 5: If ABS(Ye-Ya) < a threshold value, then the 4th sensor reading is not distorted. If the ABS(Ye-Ya) is greater than a threshold, then the 4th reading is distorted and an alarm should sound (beep).

Step 6: Thus it is a good value, and can

be combined with readings 2 and 3 used to compute the next “best fit line” for readings 2, 3, and 4.

Step 7: Write various outputs to the screen as indicated in next section of lab.

Step 8: Determine the next set of 3-values to fit a line through. If the 4th sensor

reading is within the allowable threshold and deemed “not distorted”, then select sensor readings 2, 3, and 4 for the next regression and proceed back to Step 2. If the 4th sensor reading is greater than a threshold, then the 4th sensor reading is deemed “distorted”. In this case, select the 2nd, 3rd and the estimate of the 4th sensor reading to compute the next best-fit line, and proceed back to Step 2. Note that if the distorted 4th sensor reading is allowed to be a part of the next best-fit line, the slope of the line would be distorted and the estimate of the 5th sensor reading would be distorted.

Program Inter face The program interface should be designed to convey the maximum amount of information so that you can view key sensor values, computations, and the sensor readings graphically. The file “Lab #5-sleepy.xls contains the interface for this project. Cells B4-B8 contains key input information for your program.

Best Fit L

ine fo

r last 3

readin

gs

1 2 3 4 5

Ye = Estimate of 5th reading

Ya = Actual 5th reading

If ABS(Ye-Ya) > thresholdso the reading is distorted

1 2 3 4 5 6

Use Estimate of 5th reading rather thanactual 5th reading which was distorted tocompute next regression line

Previous regression line

New Regression Line

Page 60: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

60

Cell B4 - contains an ASCII text file that contains the sensor readings in it. We are using this file to represent the sensor input because our computers are not equiped to read in sensor inputs from ports (That’s AE 404 stuff). You can open this text file with Microsoft WordPad. If you open this in Microsoft Word, do not save it, as Word does not save files in ASCII or Text format (Unless you select that option). You have two files available for development and testing. The text file called SENSOR1.DAT contains a normal brain wave curve. There are no distortions. The file called SENSOR2.DAT contains a nearly perfect sin wave, but each data point has been moved randomly +/- about 10% from its desired value. This represents a more realistic brain wave, with some noise, but no distortions that should be detected by your program. The file called SENSOR3.DAT contains a distorted brain wave file that your program must be able to diagnose. Cell B5 – contains the time between readings. If this were a real instrumentation system, you would poll the sensor input port on your computer every specified time interval. This is the input that controls how often you poll the sensor, or in the case of this lab, read the sensor inputs from the input datafile. The units are seconds. Cell B6 – This input contains the number of sensor readings to display in the data table. For debugging purposes, you may want to set this value high, so that you can track many readings. However, as a system’s monitor, someone may want to supress output and only view the previous 10 or 20 values. Cell B7 – This cell contains the number of sensor readings to be used for the linear regression. Cell B8 – This cell contains the threshold, in mV that is used to determine if a reading is distorted from its expected value. The table in cells B10:F35 contains the desired output for your program. The “Previous Reading” column (E10:E35) contains sequential numbers from 1 to the value in cell B6. The data in columns C and D are the X and Y values of the sensor readings. The data in column E is the calculated error between the actual Y value and the estimated Y value. The data in column F is either 0 or 1.0. A 0 indicates that the sensor reading is normal, and a 1.0 indicates that the reading is distorted and corresponds to an alarm sound (beep). Finally, your interface should have a visual graph that displays in real time the sensor readings. The graph shown in LAB #5-sleepy.xls is a vertical bar chart. The Y and X axis ranges have been preset for the data ranges in this project. You may change these if necessary.

Page 61: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

61

The VBA Pr ogram The goal of this lab is to develop a VBA program to perform checks on data and sound an alarm if the data are out of the expected range. In order to accomplish this, you will need to use some new VBA commands. OPEN – opens a text file for input or output. Example

Filename = “sensor1.dat” Open FileName For Input As #1

EOF – indicates when the end of a file is reached. It is helpful in a loop that should terminate when the last entry in a file is read. Example

Do While Not EOF(1) … …. Loop

INPUT # - Allows you to read in a value from a datafile Example

Input #1, x, y ‘Reads in x and Y value from file #1

TIMER - Returns a Single representing the number of seconds elapsed since midnight. It can be used in a loop to pause the program for a desired length of time before proceeding.

Example PauseTime = Range("B5").Value 'Sets time between readings Start = Timer ' Set start time. Do While Timer < Start + PauseTime DoEvents ' Yield to other processes during delay Loop

BEEP – sounds a Beep. The volume depends upon the computer characteristics.

Program Evaluation You are given a proposed interface in file “LAB #5-Sleepy.xls”. You are also given the following four files in the same directory containing brain waves: SENSOR1.DAT – perfect sin wave SENSOR2.DAT – sine wave with 20% noise, but no distortions SENSOR3.DAT – sine wave with distortions SENSOR4.DAT – sin wave with 50% noise, but no distortions

Page 62: Upload VBA Lesson_1

AE 303 Lesson 5 __________________________________________________________________________________

62

Develop the program and evaluate the behavior of the program for each of the sensor data files. What to Turn In Save your program in a file called “Lab #5-{your last name}.xls Write a brief description of how your program behaved for each sensor file. Do this in Microsoft Word and save it in a file called Lab #5-{your last name}.doc Your lab write-up should include the following: Analysis of Results – Your discussion should include, but not be limited by the following: Run your program for each sensor (SENSOR1.DAT, SENSOR2.DAT,

SENSOR3.DAT) What values did you use for thresholds? Can a threshold set for SENSOR1.DAT or SENSOR2.DAT be used to detect the

distortions in SENSOR3.DAT? What problems do you encounter in adjusting the threshold for SENSOR4.DAT?

Does the threshold that works for SENSOR4.DAT work for SENSOR3.DAT? What is the effect of changing the number of datapoints used for the best fit line?

Explain mathematically. How would you estimate the maximum amount of noise that can be in the wave

before you cannot pick up the distortions? What would you suggest to improve this process for noisy data (say, 50% noise)? What other thoughts or analysis should you include as the designing engineer?

Page 63: Upload VBA Lesson_1

AE 303 Lesson 6 __________________________________________________________________________________

63

Lesson 6 Polynomial Regression

Introduction We can extend the Least Squares approach to develop the best-fit polynomial for a set of data. Consider the general form of a 2nd order polynomial

y = a0 + a1x + a2x2 + e Eq. 1 where e is the residual error between the predicted y value using Eq. 1 and the measured y value in for a given x value. The sum of the residual error, Sr can be computed by

Eq. 2 From calculus, you remember the minimum of a function is the point where the first derivative equals zero. By taking the partial derivative of Sr with respect to each coefficient a0, a1 and a2, we can find the coefficient values that force the partial derivatives to zero, thus defining the polynomial the minimizes error between predicted and measured y values. Taking the partial derivative with respect to a0 gives

Eq. 3

Now, taking the partial derivative of Sr with respect to a1 gives

Eq. 4

Now, taking the partial derivative of Sr with respect to a2 gives

Eq. 5

2

1

2210

n

iiiir xaxaayS

n

iiii

r xaxaayaS

1

2210

0

2

i

n

iiii

r xxaxaayaS *2

1

2210

1

2

1

2210

2

*2 i

n

iiii

r xxaxaayaS

Page 64: Upload VBA Lesson_1

AE 303 Lesson 6 __________________________________________________________________________________

64

Setting the partial derivatives in Eq. 3, 4, and 5 and rearranging gives the following system of equations:

iii yaxaxan 22

10 Eq. 6

iiiii yxaxaxax 23

12

0 Eq. 7

iiiii yxaxaxax 22

41

30

2 Eq. 8 Since the xi and yi values are data, and the number of datapoints (n) is known, we are left with 3 equations and 3 unknowns, namely a0, a1 and a2, which are the coefficients that define the best fit polynomial through the data. We can use a matrix approach to solve for the coefficients by

ii

ii

i

iii

iii

ii

yxyx

y

aaa

xxxxxxxxn

22

1

0

432

32

2

Eq. 9

You can now use a numerical method to solve for the coefficients. Quantification of Er ror of Linear Regression The sum of squares of the r esidual, Sr is defined in Eq. 14. This is the error between the predicted y and measured y values squared and summed over all datapoints. If the model fits the data perfectly, Sr would be zero. If the model does not fit the data very well, the Sr value would be very high.

Eq. 10

Where n = number of datapoints yi = measured y values

2

1

2210

n

iiimeasuredir xaxaayS

Page 65: Upload VBA Lesson_1

AE 303 Lesson 6 __________________________________________________________________________________

65

xi = measured x values a0 = intercept of best fit line a1 = linear coefficient a2 = non-linear coefficient The standard deviation of the best-fit regression line can be computed by Eq. 11

The standard deviation of the regression line can be interpreted in the same was as the standard deviation of a population. Thus, based on Chebyshev’s rule:

D. Approximately 68% of the data points will fall with 1 standard deviation of the line

E. Approximately 95% of the data points will fall with 2 standard deviations of the line

F. Essentially all the measurements will fall with 3 standard deviations of the line

The total sum of squares of the error between the data and the mean (y with a bar over it) of the data by

Eq. 12 St describes the total error (squared) you would have if you represented the relationship between x and y using the mean value of y rather than a regression line. The value (St – Sr) is the improvement or reduction in error by describing the relationship of y to x using a regression line rather than just the mean value of y. The Coefficient of Determination, r2, is another way to characterize the error between predicted and measured y values. This can be computed by

Eq. 13 The Coefficient of Determination can be interpreted as the percent of the variation between predicted and measured y values that can be explained by the best-fit regression

2/ nSS r

yx

n

iit yyS

1

2)(

t

rt

SSSr 2

Page 66: Upload VBA Lesson_1

AE 303 Lesson 6 __________________________________________________________________________________

66

line. The r2 value ranges from 0-1.0. A value of 0 means that none of the variation can be explained by the regression, where a value of 1.0 means that 100% of the variation can be explained by the line. This means that the line falls through every datapoint.

Page 67: Upload VBA Lesson_1

AE 303 Lesson 6 __________________________________________________________________________________

67

Exercise 6 Develop a spreadsheet to compute the coefficients of the best fit polynomial through the data shown below. Also compute the coefficient of determination. Take advantage of Excel’s matrix features outlined in a previous Lesson. Save your spreadsheet in a file called Exercise #6-{your last name}.xls. X Y 0 2.1 1 7.7 2 13.6 3 27.2 4 40.9 5 61.1

Page 68: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

68

Lesson 7: Time Value of Money

Future Value of Present Money Introduction One of the most important steps in engineering design is computing economics associated with a project. The purpose of this lesson is to introduce the concept of the time value of money. Simple Interest You should be familiar with the concept of simple interest if you have earned interest in a bank savings account or had to pay interest for borrowing money on your credit card. Simple interest is computed by I = i * n * P Eq. 1 I = total interest earned i = interest rate for specific period of time (decimal %) N = number of unit time periods P = amount of money, or principal, for which interest is computed Example: How much interest would you receive at the end of a year if you invested $10,000 in a certificate of deposit at an annual interest rate of 7.0%? Solution: I = i * n * P I = (0.07) * 1 * 10,000 = $700 Thus, at the end of 1 year, you would have the original $10,000 in principal, plus $700 in interest, giving you $10,700. This simple interest calculation demonstrates the concept of the time value of money. The time value of money enters into most business decisions made today. If a company has one million dollars to invest, they must compare investment options against the baseline value that this money would be worth over time. For instance, if they invest this money into developing a new product that will only return 3% per year, this would be a bad decision relative to investing the money in a bank and earning 5% interest.

Page 69: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

69

Compound Interest Interest is often compounded. For instance, you may purchase a certificate of deposit (CD) that compounds interest quarterly. This means that every 3 months, the interest that is earned is added to the principle. Thus, the interest earned during the following 3 months is computed based on the original principal plus the interest accrued during the first 3-month period. Common compound periods are annual, quarterly, monthly and daily. The future value of money (F) can be computed using Equation 2.

Eq. 2

F = future value, $ P = present value, $ i = interest (decimal form) for compounding period n n = number of compounding periods Example: How much interest would you receive at the end of 5 year if you invested $1,000 in a bank certificate of deposit (CD) yielding an annual interest rate of 7% compounded A) annually and B) daily? Solution: If interest is compounded annually, then there are 5 compounding periods (n=5). Using Eq. 2, we can compute the future value as:

F=$1,402.55

If interest is compounded daily, then there are 365 days per year times 5 years = 1825 compounding periods (ie. n=1825). The interest rate per compounding period is (.07/year) * (1 year/365 days). Plugging this into Eq. 2 gives:

niPF )1(

niPF )1(

niPF )1(

5)07.01(000,1$F

5*365

36507.

1000,1$F

Page 70: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

70

F=$1,419.02

Thus, at the end of 5 years, you would have $16.47 more if interest is compounded daily vs annually. By convention, interest rate is always given as the annual nominal interest rate without consideration of the compounding period, unless otherwise stated or explained. Interest rate i is defined as the interest rate per compounding period n. In the previous example, a nominal interest rate of 7% is given, and it is compounded daily. The i term is computed by 0.07/365 days, but the number of compounding periods, n, is 365 days times 5 years. Continuous Compounding Sometimes, interest is compounded continuously, rather than annually, monthly, or daily. If this is the case, the future value (F) or present value (P) of an investment can be computed by

Eq. 3

Eq. 4 Where F = future value of money after n years P = present value of future money after n years n = years r = interest rate that is compounded continuously

Example A bank is selling certificates that will pay $5,000 at the end of 10 years, but pays nothing during the meantime. If interest is compounded continuously at 6%, what price is the bank selling the certificates? Solution: In this problem, we know the future value of the sum of money (F) is $5,000, and we are trying to solve for the present value (P). So, we select Eq. 4.

P = $2,744

rnePF

rneFP

)10*06.0(000,5$ yearsrn eFeP

Page 71: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

71

Effective Annual Interest Rate When money is compounded at smaller intervals than 1-year, the effective annual interest rate is higher than the nominal annual interest rate. The effective annual interest rate can be computed by Eq. 5 Ieff = effective annual interest rate, decimal i = interest rate per compounding period, decimal n = number of compounding periods Example: In the previous example, the nominal annual interest rate i of 7% was given. Find the effective annual interest rate if interest is compounded daily.

Ieff = 0.072501 or 7.2501% Thus, compounding daily gives a 0.25% higher interest rate than compounding annually Example: Consider the previous example. The effective annual interest rate can be substituted for i and the equation can be solved using n=5 years, since the units of Ieff is rate per year. Solution: Use i=7% compounded daily gives:

F=$1,419.02

1)1( neff iI

1)1( neff iI

1)36507.

1( 365effI

niPF )1(

5*365

36507.

1000,1$F

Page 72: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

72

Using Ieff = 7.1205% per year, and n=5 years gives

F=$1,419.02

More Complex Example Consider the money flow shown below. You have $1,000 to invest today, $1500 will be added in 12 months and $2,000 will be added in 24 months. Compute the future value of this money at the end of 36 months using a 7% annual interest rate compounded semi-annually. Solution: There’s no reason to get all excited about this more complex example. We can really view this problem as 3 different problems. For instance, we can use Eq. 2 to compute the future value of the initial $1,000 investment at the end of 36 months. We can then use Eq. 2 again to compute the future value of the $1,500 investment for the last 2-year period. Finally, we can use Eq. 2 again to compute the value of the $2,000 investment for the last year. Finally, we simply sum these future values as shown below. Note that our assumption is that interest, i, is compounded twice per year. Thus, we use (0.07/2) to convert interest from units of per year to twice per year. For the n term, we enter the number of compounding periods.

F = $1,229.255 + $1,721.285 + $2,142.45 = $5,092.99

neffIPF )1(

5072501.01000,1$F

F

0 6 12 18 24 30 36Months

$1,000 $1,500 $2,000

246

207.

12000207.

11500207.

11000F

Page 73: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

73

Present Value of Future Money There are many instances where you are trying to compare financial options by comparing the present worth of future sums of money. We can rearrange Eq. 2 to solve for the present value of future sums of money. The solution follows the same approach outlined previously.

Eq. 6 Example: How much should be invested today to pay for your newborn child’s college tuition? The experts estimate that in 18 years, it will take $200,000 to pay for a 4-year degree. Assume an annual rate of return of 6%. Solution:

P = $70,068.76

Present and Future Value of Uniform Cash Flow Another type of problem involves computing either the present or future worth of an annual (or monthly or daily) cash flow. For instance, you may be interested in computing the future value of 36 monthly rental payments on your rental house. The Figure shown below depicts the annual (A) cash flow payments and the present or future value of the series of uniform cash flows. The following equations provide a way to compute the present or future worth of a uniform cash flow, or the uniform cash flow for a desired present or future sum of money.

niPF )1(

niFP )1(

niFP )1(

18)06.1(000,200$P

F = ?

A A A A A A

P = ?

Page 74: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

74

Sinking Fund Equation (7) Series Compound Equation (8) Capital Recovery Equation (9) Series Present Worth Equation (10) A = an end of period cash receipt or disbursement in a uniform series continuing for n periods, the entire series equivalent to P or F at interest rate i Example: How much should I save monthly to have $200,000 available to pay for my son’s college tuition in 18 years? Assume 6% annual rate of return compounded monthly. Solution: In this case, we want to compute the annual uniform investment (A) required to have a future value (F) of $200,000. Thus, we choose Eq. 7 and solve the problem as shown below. Note, because compounding is monthly, we need to convert the interest rate to a monthly value of (0.06/12), which is the interest rate per month. We also need to solve this problem using n= (12 months per year) * (18 years). Remember that n is the number of compounding periods and i is the interest rate per compounding period.

1)1( nii

FA

ii

AFn 1)1(

1)1()1(

n

n

iii

PA

n

n

iii

AP)1(

1)1(

1)1( nii

FA

Page 75: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

75

A = $513.32 per month

Example: I borrow $100,000 for 30 years at 6% interest to purchase a home. What are my monthly payments? Solution: In this example, we are trying to compute the uniform monthly payment (A) based on a present value (P) of the loan. Note that since A is to be computed on a monthly basis, we need to convert the units of I to monthly (ie. I = 0.06/12 = 0.005) and the units of n must be monthly.

A = $599.55 By paying $599.55 each month for 360 months, I pay a total of $215,838 for the house. Example: What is the future value of that same house payment if I invested the monthly payment at 6% interest for 30 years? Solution: In this example, we know the monthly investment (A=$599.55), and we want to compute the future value (F) of this monthly investment. Thus, we select Eq. 8. Note that since A is on a monthly basis, we need to convert the units of i to monthly (ie. i = 0.06/12 = 0.005) and the units of n must be monthly.

11206.0

1

1206.0

000,200$ 18*12A

1)1()1(

n

n

iii

PA

1)005.01()005.01(005.0

000,100 30*12

30*12A

ii

AFn 1)1(

Page 76: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

76

F = $602,256.99

Example: Your current credit card bill is $3,088. The minimum payment is $62 (2% of balance), and the interest rate is 19%. By paying this minimum payment each month, how long would it take to pay off the balance? Solution: In this case, we know the current value of the debt (P=$3,088) and we are trying to compute the monthly payment (A). So, we select Eq. 9. Since A is on a monthly basis, we must convert interest to a monthly basis and set the units of n to a monthly basis. Solving for n yields n = 99 months or 8 years and 3 months.

005.1)005.1(

55.59930*12

F

1)1()1(

n

n

iii

PA

11219.

1

1219.

11219.

308862 n

n

Page 77: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

77

Present and Future Value of Gradients There are many situations in life and engineering that requires estimating the current or future value of a uniform gradient. The maintenance cost of a car or a piece of equipment. You would expect that the maintenance cost would be low early in the life of the car, and it will increase in a linear fashion as the car ages. If this increase in the maintenance cost increases in a uniform, or linear fashion, the cost can be described by a uniform gradient that increases with age. A uniform gradient has two components. The first component is the underlying annual cost, A, which we examined in the previous section of material. The second component is the annual increase in maintenance cost, beginning with zero in the first year, and increasing in a linear fashion. The yearly increase in the maintenance cost is said to be the uniform gradient. This is shown in the cash flow diagram below. In order to compute the present value of the maintenance cost, we need to compute the present value of the recurring annual cost (A) and the gradient (G). The present value of a gradient can be computed by:

Eq. 11

The gradient G can also be converted into an annual recurring sum A by

Eq. 12

Where

G = uniform gradient, $/time A = annual recurring cost, $/time i = interest rate per compounding period n = number of compounding periods

A

G

P

n

n

in

ii

iGP

)1(11)1(

1)1(1

nin

iGA

Page 78: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

78

Example: How much should you set aside today to pay for the expected maintenance cost of a car for the first 5 years? Assume costs occur at end of each year and you get 5% interest. Solution: The total annual maintenance cost is shown in the table below. The total maintenance can be broken up into a uniform annual cost, A, of $120 per year and a uniform gradient increase of $30 per year. Year Total Maintenance Cost,

$ Uniform Part of Annual

maintenance Cost, $ Uniform Gradient Part of

Maintenance Cost, $ 1 120 120 0 2 150 120 30 3 180 120 60 4 210 120 90 5 240 120 120

Our goal is to compute the present value of both the uniform annual cost (A) and the uniform gradient cost (G). The present value of the uniform annual cost can be computed using Eq. 10 as

The present value of the uniform gradient (G) can be computed using Eq. 11.

Thus, the total amount of money that must be saved today = $519 + $247 = $ 766

P=?

A=$120

G=$30/yr

519$)05.1(05.1)05.1(120$

)1(1)1(

5

5

n

n

iiiAP

n

n

in

ii

iGP

)1(11)1(

247$)05.1(

1505.

1)05.1(05.30$

5

5

P

Page 79: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

79

Exercise 7 1. What amount of money would have to be invested to have $4,000 at the end of three years at a 10% interest rate? 2. Fifty thousand dollars is borrowed at a nominal rate of 8%, compounded quarterly. If no payments are made in the first 3 years, how much will be owed? 3. You negotiate the price of a house to $150,000. You pay 10% as a down payment and finance the balance at 8% for 30 years. You make monthly payments of principle and interest. How much interest do you pay at the end of the 30-year period?

Page 80: Upload VBA Lesson_1

AE 303 Lesson 7 __________________________________________________________________________________

80

4. A local lending company advertises their “51-50: club. A person may borrow $2000 and repay $51 for the next 50 months beginning 30 days after he receives the money. Compute the nominal annual interest rate for this loan. 5. You wish to become a millionaire in 30 years. After careful investigation, you determine that you can obtain an average of 10% nominal interest from careful investment in the stock market. How much money should you invest each month to have accumulated $1,000,000 in 30 years? 6. Make up your own problem that answers a practical question related to repayment of your student loans or purchase of a car.

Page 81: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

81

Lesson 8 Present Worth Analysis

Introduction You are trying to purchase a new piece of equipment. You have several options. Vendor A can sell you the equipment for $5000, with a useful life of 4 years and an annual maintenance cost of $500. Vendor B can provide you with equipment that will last 6 years, cost $7000, with an estimated $400 per year maintenance cost. Which vendor would you choose? Engineers are often faced with making economic decisions such as this. One method to make the decision is to compute the present worth of each alternative, and then select the alternative that has the lowest present worth. This is called Present Worth Analysis (PWA). This technique allows you compare two or more series of cash flows by converting them into their present value equivalents. Example: Story Co. needs to build an aqueduct to bring water from the upper part of the state. There are two alternatives: Alternative 1: The system can be built at a reduced size now for $300 million and be enlarged 25 years later for an additional $350 million. Alternative 2: The system can be built at full size now for $400 million. Assuming a nominal annual interest rate of 6%, which alternative is cheaper? Solution Let’s compute the present worth of the costs associated with Alternative 1. We have an initial investment of $300 million, plus a future cost of $350 million in 25 years. Compute the present value of these costs: PW of cost = $300 million + 350 million (P/F 6%, 25 years) PW of cost = $300,000,000 + $81,548,521 PW of cost = $381,548,521, or about $381.6 million Now, let’s compare this to the present worth of the costs for Alternative 2. In this case, we have the present worth of Alternative 2 is simply the $400 million investment today. Since the cost of alternative 1 is less than the cost of alternative 2, we select alternative 1.

25)06.01(350300cos millionmilliontPW

Page 82: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

82

Different Life Spans In present worth analysis, the useful life of each alternative must be identical. Often, alternatives have different useful lives. Thus, the least common multiple analysis period must be used for PW analysis comparisons when the useful life is different for each alternative. Example: Use present worth analysis to determine which grain elevator is most economical. Elevator 1 Elevator 2 Installation $45,000 $54,000 Service life 10 years 15 years Annual operating cost, $ $2,700 $2,850 Salvage Value, $ $3,000 $4,500 Solution: Since the useful life is different for each elevator, we need to find the least common multiple, which is 30 years. Elevator 1 will have to be installed and replaced 3 times during 30 years due to the 10-year useful life. The cash flow associated with Elevator 1 is shown below.

We need to compute the present worth of all these different cash flows. A simple way to do this is to begin by computing the present worth of one elevator a 10-year useful life.

10 years 20 years 30 years

$45,000

$3,000 $3,000 $3,000

$45,000 $45,000

10 years

$3,000A=2700/yr

Page 83: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

83

Thus, the PW of cost for 1 Elevator is $45,000 + $16,590 - $1,157 = $60,433. Note that we are computing the present worth of costs, so we subtract the salvage value (rather than add it), because it offsets the cost. We now know that it costs $60,433 for Elevator 1 for each of the three 10-year periods. We now need to compute the present worth (in year 0) of the elevators installed in year 10 and 20. The cash flow is shown below:

PW of costs = $60,433 + $60,433(P/F, 10%, 10 yrs) + $60,433(P/F, 10%, 20 yrs) Using Eq. 6, we can compute the present value (P) of a future sum of money (F). The present value (year 0) for the elevator installed at the end of 10 years is

The present value of the future cost of the for the elevator installed at the end of 20 years can also be computed by Eq. 6 as

Plugging this into our present worth of cost equation we get: PW of costs = $60,433 + $60,433( 0.3855 ) + $60,433(0.1486)

PW of cost = $45,000 + $2700(P/A, 10%, 10 yr) - $3,000(P/F, 10%, 10yr)

10

10

)1.01(1.01)1.01(2700P

P = 2700(6.1446) = $16,590

10)1.01(3000P

P = 3000(0.38554) = $1,157

$60,433 $60,433 $60,433

10 years 10 years 10 years

101.01433,60$)1( niFP

201.01433,60$)1( niFP

Page 84: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

84

PW of costs = $60,433 + $23,300 + $8,983 = $92,716 Conducting a similar analysis for Elevator 2 reveals the present worth of cost of $92,459. Since the PW of cost for elevator 2 is lower than the cost of elevator 1, you should select elevator #2.

Page 85: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

85

Exercise 8

1. A farmer manages 600 acres on which he produces corn. He can hire custom harvesters at $35/acre. An adequate combine will cost $90000 and have a service life of 10 years, at the end of which it can be sold for $8000. The estimated operating costs for the combine are $10/acre per year. If the expected annual interest rate is 12%, should the farmer buy his own combine or hire custom harvesters? Use present worth analysis.

Page 86: Upload VBA Lesson_1

AE 303 Lesson 8 __________________________________________________________________________________

86

2. A group of farmers are considering developing a land drainage project. The drainage is needed because the topography of the area is too flat, and the natural stream in the area is too high to provide an outlet for their system at the field edge. They are considering two alternatives to obtain an outlet. Option 1 is to construct a drainage ditch at a very flat grade down the watershed until it is high enough to discharge into the natural stream. This ditch would be approximately one mile long, would cost $50000, would have an annual maintenance cost of $100, and would have a service life of 20 years. Option 2 is to build a pump outlet with sump and lift pumps at the edge of the field to lift the water into the natural stream channel. The pump outlet system would cost $25000, would have an annual operation and maintenance cost of $1000, and would have a service life of 10 years. If the cost of money to the project would be 7% annual rate, which option would be the least expensive for the farmers? Use present worth analysis.

Page 87: Upload VBA Lesson_1

AE 303 Lesson 9 __________________________________________________________________________________

87

Lesson 9 Annual Cash Flow Analysis

Introduction In the previous lesson, we examined how to compare financial alternatives by moving all the cash flow events to the present. An alternative way to compare alternatives is to compute the annual cost of different alternatives by representing all cash flow events as annual costs. This is called the Annual Cash Flow Analysis (ACFA) method. The advantage of this method is that it can be used to compare alternatives that have different useful life spans. This method uses the equations outlined in the first Engineering Economics lesson to compute the equivalent uniform annual cost (EUAC) and equivalent uniform annual benefit (EUAB) for each alternative. Example: Use Annual Cash Flow Analysis to determine which machine is the best selection. Each machine has an estimated life of 10 years, and assume 8% nominal annual interest. Machine 1 Machine 2 Initial Cost $15,000 $25,000 Materials and Labor savings per year $14,000 $9,000 Annual operating costs $8,000 $6,000 End of life scrap value $1,500 $2,500

Machine 1

EUAB = 14,000 + 1500(A/F, 8, 10)

EUAC = 15,000(A/P, 8, 10) + 8,000

1)08.1(08.500,1000,14 10EUAB = $14,104

Benefits

Costs

235,10$80001)08.1(

)08.1(08.15000 10

10EUAC

(EUAB-EUAC) = $14,104 - $10,235 = $3,869Annual Cost

Page 88: Upload VBA Lesson_1

AE 303 Lesson 9 __________________________________________________________________________________

88

Machine 1 has an equivalent annual benefit of $3,869 Machine 2 has an equivalent annual benefit of - $553 Thus, machine 1 is the best alternative, promising a positive cash flow, where machine 2 promises a negative cash flow.

Machine 2

EUAB = 9,000 + 2500(A/F, 8, 10)

EUAC = 25,000(A/P, 8, 10) + 6,000

1)08.1(08.500,2000,9 10EUAB = $9,173

Benefits

Costs

726,9$60001)08.1(

)08.1(08.25000 10

10EUAC

(EUAB-EUAC) = $9,173 - $9,726 = - $553Annual Cost

Page 89: Upload VBA Lesson_1

AE 303 Lesson 9 __________________________________________________________________________________

89

Exercise 9 1. A fertilizer salesman proposes to a farmer that he buy and take delivery of 30 t of fertilizer on July 1 each year at a 10% discount on the regular price of $250/t. Normally the fertilizer is purchased on January 1 and delivered at the time of application in the spring. In order to take advantage of this discount, the farmer must build a storage bin which will cost $2000 initially, and have a 20-year life with an estimated salvage value at the end of that time of $100, and an annual maintenance cost of 8% of the purchase price. Assuming constant prices and interest rates over the 20-year period, should the farmer take advantage of this discount if the expected annual interest rate is 15%? Use Annual Cash Flow analysis.

Page 90: Upload VBA Lesson_1

AE 303 Lesson 9 __________________________________________________________________________________

90

2. A feed mixer is to be purchased by a local feed dealer. He has solicited the bids shown below. Assume the value of his money is 7% compounded monthly. Which model is the most economical? Use Annual Cash Flow analysis. (hint, since interest is compounded monthly, you need to compute the effective annual interest rate Ieff for your analysis). Model A Model B Initial Cost $4,500 $4,250 Annual Repair Cost Year 1 = $200

Year 2 = $200 Year 3 = $200 Year 4 = $200 Year 5 = $200

Year 1 = $200 Year 2 = $225 Year 3 = $250 Year 4 = $275 Year 5 = $300 Year 6 = $325 Year 7 = $350

Salvage Value at end of useful life

$500 $500

Useful Life 5 years 7 years

Page 91: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

91

Lesson 10 User Inter face in Excel and VBA

Introduction Up till now, we have used pretty crude ways to move data between Excel and VBA. We have declared groups of cells in Excel as variables, then read values from Excel into arrays or variables in VBA. While this is functional and probably the fastest way to move data from Excel to VBA, it does not lead to a very user friendly user interface. Control Toolbox You can use the Control Toolbox in Excel to add data inputs, check boxes, list boxes and buttons for user input. The control toolbox may or may not be turned on as a default in Excel. You can turn it on by going to the View menu, selecting the Toolbars item then clicking on the Control item. You will see the toolbar appear. Moving Data from Excel to VBA Forms are used to allow users to input data or select program inputs from a list. Forms usually have a “Run” or “OK” button that is used to run an underlying VBA program that uses the data entered by the user in a program. Below is a flow diagram showing how user inputs in Excel can be read directly by a VBA program that is tied to the Run Model button. The VBA program can also write values back to text boxes or cells in a spreadsheet.

2635

Silver Springs Energy Model

Plants, Kcal/m2

213 Herbivores, Kcal/m2

9

Carnivores, Kcal/m262

Alligators, Kcal/m2

25 Decomposers, Kcal/m2

Initial Energy Levels

Feeding ModelLinear modelnmlkji

Non-Linear Modelnmlkj

Run Model

Private Sub CommandButton1_Click()

‘ Read Inputs from ExcelPlants = TextBox1.ValueHerb = TextBox2.ValueCarn = TextBox3.ValueAllig = TextBox4.ValueDecom = TextBox5.ValueFeedLin = OptionButton1.Value FeedNon = OptionButton2.Value

‘ Add Program Here

End Sub

VBA ProgramExcel User Interface

Page 92: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

92

Laboratory #10 User Inter faces in Excel

Introduction The purpose of this lab is to develop a user interface and model of the falling parachute problem. The majority of the work is in learning how to create forms in Excel, and how to pass data from Excel forms to VBA and back again. Go back to Lesson 1 and review again both the analytical and numerical solution of the falling parachute problem outlined in Equation 3. The analytical solution was derived as

Where V(t) is the velocity at time t g = gravity m = mass c = drag coefficient of the parachute t = time The numerical solution was derived as:

Where Vt+dt = velocity at time t+dt, m/s Vt = velocity at time t, m/s Dt = time step, s Objectives The objective of this lab is for you to create a nice user interface in Excel along with a VBA program to solve for the velocity of the parachute over time.

dtVmc

gVV ttdtt

mtc

ec

mgtV*

1*)(

Page 93: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

93

Methods Step 1. Create a new Excel spreadsheet called Lab #10-{Your name}.xls. Step 2. We are going to add a form directly onto this spreadsheet. Go to the >View>Toolbar menu and select/turn on the Control Toolbox toolbar if it is not already visible on your screen. The Control toolbar is shown to the right. Step 3. You are now ready to go into the form development mode. Click the Design Mode icon (looks like a blue 45o angle square) on the Control Toolbox Toolbar to change modes from design to runtime (ie. exit design mode). In order to add items to your form, you must be in the design mode. In order to run your form, you must NOT be in design mode. Step 4. Let’s now add a textbox that contains the default values for the parachute problem. On the Control Toolbox toolbar, select the TextBox button (ie. the button that has abc in it). Click on this button and then go over to the form and drag and drop a textbox onto your form. This will be the box where the user enters the mass of the parachutist. By default, this is called TextBox1, which is the name you should use in VBA to bind this user input value to a variable in VBA. Hint, you can also add a new textbox by right-clicking on an existing textbox, selecting copy, then selecting paste and move it to a new location. Step 5. Click on the Properties button on the Control Toolbox toolbar (upper right hand button) to turn on the property options for your newly added textbox. You can also view the properties of this textbox by right clicking on the textbox and selecting the properties item. You can then go into this textbox and set the Text Property to whatever default value you want. For instance, if you want the default value to be 68 kg, type in 68 in the Text property. Step 6. Now let’s add a label box to tell the user that this textbox contains the mass of the parachutist. Click on the Label button on the Control Toolbox toolbar (it is the button that says “A”). Then click onto the spreadsheet and drag and drop your new label button. By default, this is LabelButton1. By clicking on your newly added Label Button, you can change the Caption in the Proper ties window to Mass, kg. Step 7. Repeat Steps 5 and 6 to add text boxes and labels for the Drag coefficient, gravity, duration of the simulation and the time step that you want to use to solve the problem using a numerical technique. Your menu should look like the figure shown below (with correct default values).

Page 94: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

94

Step 8. Now, let’s add a set of buttons that allows the user to select between the Analytical or Numerical Solution. From the Control Toolbox toolbar, select the Option Button item (the circle with a black dot in it), and drag and drop a circle on your spreadsheet. On the Properties menu, change the caption to “Numerical Solution” and set the Value to TRUE. The value of “True” sets this Option Button to true as the default value. If the user select a different button, this value will automatically change to false. Step 9. Following the procedures in Step 8, add another button and call it “Analytical Solution”. This will allow the user to switch between the analytical and numerical solutions when running the model. Set the default value for the Analytical Solution button to FALSE in the Properties menu (you don’t want both buttons to initially be true!).

Page 95: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

95

Step 10. Now, let’s add a Command Button to the form so that we can run the program. Click on the Command Button icon on the Control Toolbox (the grey square button) and drag and drop a command button onto your form. In the Properties menu, change the caption to “Run Model”, so that the text on the button tells the user to run the model. Your form should now look like this:

Step 11. We now need to add the Parachute program to your command button, so that when the user clicks on the button, the model will run. From the spreadsheet, double click on the command button and Excel will kicked you into the VBA source code for the command button. You will see the following code that is executed when the command button is clicked:

Pr ivate Sub CommandButton1_Click()

End Sub We now want to add the Parachute model code to the command button’s VBA subroutine, which is called CommandButton1_Click().

Page 96: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

96

Step 12. First, we need to bind the user inputs in the Excel form to variables in VBA. In the VBA surbroutine called CommandButton1_Click90, dimension the following variables and set them to the appropriate text box values: M = TextBox1.Value ‘Mass, kg c = TextBox2.Value ‘drag coefficient, kg/s g = TextBox3.Value ‘gravity, m/s2 dt = TextBox4.Value ‘timestep, s Dur = TextBox5.Value ‘duration of simulation Numeric = OptionButton1.Value ‘true for numeric solution, false for analytical solution Analytic = OptionButton2.Value ‘true for analytical solution, false for numeric solution Step 13. Next, we need to create some logic so that we can either run the analytical or numerical solution. Our internal variables called Numeric and Analytic are logic variables that are either true or false based on the user selection. Thus, we can use an IF-Then loop to determine if the user wants an analytical or numerical solution. This is shown in the following code: If Numeric = True Then ‘ Add numerical solution calculations here End If If Analytic = True Then ‘ Add analytical solution calculation here End If Step 14. Finally, create the code required for the analytical and numerical solutions. Note that you can cut and past the code you developed in Laboratory 1 into this lab. Step 15. Now, add a table in Excel to write the time and velocity back to the spreadsheet for each time step. Add a graph that automatically updates itself showing velocity vs time. Your final interface should look something the one shown below:

Page 97: Upload VBA Lesson_1

AE 303 Lesson 10 __________________________________________________________________________________

97

Step 16. Now, change the status in the Excel Control Toolbox to exit design mode in order to run your form (ie. run the model). Do this by clicking on the “Exit Design Mode” button on the Control Toolbox toolbar (upper left hand symbol that has a 45o triangle on it). Step 17. Run your program and select different options and play around with different variable settings to insure your program runs perfectly. Step 18. Save your program and name it Lab #10-{your last name}.xls.

Page 98: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

98

Visual Basic for Applications Reference Guide

The VBA Programming Environment Visual Basic is a modern version of the BASIC (Beginners All-Purpose Symbolic Instruction Code) computer programming language, developed when personal computers first became popular in the early 1980’s. Visual Basic for Applications is a subset of Visual Basic. It is available in many Microsoft applications including Excel, Word, Access. VBA can be used like any other programming language, such as Fortran to develop programs using an Excel Spreadsheet as the input/output file. VBA has its own programming environment. To get into the VBA programming environment, you start in an Excel Worksheet. From within Excel, select the Tools>Macro>Visual Basic Editor menu items. You may also press Alt+F11 on the keyboard. This will open up the VBA programming environment that should look similar to the one shown below.

Page 99: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

99

Once you are in the VBA environment, you can create a VBA program (called a module) or a user form. To create a VBA program, go to the Insert>module menu item and select module. You will now see a blank screen ready for programming. VBA On-line Help It isn’t as user friendly as it should be, but it is about the only help available, except for what we can provide to each other. To access this help, click on the Help button from within the Visual Basic Editor. Then click on the Contents and Index menu item, and click on the Contents tab. A number of menu items appear. One of the most useful is the Microsoft Excel Visual Basic Reference. This includes a link to the Visual Basic Language Reference, which gives an alphabetical list of aspects of the language such as data types, functions, key words, and statements. It also contains a topic on Getting Started with Visual Basic. You will probably need to become familiar with these.

Page 100: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

100

Wr iting a Subr outine Option Explicit: You begin creating a VBA subroutine, or program by typing command lines on the editor screen. The first line of most programs should be:

Option Explicit Don’t worry about upper or lower case in these lines. The editor will convert as needed when you hit the Enter key. The Option Explicit command will cause the program to check each variable used in the program against the list of explicitly declared variable names and types, and to stop and indicate any variable name it encounters within the program which has not been declared. This is very useful for program debugging, since one common problem in programming is a typing error which appears to be a new variable. You can see the Help for the Option Explicit statement in the Visual Basic Language Reference under the heading of Statements M-Z. Creating a Subroutine: A VBA subroutine is a block of VB code that is executed as a unit. It begins with a header statement and ends with a footer statement. There are three types of VB procedures: Subroutine, Function, and Property. Every subroutine must begin with the SUB command and end with the End Sub command. For instance, you may want to create a subroutine called “Newton”. In order to create a subroutine, you simply click on the open page in the VBA environment and type Sub Newton( ) End Sub You will notice that when you type the Sub command, followed by the subroutine name and parentheses (which are used to pass arguments into the subroutine), the End Sub command automatically appears. Sub procedures in VBA work exactly like Programs and Subroutines in Fortran. A procedure can be called from another procedure using a Call statement which looks like it would in Fortran. A Function procedure is used to determine the value of a variable, in the same manner that a Function subprogram is used in Fortran. Adding Comments: Comments can be entered into the code as independent lines, or following program code on the same line. A comment begins with an apostrophe (‘). All good programs should be adequately documented. A good program should include at least 40 percent comment statements. The comments should clearly indicate what each part of the program is doing, and make reading the program easier. Indenting Code: Program code can be made more readable by using indentions to identify sections of related code. Visual Basic allows lines to be longer than is good for readability. Therefore, it is good practice to break lines so that they will fit on the screen without having to scroll sideways. A space and underscore ( _ ) indicate that the line is being continued on the next line of the program code.

Page 101: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

101

Dimensioning Var iables (DIM) The DIM command is used in VBA to dimension variables. Variables can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, or Variant. If you do not specify a data type, the Variant data type is assigned by default. You can also create a user-defined type using the Type statement. For more information on data types, see “Data Type Summary” in Visual Basic Help. Real Numbers are always dimensioned as double precision numbers by dimensioning them as double. In the example below, the DIM command dimensions the variables X, Y, and Z as real numbers.

DIM X, Y, Z as Double Integer s are dimensioned as Integers as shown below:

Dim, X, Y, Z as Integer Str ings can be defined as variable length, using the String statement, or as a specific length, using the String*Length statement. In the first example below, the variables X, Y, and Z are dimensioned as variable length strings. In the second example below, X, Y, and Z are dimensioned as strings that are 5 characters long.

Dim X, Y, Z as String Dim X, Y, Z as String*5 Boolean variables are defined using the Boolean Command. Remember that a variable defined as Boolean takes on the value of either True or False. Dim X as Boolean Var iant variables can take on whatever variable type the context dictates. For instance, if you do not dimension a variable, VBA assumes that it is of type Variant, and uses the variable as either boolean, double, integer or string based on the context that the variable is used. You can declare a variable as Variant type as shown below: Dim X as Variant Arrays can be dimensioned by adding the range of the array index in the DIM statement. For instance, in the example below, the variable X is defined as a one dimensional array and can have 10 values, where the variable Y is dimensioned as a double array and can have up to 100 values for each dimension.

DIM X(10), Y(100,100) as Double

Page 102: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

102

Moving Data from Excel to VBA Working with Single Cells The most straightforward way to pass variables between Excel spreadsheets and VBA programs is to use cells and ranges of cells in the spreadsheet as the input and output files. VBA has commands that will allow you to directly read or write values directly into spreadsheet cells. To access the value in cell A1 on the worksheet named FlowCalc in the Design workbook, you would use the following syntax: X = Sheets(“FlowCalc”).Range(“A1”).Value This command sets the value of X to be whatever is in cell A1 on the Excel sheet called FlowCalc. Note that the Sheets part of the command points to a specific Excel worksheet and the Range part of the command points to a specific cell (or group of cells). Most of the time, the program you are using is designed to work with the Workbook and Sheet that is currently open. Therefore the following shortcut will work exactly the same, if “Design” is the active workbook and “FlowCalc” is the active sheet.

X = ActiveSheet.Range(“A1”).Value Or

X = Range(“A1”).Value To save a value calculated in the program into the spreadsheet, use a statement like this:

ActiveSheet.Range(“A1”).Value = x Working with Multiple Cells Another approach is to identify a range of cells, either as an array with a name, or as the top-left corner of the range, as:

Range(“B7”).Cells(1,1).Value=2 Range(“B7”).Cells(2,2).Value=3

This code will select the cell B7 in the active sheet as the top left-hand corner of the range. It will then put a 2 in the cell in row 1, column 1, which is cell B7, and then put a 3 in the cell in row 2, column 2, which would be cell C8. If the range in this example was changed to D5 then the 2 would be put in cell D5, and the 3 would be put in cell E6,

Page 103: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

103

which are the cells defined by the (1,1) and (2,2) positions of an array which has D5 in the upper left-hand corner. Naming Cells and Cell Ranges It is sometimes convenient, for purposes of reading and using the program/spreadsheet combination, to name ranges of cells within the spreadsheet and then refer to those ranges by name in the program. To name a range of cells on the spreadsheet, first highlight the group of cells on the spreadsheet using the mouse. Then click Insert>Name>Define to get the Define Name Window. Then type in the name you want to call this range. It can then be used in a VBA procedure. If you later want to modify the range definition, you get into the Define Name Window, highlight the range name, and then, edit the range definition, shown at the bottom of the window. The figure below shows how to read an array of Excel cells into an array in VBA.

A WORD OF CAUTION IN NAMING CELLS AND RANGES: Excel already has names for cells, based on letters of the alphabet for the column designation and numbers for the row designation; example (X1). Many numerical methods involve stepping through a problem with a known value of X1 and solving for an unknown value of X2. A natural tendency is to name the locations for the first value X1 and the second value X2. Excel will over-ride these assignments, and use its own location for cells X1 and X2 with unexpected results.

Group of Cells named“Output” in Excel

Sub Test()

for I = 1 to 8 for j = 1 to 2 X(i,j) = Range(“Output”).Cells(i,j).Value Next jNext I

End Sub

VBA Program

Page 104: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

104

Program Control There are many different looping commands available in VBA. The table below gives a summary of the commands that are available for different program controls that you may need to implement. You can look these commands up on the Help menus to get more specific information about what they do and how to use them. What Do You Want To Do? Command To Do It Branch Gosub and Return

GoTo On Error On and Gosub On and GoTo

Exit or pause the program DoEvents End Exit Stop

Loop Do and Loop For and Next While and Wend With

Make Decisions Choose If – Then – Else Select Case Switch

Use Procedures Call Function Property Get Property Let Property Set Sub

For-Next Loop are one of the most often used methods of creating a loop. The format of this statement is shown below. You can add the Step command to tell the loop how to increment the index variable (in this case, I). In the example below, the index variable I will be increments from 0 to 100 in increments, or steps of 10. Thus, I will take on values of 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, and 100 in the loop. For I = 0 to 100 Step 10 {insert your code here} Next I

Page 105: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

105

While-Wend Loops are often used when you want to execute the code inside the loop until a specific condition is met. For instance, in a control program, you may want to monitor temperature constantly. But, if temperature exceeds a threshold of 100 F, you may want break out of the loop and do something. In the example below, the loop reads the temperature from a thermocouple constantly until the temperature exceeds 100F, in which case, the condition to terminate the loop is satisfied and the loop is terminated. While Temp < 100 {add code to read temperature from thermocouple} Wend Another example is shown below. In this example, the variable I is incremented by 1 in the loop until its value reaches 10. Then the loop is terminated. I = 0 While I < 10 I = I + 1 Wend If-Then-Else commands are the most common way to make decisions. In the example below, if the variable p is less than 100, the variable V is computed. If p < 100 then V is set to zero.

If p<100 then V = p * 6

Else V = 0

Endif You can have multiple test by using the AND command as shown below:

If p<100 AND V = 0 then V = p * 6

Else V = 0

Endif

Page 106: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

106

Other Useful Commands Pop-up Text Windows InputBox – sends a message box to the screen and binds the user input message to a variable on the left hand side of the = sign. Example: Dim message as String

message = InputBox(prompt, "Input Message to Encode") MsgBox – sends a message box to the user. In the example below, the variable Msg is defined as a text string and contains the message that will be sent to the user in a message box. The variable Style is always set to vbOK, and is the variable that pops up the OK and Cancel button in the message box. The variable Title contains the title that will be located at the top of the message box. Example:

Msg = “Hello World” Style = vbOK Title = “Message Decoded” Response = MsgBox(Msg, Style, Title)

Wor king with Str ing Data Len – Returns the length of a string Example: Dim message as String Message = “Today is Monday”

Length = Len(message) Returns Length as 15

Ucase – converts a string of characters to uppercase characters Example: message = UCase(message) Mid (str ing, position to begin, number of characters to read) – Returns a specific character or group of characters within a text string Example 1 M(i) = Mid(message, 4, 1) Returns the 4th character of the string “message”

Page 107: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

107

Example 2 M(i) = Mid(message,4,3) Returns 4th, 4th and 6th characters in the string “message” Reading ASCII Text Files OPEN – opens a text file for input or output. Example

Filename = “sensor1.dat” Open FileName For Input As #1

EOF – indicates when the end of a file is reached. It is helpful in a loop that should terminate when the last entry in a file is read. Example

Do While Not EOF(1) … …. Loop

INPUT # - Allows you to read in a value from a datafile Example

Input #1, x, y ‘Reads in x and Y value from file #1

Adding Sound TIMER - Returns a Single representing the number of seconds elapsed since midnight. It can be used in a loop to pause the program for a desired length of time before proceeding, such as setting the length of a BEEP.

Example PauseTime = Range("B5").Value 'Sets time between readings Start = Timer ' Set start time. Do While Timer < Start + PauseTime DoEvents ' Yield to other processes during delay Loop

BEEP – sounds a Beep. The volume depends upon the computer characteristics. It can be used in conjunction with the TIMER command to set the length of the beep.

Page 108: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

108

Saving, Editing, and Running VBA programs in Excel When you have completed the entry of the program lines into the VBA editor, simply close the editor window using the close button in the upper right hand corner of the screen. (There may be two close buttons in the corner, one for the specific module you are creating, and one for the editor. You will need to close both of them.) This will put you back into the Excel spreadsheet. If you are using it for input, you will need to make sure that the desired input is in the desired cell or cells of the spreadsheet. To run the program click on Tools>Macro>Macros or use the keys Alt+F8 to get to the Macro Window. The name of the macro you created (and any others you may have created within this same workbook or in any other active workbooks) will appear. Choose the correct one if there is more than one, and click Run. If no run-time errors occur, you should see the results of your program on the spreadsheet. If run-time errors occur, the program will automatically go into the VBA editor and highlight the line where the error was detected. As with most computer languages, this may not be the line that needs to be changed to correct the problem. Make corrections, and exit the editor (you will get a message saying that this will end the debugging. Say OK to that). Then rerun the program again to see if it now works. Your program is saved as part of the Excel workbook when it is saved, and will be available for use again when that workbook is opened. To edit a program in the future, open the workbook and get into the Macro Window, choose the appropriate macro, and click the edit button. One advantage of writing VBA programs is that they can be used again in a different workbook. From the VB editor, click on File>Export to get into the Export File window. This looks like any other save window. Sometimes it says it is going to save it as a *.cls type file and sometimes as a *.bas file. I haven’t yet figured out why it does which one. You probably want to save it as *.bas because this type is usable in a text editor, and the *.cls type is not. Both types can be imported into a new spreadsheet. Save it to whatever directory you want (probably your own floppy disk). To use a module you have previously written in a new spreadsheet, get into the VB editor and click on File>Impor t to get into the Import File window, which looks like any other open file window. You will notice that it will be looking for files with endings *.frm, *.bas, and *.cls. When you find the one you want in the directory, choose it and open it. It won’t immediately show up on the VB editor window, but, when you exit and look at the available modules for the spreadsheet, it will be there, and can be opened and edited just like any other.

Page 109: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

109

Debugging Programs in the VBA Inter face VBA provides a very nice debugging environment. This is very useful for determining if your code is working the way you intended. All the VBA debugging tools are in the Debug menu. One Line At A Time The “Step Into” menu item on the Debug menu allows you to run your program one line at a time. You can also push the F8 function key to step into each line of your code. As you run your code by pushing the F8 function key, you can move the cursor over variables of interest and their current value should pop up just over the cursor. You can Select the “Add to Watch” item on the Debug menu and type in variable names that you want to see displayed in a watch window at the bottom of the screen. This is a very powerful feature in debugging. Breakpoints You can set a break point anywhere in your code that will allow you to run the program to the breakpoint, then stop and allow you to run the code one line at a time. To set a breakpoint, place the cursor on the line of code you want the program to stop at and either select the Toggle Breakpoint item on the Debug menu or press the F9 function key. You can also clear all breakpoints by selecting this option on the Debug menu. Run to Cursor Another way to stop a program at a specific line of code is to place click the cursor onto that line of code and select the Run to Cursor item on the Debug menu. The program will then run until it reaches the line of code that the cursor is on, and you can then step through the remaining line of code one line at a time.

Page 110: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

110

Adding an ActiveX Char t to a UserForm You can add a chart to a User Form and draw the chart with VBA commands. In order to add a chart, your program needs access to Microsoft’s chart tools. These are contained in the following files:

MSCHRT20.DEP MSCHRT20.OCX MSCHRT20.OCA MSCHRT20.SRG

It is likely that your computer already has these libraries loaded and available for use in VBA. Here is how you can reference to charting library if it is already loaded on your system. Step 1: Open a new worksheet and go to the VBA interface. Step 2: Select the Insert menu and add a new UserForm to the program. You will see a new userform pop up on your screen. Step 3: If the Controls Toolbox form is not visible, click on the <View<Toolbox menu to turn it on. Step 4: Right click on the Toolbox form and select the Additional Controls menu item. Step 5: Search for the Microsoft Chart Control 6.0 Control and click in the box to turn it on. If you do not see this control, then you must add it as a reference (see steps below). Step 6: Once you turn on the Chart Control select the OK button. You should now see a red, blue and green chart icon on the Toolbox Controls Form. If you cannot find the Microsoft Chart Control 6.0, you need to add it as a reference. Here’s the procedures for this. Step 1. Copy the following files into your working directory.

MSCHRT20.DEP MSCHRT20.OCX MSCHRT20.OCA MSCHRT20.SRG

Step 2: In the VBA editor, go to the Tools menu and select the References option.

Page 111: Upload VBA Lesson_1

AE 303 VBA Reference Guide __________________________________________________________________________________

111

Step 3: In the References form, click on the Browse button and search for the MSCHRT20.OCX file you just copied into your working directory. Double click on the file. It is now loaded. Step 4: Oops, I got this error. This control could not be created because it is not properly licensed. Thus, it seems like you have to have visual basic on your computer to have access to this control.