Anda di halaman 1dari 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 bbatch@iastate.edu

2

3

Topic Supporting
Pr ograms
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

Pr ograms You Should Turn In

AE 303 Lesson 1
__________________________________________________________________________________
4

Lesson 1
Intr oduction to Numer ical 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

F
up
F
down

= a m F *
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

F
up
= - c * V

Where c = drag coefficient of the parachute
V = velocity of the parachute

The downward force on the body can be characterized by

F
down
= 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

m
F
dt
dV

=
m
cV mg
dt
dV
=
m
cV
g
dt
dV
=
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

Lets assume that when the person jumps from the plane at time t=0, the velocity is 0 m/s.
Lets 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.

|
|
.
|

\
|
=
|
.
|

\
|

m
t c
e
c
m g
t V
*
1
*
) (
Analytic Solution for Terminal Velocity
0
10
20
30
40
50
60
0 10 20 30 40 50 60
Ti me, s
V
e
l
o
c
i
t
y
Analytical Solution
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.

Lets look at a simple example of a numerical method to solve the parachute problem
outlined above. Lets 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

m
cV
g
dt
dV
=
V
t
V
t+dt
V
e
l
o
c
i
t
y
,

m
/
s
Time, s
t
t+dt
t dt t
V V
run
rise
dt
dV
t dt t
+

= =
+
) (
t
t dt t
V
m
c
g
t dt t
V V
*
) (
=
+

+
( ) t dt t V
m
c
g V V
t t dt t
+ |
.
|

\
|
+ =
+
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. Lets assume that at time t=0, the velocity = 0 m/s. Lets now
solve Equation 3 using a time step dt = 2 seconds. Lets 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

( ) dt V
m
c
g V V
t t t
|
.
|

\
|
+ =
= = = 0 0 2
( ) s m V
t
/ 6 . 19 2 0 *
1 . 68
5 . 12
8 . 9 0
2
= |
.
|

\
|
+ =
=
( ) dt V
m
c
g V V
t t t
|
.
|

\
|
+ =
= = = 2 2 4
( ) s m V
t
/ 0 . 32 2 6 . 19 *
1 . 68
5 . 12
8 . 9 6 . 19
4
= |
.
|

\
|
+ =
=
100 *
value Analytical
value Numerical value Analytical
error

=
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.

AE 303 Lesson 1
__________________________________________________________________________________
10
Exer cise 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.

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 citys demands. The water
volume is recharged at a sinusoidal rate 3Qsin
2
t.
The following equation can be written for this
system:

Where V = volume of the tank
Q = flowrate of water withdrawn from the tank, m
3
/d
A = cross sectional area of the tank, m
3

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 m
2
and Q = 400 m
3
/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?

A
Q
t
A
Q
dt
dy
=
2
sin 3
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
H
e
i
g
h
t
,

m
Step = 0.5
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.5
Step = 1.0
Step = 2.0
Step = 3.0
AE 303 Lesson 1
__________________________________________________________________________________
13

Laborator y 1
Intr oduction 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
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.

Pr ocedures

Step 1: Open a new spreadsheet in Excel and set up Inputs (Fields B9-B13) on the

Row
Number
Column Colum
n
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
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. Dont 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
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" ).Clear Contents
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" ).Clear Contents 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.

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

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
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
) ( Numeric Analytical RMSE =

name}.xls.

AE 303 Lesson 1
__________________________________________________________________________________
18
Subr outines

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
AE 303 Lesson 1
__________________________________________________________________________________
19
Tf = Range("B12").Value
dT = Range("B13").Value

' --- Solve the Function at discr ete 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

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
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

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.
Lets 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:
|
|
.
|

\
|
=
t
m
c
e
c
m g
V 1
V e
c
m g
c f
t
m
c

|
|
.
|

\
|
= =

1 0 ) (
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.

Lets 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 X
L
and X
U
. The only criteria governing the choice of these roots is that X
L
must be
below the real root and X
U
must be higher than the root. The value of the function
evaluated at X
L
is F(X
L
) and the value of the function evaluated at X
U
is F(X
U
). If F(X
L
)
* F(X
U
) is negative, then a real root lies between X
L
and X
U
.

By geometry, a better estimate of the root can be obtained by drawing a straight line
between the function at X
L
and X
U
and selecting the new root X
R
as point where this line
intersects the X axis. This is shown in the Figure below.
-20
-10
0
10
20
30
40
0 10 20 30
Drag Coefficient, c
f
(
c
)
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, X
R
using the method of similar triangles. The first triangle is formed
by the points X
L
, X
R
and F(X
L
) while the second triangle is formed by X
U
, X
R
and F(X
U
).
We know the values of X
L
, F(X
L
), X
U
and F(X
U
). We want to compute X
R
. By similar
triangles, we can write the following equation

Eq. 3

Rearranging this relationship to solve for X
R
gives

Eq. 4

Using Equation 4, we can now compute the new estimate of the root, X
R
, 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 X
L
or X
U
, however it is not accurate enough for engineering
calculations.

However, we can now repeat these steps by replacing our original estimate of either X
U

or X
L
with the new estimate of the root, X
R
and solving Equation 4 for a second new
estimate of the root. In order to determine if we should replace X
L
or X
U
with X
R
, we
must determine if the real root lies in the interval X
L
to X
R
or X
R
to X
U
. 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 X
R
for X
L
or X
U
:
X
L
X
U
F(X
L
)
F(X
U
)
X
R
U R
U
L R
L
X X
X F
X X
X F

) ( ) (
) ( ) (
) ( ) (
U L
U L U
U R
X F X F
X X X F
X X

=
AE 303 Lesson 2
__________________________________________________________________________________
24

A) If the function evaluated at X
L
multiplied by the function evaluated at X
R
is negative,
then the root lies between X
L
and X
R
, so we set X
U
= X
R
. Mathematically, this can be
computed by:

If F(X
L
) * F(X
R
) < 0 then set X
U
= X
R

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

If F(X
L
) * F(X
R
) > 0 then set X
L
= X
R

C) If F(X
L
) * F(X
R
) = 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:

X
L
X
U
F(X
L
)
F(X
U
)
X
R
AE 303 Lesson 2
__________________________________________________________________________________
25

Where E = percent error
X
R
i
= estimate of the root for the current iteration, i
X
R
i-1
= estimate of the root for the previous iteration, i-1
100 converts from decimal to percent

100 *
1
1

=
i
R
i
R
i
R
X
X X
E
AE 303 Lesson 2
__________________________________________________________________________________
26
Cheat Sheet For False Position Method

Step 1: Choose values for X
L
and X
U
that bracket the root. This can be verified by
multiplying F(X
L
) * F(X
U
) to insure the product is negative.

Step 2: Estimate the new root by

Step 3: Replace X
L
or X
U
with X
R

If F(X
L
) * F(X
R
) < 0 then set X
U
= X
R

If F(X
L
) * F(X
R
) > 0 then set X
L
= X
R

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

) ( ) (
) ( ) (
U L
U L U
U R
X F X F
X X X F
X X

=
100 *
1
1

=
i
R
i
R
i
R
X
X X
E
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. Lets
assume that the mass of the person and parachute (m) is 68.1 kg and the gravity constant
(g) is 9.8 m/s
2
.

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 X
L
and X
U
that bracket the root. This can be verified by
multiplying F(X
L
) * F(X
U
) 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 X
L

= 12 and X
U
= 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

V e
c
m g
c f
t
m
c

|
|
.
|

\
|
= =

1 0 ) (
) ( ) (
) ( ) (
U L
U L U
U R
X F X F
X X X F
X X

=
26786 . 2 40 1
16
1 . 68 * 8 . 9
) (
10 *
1 . 68
16
=
|
|
|
.
|

\
|
=
|
.
|

\
|
e X F
U
0669 . 6 40 1
12
1 . 68 * 8 . 9
) (
10 *
1 . 68
12
=
|
|
|
.
|

\
|
=
|
.
|

\
|
e X F
L
911313 . 14
) 26786 . 2 ( 0669 . 6
) 16 12 ( * 26786 . 2
16 =

=
R
X
AE 303 Lesson 2
__________________________________________________________________________________
28
Table 1 also shows the results for each iteration of the solution.

Step 3: Replace X
L
or X
U
with X
R

If F(X
L
) * F(X
R
) < 0 then set X
U
= X
R

If F(X
L
) * F(X
R
) > 0 then set X
L
= X
R

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

In this iteration, F(X
L
) * F(X
R
) = (6.0669) * (-0.2543) = -1.5427. Since this value is
negative, we replace X
U
with X
R
. So, for iteration 1, the value of X
L
remains unchanged
at 12 and the value for X
U
is now 14.911303.

Since this is the first estimate of the root, Step 4 cannot be applied until the 2
nd
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) Comments
1 12 16 14.91130318 6.0669 -0.2543 -1.5427 Negative, so replace XU with XR for next iteration
2 12 14.9113 14.79419278 0.79160 6.0669 -0.0273 -0.1654 Negative, so replace XU with XR for next iteration
3 12 14.79419 14.78169534 0.08455 6.0669 -0.0029 -0.0176 Negative, so replace XU with XR for next iteration
4 12 14.7817 14.78036284 0.00902 6.0669 -0.0003 -0.0019 Negative, so replace XU with XR for next iteration
5 12 14.78036 14.78022078 0.00096 6.0669 0.0000 -0.0002 Negative, so replace XU with XR for next iteration
6 12 14.78022 14.78020564 0.00010 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration
7 12 14.78021 14.78020402 0.00001 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration
8 12 14.7802 14.78020385 0.00000 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration
9 12 14.7802 14.78020383 0.00000 6.0669 0.0000 0.0000 Negative, so replace XU with XR for next iteration
2543 . 0 40 1
911303 . 14
1 . 68 * 8 . 9
) (
10 *
1 . 68
911303 . 14
=
|
|
|
.
|

\
|
=
|
.
|

\
|
e X F
R
AE 303 Lesson 2
__________________________________________________________________________________
29
Exer cise 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.

AE 303 Lesson 2
__________________________________________________________________________________
30

Exer cise 2 Continued

AE 303 Lesson 2
__________________________________________________________________________________
31
Laborator y 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

t t
e e c
075 . 0 5 . 1
25 70

+ =

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 (X
L
and X
U
). If there is no
root between these two estimates, the program should warn the user to select different
values of X
L
and X
U
. 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

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

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.

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. Lets 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 For mulation

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

)
`

=
)
`

2
18
2 1
2 3
Y
X
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. Thats 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

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

Forwar d 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 . 70 02 . 10 19000 . 0 0
85 . 7 2 . 0 1 . 0 3
3
3 . 0
4 . 71 10 2 . 0 3 . 0
=
=
= +
Z Y X
Z Y X
Z Y X
( )
615 . 70 02 . 10 19000 . 0 0
85 . 7 2 . 0 1 . 0 3
3
1 . 0
3 . 19 3 . 0 7 1 . 0
=
=
= +
Z Y X
Z Y X
Z Y X
615 . 70 02 . 10 1900 . 0
5617 . 19 2933 . 0 0033 . 7
85 . 7 2 . 0 1 . 0 3
= +
=
=
Z Y
Z Y
Z Y X
( )
0843 . 70 02 . 10
5617 . 19 2933 . 0 0033 . 7
0033 . 7
19 . 0
615 . 70 02 . 10 1900 . 0
=
=

= +
Z
Z Y
Z Y
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 . 70 02 . 10
5617 . 19 2933 . 0 0033 . 7
85 . 7 2 . 0 1 . 0 3
=
=
=
Z
Z Y
Z Y X
AE 303 Lesson 3
__________________________________________________________________________________
37
Exer cise #3
Gauss Elimination for Solving Systems of Linear Equations

Use Gauss Elimination to solve for X
1
, X
2
and X
3
in the following system of equations.
you have the correct solution.

4X
1
+ X
2
X
3
= -2
5X
1
+ X
2
+ 2X
3
= 4
6X
1
+ X
2
+ X
3
= 5

Solution:

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.

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).

Pr ocedures

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:

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

200
0
0
0
0
0
6
5
4
3
2
1
0
5
1
1
0
0
0 20 0 10 5
15 0 10 10 0
1 0 0 0 0
0 0 1 0 0
1 1 0 1 0
0 0 1 1 1
X
X
X
X
X
X
AE 303 Lesson 4
__________________________________________________________________________________
40
Lesson #4
Matr ix Inver sion 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.

)
`

=
)
`

2
18
2 1
2 3
2
1
X
X
1 0 0
0 1 0
0 0 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:

c
11
= a
12
* b
11
+ a
12
* b
21

c
12
= a
11
* b
12
+ a
12
* b
22

c
21
= a
21
* b
11
+ a
22
* b
21

c
22
= a
21
* b
12
+ a
22
* b
22

Consider the matrix [A] and its inverse [A]
-1

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

Inver ting a Matr ix Using Micr osoft Excel

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

22 21
12 11
22 21
12 11
22 21
12 11
c c
c c
b b
b b
a a
a a
=
| | | |
1 2
5 . 1 5 . 2
5 4
3 2
1

= =

A A
1 0
0 1
) 1 * 5 5 . 1 * 4 ) 2 * 5 5 . 2 * 4 (
) 1 * 3 5 . 1 * 2 ( ) 2 * 3 5 . 2 * 2 (
1 2
5 . 1 5 . 2
5 4
3 2
=
+ +
+ +
=

AE 303 Lesson 4
__________________________________________________________________________________
42

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 r ow matrix.

Lets assume that we want to use a 3x3 matrix for encryption. Lets 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

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 lets encrypt the second 1x3 matrix [T_M] or [20 0 13] following the same
approach:

4 1 1
3 1 1
2 2 1

= A
| |
| |
| | 21 26 13
) 4 * 5 3 * 5 2 * 13 ( ) 1 * 5 1 * 5 2 * 13 ( ) 1 * 5 1 * 5 1 * 13 (
4 1 1
3 1 1
2 2 1
5 5 13
=
+ + + + + +
=

| |
| |
| | 12 53 33
) 4 * 13 3 * 0 2 * 20 ( ) 1 * 13 1 * 0 2 * 20 ( ) 1 * 13 1 * 0 1 * 20 (
4 1 1
3 1 1
2 2 1
13 0 20
=
+ + + + + +
=

AE 303 Lesson 4
__________________________________________________________________________________
45
Now lets encrypt the third matrix [E _ M] or [5 0 13] by

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

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

| |
| |
| | 42 23 18
) 4 * 13 3 * 0 2 * 5 ( ) 1 * 13 1 * 0 2 * 5 ( ) 1 * 13 1 * 0 1 * 5 (
4 1 1
3 1 1
2 2 1
13 0 5
=
+ + + + + +
=

| |
| |
| | 56 20 5
) 4 * 4 3 * 14 2 * 15 ( ) 1 * 4 1 * 14 2 * 15 ( ) 1 * 4 1 * 14 1 * 15 (
4 1 1
3 1 1
2 2 1
4 14 15
=
+ + + + + +
=

| |
| |
| | 77 23 24
) 4 * 0 3 * 25 2 * 1 ( ) 1 * 0 1 * 25 2 * 1 ( ) 1 * 0 1 * 25 1 * 1 (
4 1 1
3 1 1
2 2 1
0 25 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:

4 1 0
5 6 1
8 10 1
1

=

A
| | | | | | E E M = =

5 5 13
4 1 0
5 6 1
8 10 1
21 26 13
| | | | | | M E _ 13 0 5
4 1 0
5 6 1
8 10 1
42 23 18 = =

AE 303 Lesson 4
__________________________________________________________________________________
47

We can now peace the decoded 3x1 matrices back together into the original message that
says Meet Me Monday.

Secur e Systems

The beauty of this encryption technique is that the only way to unscramble the message is
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.

| | | | | | M T _ 13 0 20
4 1 0
5 6 1
8 10 1
12 53 33 = =

| | | | | | D N O = =

4 14 5 1
4 1 0
5 6 1
8 10 1
56 20 5
| | | | | | _ 0 25 1
4 1 0
5 6 1
8 10 1
77 23 24 Y A = =

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 mPower
3
/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
producers 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 users end, sending the
scrambled message across the web to the clients 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.

Tr anscribe 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.

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.

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 Tur n In

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 (string, 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 4
th
character of the string message

Example
M(i) = Mid(message,4,3)
Returns 4
th
, 4
th
and 6
th
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)

AE 303 Lesson 5
__________________________________________________________________________________
51
Lesson 5

Linear Regr ession

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 Squar es Regr ession

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
a
o
= intercept of the line
0
2
4
6
8
10
12
0 2 4 6 8 10
e x a a y + + =
1 0
AE 303 Lesson 5
__________________________________________________________________________________
52
a
1
= 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. e
2
) between each pair of
predicted and measured values of y. Mathematically, we can define the sum of the
residual error, S
r
as

Eq.
2

Where n is the number of data points. Since y
i model
= a
o
+ a
1
x, we can substitute this into
the previous equation to get

Eq. 3

How do you determine the coefficients a
0
and a
1
for the best fit line? We take the partial
derivative of S
r
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 S
r
with respect to a
1
gives

Eq. 6

Eq. 7

( ) ) 1 ( * 2
1
1 0
0
=
c
c

=
n
i
i i
r
x a a y
a
S
( )
2
1
1 0
=
=
n
i
i measured i r
x a a y S
( )
2
1 1
mod
2

= =
= =
n
i
n
i
el i measured i i r
y y e S
( )

=
=
c
c
n
i
i i
r
x a a y
a
S
1
1 0
0
2
( ) ) ( * 2
1
1 0
1
i
n
i
i i
r
x x a a y
a
S
=
c
c

=
( )
i
n
i
i i
r
x x a a y
a
S
* 2
1
1 0
1

=
=
c
c
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
i
i
n
i
i
y a x a n
1
1
1
0
Eq. 10

i
n
i
i
n
i
i
n
i
i
y x x a x

= = =
= |
.
|

\
|
+ |
.
|

\
|
1 1
2
0
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 a
0
and a
1
. We can now solve Eq. 10 and 11 explicitly for the
coefficient a
0
and a
1
by

Eq. 12

Eq. 13

( )

=
=
c
c
=
n
i
i i
r
x a a y
a
S
1
1 0
0
2 0
( )
i
n
i
i i
r
x x a a y
a
S
* 2 0
1
1 0
1

=
=
c
c
=
2
1 1
2
1 1 1
1
) (
|
.
|

\
|

=

= =
= = =
n
i
i
n
i
i
n
i
i
n
i
i
n
i
i i
x x n
y x y x n
a
x a y a
1 0
=
AE 303 Lesson 5
__________________________________________________________________________________
54
Example: Compute the coefficients of the best-fit line for data shown below.

x
i
y
i
x
i
* y
i
x
i
2

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 a
0
and a
1
.

Thus, the equation of the best-fit line is

2
1 1
2
1 1 1
1
) (
|
.
|

\
|

=

= =
= = =
n
i
i
n
i
i
n
i
i
n
i
i
n
i
i i
x x n
y x y x n
a
8392857 . 0
) 28 ( ) 140 ( 7
) 24 ( 28 ) 5 . 119 ( 7
2
1
=

= a
07142857 . 0
) 4 ( 8392857 . 0 42857 . 3
1 0
=
=
= x a y a
x y 8392857 . 0 07142857 . 0 + =
AE 303 Lesson 5
__________________________________________________________________________________
55
Quantification of Er r or of Linear Regression

The sum of squares of the r esidual, S
r
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, S
r
would be zero. If the model does not fit the data very well, the S
r

value would be very high.

Eq. 14

Where n = number of datapoints
y
i
= measured y values
x
i
= measured x values
a
0
= intercept of best fit line
a
1
= 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 Chebyshevs 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

S
t
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
1
1 0
=
=
n
i
i measured i r
x a a y S
2
/

=
n
S
S
r
y x

=
=
n
i
i t
y y S
1
2
) (
AE 303 Lesson 5
__________________________________________________________________________________
56
The value (S
t
S
r
) 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, r
2
, 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 r
2
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
r t
S
S S
r

=
2
AE 303 Lesson 5
__________________________________________________________________________________
57
Exer cise 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, S
x/y
and the coefficient of determination, r
2
of the
best fit line

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

AE 303 Lesson 5
__________________________________________________________________________________
58
Laborator y 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
sensor values every second, determines if the reading is distorted and sounds an alarm if

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 1
st
, 2
nd
and 3
rd
sensor

- 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
Cycl es
V
o
l
t
a
g
e
,

m
v
Figure 2. Distorted Brain Wave
-2.50
-2.00
-1.50
-1.00
-0.50
0.00
0.50
1.00
1.50
2.00
2.50
0 500 1000 1500 2000
Cycles
V
o
l
t
a
g
e
,

m
v
Fit linear regression through first 3
B
e
s
t

F
i
t

L
i
n
e
1 2 3 4
Ye = Estimate of 4th reading
If ABS(Ye-Ya) < threshold
AE 303 Lesson 5
__________________________________________________________________________________
59
- Step 5: If ABS(Ye-Ya) < a threshold
value, then the 4
th
distorted. If the ABS(Ye-Ya) is greater
than a threshold, then the 4
th
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 4
th
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
4
th
sensor reading is greater than a threshold, then the 4
th
distorted. In this case, select the 2
nd
, 3
rd
and the estimate of the 4
th
compute the next best-fit line, and proceed back to Step 2. Note that if the distorted
4
th
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 5
th

Pr ogr am 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.

B
e
s
t
F
i
t
L
i
n
e

f
o
r

l
a
s
t

3
r
e
a
d
i
n
g
s
1 2 3 4 5
Ye = Estimate of 5th reading
If ABS(Ye-Ya) > threshold
1 2 3 4 5 6
Use Estimate of 5th reading rather than
actual 5th reading which was distorted to
compute next regression line
Previous regression line
New Regression Line
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 (Thats 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 systems 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.

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.

Pr ogr am 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
AE 303 Lesson 5
__________________________________________________________________________________
62

Develop the program and evaluate the behavior of the program for each of the sensor data
files.

What to Tur n In

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?

AE 303 Lesson 6
__________________________________________________________________________________
63
Lesson 6
Polynomial Regr ession

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 2
nd
order polynomial

y = a
0
+ a
1
x + a
2
x
2
+ 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, S
r
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 S
r
with respect to each
coefficient a
0
, a
1
and a
2
, 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 a
0
gives

Eq. 3

Now, taking the partial derivative of S
r
with respect to a
1
gives

Eq. 4

Now, taking the partial derivative of S
r
with respect to a
2
gives

Eq. 5
( )
2
1
2
2 1 0
=
=
n
i
i i i r
x a x a a y S
( )

=
=
c
c
n
i
i i i
r
x a x a a y
a
S
1
2
2 1 0
0
2
( )
i
n
i
i i i
r
x x a x a a y
a
S
* 2
1
2
2 1 0
1

=
=
c
c
( )
2
1
2
2 1 0
2
* 2
i
n
i
i i i
r
x x a x a a y
a
S

=
=
c
c
AE 303 Lesson 6
__________________________________________________________________________________
64
Setting the partial derivatives in Eq. 3, 4, and 5 and rearranging gives the following
system of equations:

( ) ( )

= + +
i i i
y a x a x a n
2
2
1 0
Eq. 6

( ) ( ) ( )

= + +
i i i i i
y x a x a x a x
2
3
1
2
0
Eq. 7

( ) ( ) ( )

= + +
i i i i i
y x a x a x a x
2
2
4
1
3
0
2
Eq. 8

Since the x
i
and y
i
values are data, and the number of datapoints (n) is known, we are left
with 3 equations and 3 unknowns, namely a
0
, a
1
and a
2
, 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

i i
i i
i
i i i
i i i
i i
y x
y x
y
a
a
a
x x x
x x x
x x n
2
2
1
0
4 3 2
3 2
2
Eq. 9

You can now use a numerical method to solve for the coefficients.

Quantification of Er r or of Linear Regression

The sum of squares of the r esidual, S
r
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, S
r
would be zero. If the model does not fit the data very well, the S
r

value would be very high.

Eq. 10

Where n = number of datapoints
y
i
= measured y values
( )
2
1
2
2 1 0
=
=
n
i
i i measured i r
x a x a a y S
AE 303 Lesson 6
__________________________________________________________________________________
65
x
i
= measured x values
a
0
= intercept of best fit line
a
1
= linear coefficient
a
2
= 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 Chebyshevs 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

S
t
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 (S
t
S
r
) 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, r
2
, 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
/

=
n
S
S
r
y x

=
=
n
i
i t
y y S
1
2
) (
t
r t
S
S S
r

=
2
AE 303 Lesson 6
__________________________________________________________________________________
66
line. The r
2
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.

AE 303 Lesson 6
__________________________________________________________________________________
67
Exer cise 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
Excels matrix features outlined in a previous Lesson. Save your spreadsheet in a file

X Y
0 2.1
1 7.7
2 13.6
3 27.2
4 40.9
5 61.1

AE 303 Lesson 7
__________________________________________________________________________________
68
Lesson 7: Time Value of Money

Futur e Value of Pr esent 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 Inter est
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.

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:

n
i P F ) 1 ( + =
n
i P F ) 1 ( + =
n
i P F ) 1 ( + =
5
) 07 . 0 1 ( 000 , 1 \$ + = F
5 * 365
365
07 .
1 000 , 1 \$ |
.
|

\
|
+ = F
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
rn
e P F =
rn
e F P

=
) 10 * 06 . 0 (
000 , 5 \$
years rn
e Fe P

= =
AE 303 Lesson 7
__________________________________________________________________________________
71

Effective Annual Inter est 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

I
eff
= 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.

I
eff
= 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 I
eff
is
rate per year.

Solution:

Use i=7% compounded daily gives:

F=\$1,419.02
1 ) 1 ( + =
n
eff
i I
1 ) 1 ( + =
n
eff
i I
1 )
365
07 .
1 (
365
+ =
eff
I
n
i P F ) 1 ( + =
5 * 365
365
07 .
1 000 , 1 \$ |
.
|

\
|
+ = F
AE 303 Lesson 7
__________________________________________________________________________________
72

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

F=\$1,419.02

Mor e 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: Theres no reason to get all excited
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

n
eff
I P F ) 1 ( + =
( )
5
072501 . 0 1 000 , 1 \$ + = F
F
0 6 12 18 24 30 36
Months
\$1,000
\$1,500
\$2,000
2 4 6
2
07 .
1 2000
2
07 .
1 1500
2
07 .
1 1000 |
.
|

\
|
+ + |
.
|

\
|
+ + |
.
|

\
|
+ = F
AE 303 Lesson 7
__________________________________________________________________________________
73
Pr esent Value of Futur e 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 childs 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

Pr esent and Futur e Value of Unifor m 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.
n
i P F ) 1 ( + =
n
i F P

+ = ) 1 (
n
i F P

+ = ) 1 (
18
) 06 . 1 ( 000 , 200 \$

+ = P
F = ?
A A A A A A
P = ?
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
sons 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 (
n
i
i
F A
(

+
=
i
i
A F
n
1 ) 1 (
(

+
+
=
1 ) 1 (
) 1 (
n
n
i
i i
P A
(

+
+
=
n
n
i i
i
A P
) 1 (
1 ) 1 (
(

+
=
1 ) 1 (
n
i
i
F A
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.

(
(
(
(

|
.
|

\
|
+
=
1
12
06 . 0
1
12
06 . 0
000 , 200 \$
18 * 12
A
(

+
+
=
1 ) 1 (
) 1 (
n
n
i
i i
P A
(

+
+
=
1 ) 005 . 0 1 (
) 005 . 0 1 ( 005 . 0
000 , 100
30 * 12
30 * 12
A
(

+
=
i
i
A F
n
1 ) 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 . 599
30 * 12
F
(

+
+
=
1 ) 1 (
) 1 (
n
n
i
i i
P A
(
(
(
(

|
.
|

\
|
+
|
.
|

\
|
+
=
1
12
19 .
1
12
19 .
1
12
19 .
3088 62
n
n
AE 303 Lesson 7
__________________________________________________________________________________
77
Pr esent and Futur e Value of Gr adients

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
A = annual recurring cost, \$/time
i = interest rate per compounding period
n = number of compounding periods

A
G
P
(

+
(

+
=
n
n
i
n
i
i
i
G
P
) 1 (
1 1 ) 1 (
(

+
=
1 ) 1 (
1
n
i
n
i
G A
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, \$
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
i i
i
A P
(

+
(

+
=
n
n
i
n
i
i
i
G
P
) 1 (
1 1 ) 1 (
247 \$
) 05 . 1 (
1
5
05 .
1 ) 05 . 1 (
05 .
30 \$
5
5
=
(

+
(

+
= P
AE 303 Lesson 7
__________________________________________________________________________________
79
Exer cise 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?

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.

AE 303 Lesson 8
__________________________________________________________________________________
81
Lesson 8
Pr esent Wor th 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

Lets 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, lets 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 . 0 1 ( 350 300 cos

+ + = million million t PW
AE 303 Lesson 8
__________________________________________________________________________________
82
Differ ent 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,000
A=2700/yr
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 . 0 1 ( 1 . 0
1 ) 1 . 0 1 (
2700 P
P = 2700(6.1446) = \$16,590
10
) 1 . 0 1 ( 3000

+ = P
P = 3000(0.38554) = \$1,157
\$60,433
\$60,433 \$60,433
10 years 10 years 10 years
( )
10
1 . 0 1 433 , 60 \$ ) 1 (

+ = + =
n
i F P
( )
20
1 . 0 1 433 , 60 \$ ) 1 (

+ = + =
n
i F P
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.

AE 303 Lesson 8
__________________________________________________________________________________
85
Exer cise 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.

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.

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 , 1 000 , 14
10
EUAB = \$14,104
Benefits
Costs
235 , 10 \$ 8000
1 ) 08 . 1 (
) 08 . 1 ( 08 .
15000
10
10
= +
(
(

+
+
= EUAC
(EUAB-EUAC) = \$14,104 - \$10,235 = \$3,869
Annual Cost
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 , 2 000 , 9
10
EUAB = \$9,173
Benefits
Costs
726 , 9 \$ 6000
1 ) 08 . 1 (
) 08 . 1 ( 08 .
25000
10
10
= +
(
(

+
+
= EUAC
(EUAB-EUAC) = \$9,173 - \$9,726 = - \$553
Annual Cost
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.

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 I
eff

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

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.

Contr ol 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

2635
Sil ver Spri ngs Energy Model
Plants, Kcal/m2
213 Herbivores, Kcal/m2
9
Carnivores, Kcal/m2 62
Alligators, Kcal/m2
25 Decomposers, Kcal/m2
Initial Energy Levels
Feeding Model
Linear model nmlkji
Non-Linear Model nmlkj
Run Model
Private Sub CommandButton1_Click()
Plants = TextBox1.Value
Herb = TextBox2.Value
Carn = TextBox3.Value
Allig = TextBox4.Value
Decom = TextBox5.Value
FeedLin = OptionButton1.Value
FeedNon = OptionButton2.Value
End Sub
VBA Program
Excel User Interface
AE 303 Lesson 10
__________________________________________________________________________________
92
Laborator y #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
V
t+dt
= velocity at time t+dt, m/s
V
t
= 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.

( ) dt V
m
c
g V V
t t dt t
|
.
|

\
|
+ =
+
|
|
.
|

\
|
=
|
.
|

\
|

m
t c
e
c
m g
t V
*
1
*
) (
AE 303 Lesson 10
__________________________________________________________________________________
93
Methods

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 45
o
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. Lets 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 lets 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).

AE 303 Lesson 10
__________________________________________________________________________________
94

Step 8. Now, lets 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 dont want both buttons to initially be
true!).

AE 303 Lesson 10
__________________________________________________________________________________
95
Step 10. Now, lets add a Command Button to the form so that we can run the program.
Click on the Command Button icon on the Contr ol 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 buttons VBA subroutine,
which is called CommandButton1_Click().
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
End If

If Analytic = True Then
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:

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 45
o

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.

AE 303 VBA Reference Guide
__________________________________________________________________________________
98
Visual Basic for Applications
Refer ence Guide

The VBA Pr ogr amming Envir onment

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 1980s. 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.

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 isnt 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.

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

Dont 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 Subr outine: 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.

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.
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

Strings 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

Arr ays 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
AE 303 VBA Reference Guide
__________________________________________________________________________________
102
Moving Data fr om Excel to VBA

Wor king 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

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

Wor king 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,
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 X
1
and solving for an
unknown value of X
2
. 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.

Gr oup 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 j
Next I
End Sub
VBA Pr ogram
AE 303 VBA Reference Guide
__________________________________________________________________________________
104
Pr ogr am Contr ol

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
Next I
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
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

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 (string, 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 4
th
character of the string message
AE 303 VBA Reference Guide
__________________________________________________________________________________
107

Example 2
M(i) = Mid(message,4,3)
Returns 4
th
, 4
th
and 6
th
characters in the string message

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,
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.

AE 303 VBA Reference Guide
__________________________________________________________________________________
108
Saving, Editing, and Running VBA pr ogr ams 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

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 havent 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 wont 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.

AE 303 VBA Reference Guide
__________________________________________________________________________________
109
Debugging Pr ogr ams 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

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.

Br eakpoints
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 Cur sor
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.

AE 303 VBA Reference Guide
__________________________________________________________________________________
110
Adding an ActiveX Char t to a User For m

You can add a chart to a User Form and draw the chart with VBA commands. In order to
the following files:

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

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.
Heres 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.

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