Engineering Computation An Introduction Using MATLAB and Excel PDF
Engineering Computation An Introduction Using MATLAB and Excel PDF
ENGINEERING COMPUTATIONS
An Introduction Using
MATLAB® and Excel®
Joseph C. Musto
Milwaukee School of Engineering
William E. Howard
East Carolina University
Richard R. Williams
East Carolina University
ch00_mus80164.qxd 9/2/08 3:42 PM Page ii
Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the
Americas, New York, NY 10020. Copyright © 2009 by The McGraw-Hill Companies, Inc. All rights reserved.
No part of this publication may be reproduced or distributed in any form or by any means, or stored in a
database or retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including,
but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.
Some ancillaries, including electronic and print components, may not be available to customers outside the
United States.
1 2 3 4 5 6 7 8 9 0 DOC/DOC 0 9 8
ISBN 978-0-07-338016-2
MHID 0-07-338016-4
Musto, Joseph C.
Engineering computations : an introduction using matlab and excel / Joseph C. Musto, William E. Howard,
Richard R. Williams.
p. cm.
Includes index.
ISBN 978-0-07-338016-2 --- ISBN 0-07-338016-4 (hard copy : alk. paper) 1. Engineering mathematics.
I. Howard, William E. II. Williams, Richard R. III. Title.
TA329.M87 2009
620.001'51--dc22
2008035067
www.mhhe.com
ch00_mus80164.qxd 9/2/08 3:42 PM Page iii
CONTENTS
iv Contents
Introduction 197
6.1 Motivation 198 CHAPTER 9
6.2 Roots of Equations: Theory 199 Numerical Integration 259
6.3 Tutorial: Solution of General Nonlinear Introduction 259
Equations Using MATLAB 209 9.1 Concepts from Calculus 259
6.4 Tutorial: Solution of Polynomial Equations 9.2 Tutorial: Numerical Integration of
Using MATLAB 211 Functions 263
6.5 Tutorial: Solution of General Nonlinear 9.3 Tutorial: Numerical Integration of
Equations Using Excel 214 Measured Data 276
CHAPTER 7 CHAPTER 10
Matrix Mathematics 221 Optimization 287
Introduction 221 Introduction 287
7.1 Properties of Matrices 221 10.1 Engineering Optimization 288
7.2 Tutorial: Matrix Operations using 10.2 Formulating an Optimization Problem 290
Excel 225 10.3 Solution of an Optimization Problem 292
7.3 Tutorial: Matrix Operations using 10.4 Solution of an Optimization Problem
MATLAB 230 Using MATLAB 301
10.5 Solution of an Optimization Problem
CHAPTER 8 Using Excel 308
Solving Simultaneous Equations 239 10.6 Tutorial: Engineering Application of Linear
Constrained Optimization 317
Introduction 239
8.1 Systems of Linear Equations 239
8.2 Tutorial: Solutions of Linear Equations INDEX 327
Using Excel 240
ch00_mus80164.qxd 9/2/08 3:42 PM Page v
P R E FA C E
This text has grown out of the authors’ experiences ■ Excel is a ubiquitous spreadsheet application,
teaching introductory computation courses to engi- which nearly every engineering student will
neering students from a variety of disciplines at two have access to during their academic and pro-
different institutions. The integration of computa- fessional careers. Excel has powerful built-in
tional tools in engineering programs is a constant functions that allow it to be applied to high-
challenge for educators. The broad goals associated level engineering problems.
with an introductory course in computer applica- ■ Since spreadsheet solutions are so fundamen-
tions often include: tally different than the procedural solutions de-
■ Teaching the concept of “procedural thinking” veloped using programming tools like
and algorithm development. MATLAB, the contrasting approach allows for
■ Teaching the mechanics of the computational demonstration and discussion about implication
tools required in both the subsequent academic of the choice of software tool on the type and
program and professional practice. complexity of the solution technique.
■ Teaching the techniques for developing a com-
putational solution to a physical problem. Philosophy of the Text
■ Providing the context for the selection of a The underlying philosophy behind the approach
computational tool appropriate for the task at taken in this text is:
hand.
■ Teaching the accepted techniques for docu- ■ Computer tools will change during the profes-
menting and verifying computer-based solu- sional careers of a freshmen engineering stu-
tions to engineering problems. dent. While it is important to teach the
■ Stimulating interest in upper-division course- mechanics of using the relevant tools, the fo-
work by introducing the students to realistic, cus of this text should be on the fundamentals
interesting, and exciting problems and applica- of engineering computing: algorithm develop-
tions. ment, selection of appropriate tools, documen-
tation of solutions, and verification and
This text will emphasize these concepts, using interpretation of results.
MATLAB® and Excel® as the software packages of ■ Programming is a fundamental concept for
choice. These packages were chosen because: engineers; while “shortcut” solutions (such as
■ MATLAB is widely accepted as a first compu- implied loops in MATLAB) and “canned”
tation tool in numerous engineering programs. software are certainly appropriate for upper-
■ MATLAB has the unique ability to be both used division students and practicing engineers,
as an introductory programming tool and a introductory students should be focused on the
high-level computational tool; the programming basics of structured programming: loops,
constructs (loops and logic) allow it to be used logic, and array structures. These basic con-
as a first programming language for engineering cepts, which are language-independent, are the
students, while the numerous mathematical and critical building blocks for programming, and
analysis “toolboxes” allow it to be readily ap- should be introduced early.
plied to high-level engineering applications.
vi Preface
With this in mind, the text was developed in two also allows students to take advantage of Course-
parts. The first part generally covers the mechanics Smart’s web tools for learning, which include full
of programming and spreadsheet usage; including: text search, notes and highlighting, and email tools
for sharing notes between classmates. To learn more
■ An introduction to computational theory,
about CourseSmart options, contact your sales rep-
■ An introduction to number representation
resentative or visit www.CourseSmart.com.
(scalars, arrays, and matrices),
■ An introduction to programming constructs,
including algorithm development and flow- Acknowledgments
charting, We are grateful to our friends at McGraw-Hill for
■ The mechanics of MATLAB and Excel usage, their support and encouragement during this project.
and Lora Neyens, our editor, and Bill Stenquist, our
■ Best practices in computer tool usage, includ- sponsoring editor, have provided invaluable support
ing tool selection, documentation of solutions, and guidance during this project. We wish to thank
and checking of results. Fleck’s Communications for page layout, and Nicole
These chapters include detailed “keystroke-level” Schlutt for copyediting. Additionally, the coopera-
instructions, which will guide the reader through the tion and support of the MathWorks Book Program
use of the MATLAB and Excel tools. was invaluable.
The second part focuses on typical applications Feedback provided during the review process was
of engineering computation; these applications are greatly appreciated, and helped to shape the final
motivated with engineering problems, and include: form of this text. We wish to thank the following re-
■ Root finding, viewers for their careful reviews of the initial manu-
■ Matrix methods, script:
■ Simultaneous equations, Ali Elkamel, University of Waterloo
■ Numerical integration, and Bill Elmore, Mississippi State University
■ Optimization. Howard Fulmer, Villanova University
These applications are intended to motivate not only Brian Grady, Oklahoma University
engineering computation, but the use of concepts Mark Kerstetter, Western Michigan University
from upper-division engineering courses as well. Leo Pérez y Pérez, California State University
Both theoretical concepts and “keystroke-level” tu- at Long Beach
torials are presented in these applications chapters. Michael Robinson, Rose-Hulman Institute of
Technology
David Rockstraw, New Mexico State University
Instructor Resources Scott Short, Northern Illinois University
Additional resources for instructors are available on Elisa H. Barney Smith, Boise State University
the web at www.mhhe.com/best. These resources in- J. Steven Swinnea, University of Texas at Austin
clude solutions to the end-of-chapter problems and Michael Weinstein, University of Rochester
book figures in PowerPoint format. Instructors can Students in the Computing Applications in Engineer-
contact a McGraw-Hill representative for a password. ing course at East Carolina University class tested an
early version of this text; their feedback was appreci-
Electronic Textbook Option ated. Also at East Carolina University, Scott Martin
This text is offered through CourseSmart for both in- provided a thorough reading and review of this text,
structors and students. CourseSmart is an online re- and we thank him for his insight and input.
source where students can purchase access to this
and other McGraw-Hill textbooks in a digital for- Joe Musto
mat. Through their browser, students can access the Ed Howard
complete text online for one year at almost half the Rick Williams
cost of a traditional text. Purchasing the eTextbook
ch01_mus80164.qxd 8/27/08 2:49 PM Page 1
PART 1
COMPUTATIONAL TOOLS
Chapter 1: Computing Tools
1
ch01_mus80164.qxd 8/27/08 2:49 PM Page 2
ch01_mus80164.qxd 8/27/08 2:49 PM Page 3
C H A P T E R 1
Computing Tools
Introduction
The engineering profession is a discipline devoted to problem solving, applying
principles of mathematics and science to develop solutions to practical problems
involving structures, machines, electrical circuits, and various other physical sys-
tems and devices. With their ability to perform numerical analysis and data han-
dling, computers are important tools for practicing engineers. Engineering
graduates from all disciplines are expected to have proficiency in a wide range of
computational tools and software. New engineering graduates should expect to
have proficiency in:
■ communication tools (for e-mail and messaging),
■ Internet search tools (for research),
■ word processing tools (for report preparation and memo writing),
■ presentation tools (for audiovisual presentation),
■ data acquisition tools (for running and reading data from experiments), and
■ computational tools (for programming, data analysis, equation solving, and
plotting).
In addition to these basic tools that cross all engineering disciplines, there are spe-
cific computer tools that are considered part of the core skill set for each engi-
neering discipline. Examples of these tools include:
■ solid modeling and computer-aided design/drafting software (for mechani-
cal and civil engineers),
■ electric circuit simulation software (for electrical and computer engineers),
■ finite element analysis software (for mechanical, civil, and electrical
engineers),
■ advanced programming languages (for computer and software engineers),
and
■ statistical analysis software (for industrial engineers).
3
ch01_mus80164.qxd 8/27/08 2:49 PM Page 4
Figure 1.1
MATLAB® is a trademark of The MathWorks, Inc. Excel® is a trademark of the Microsoft group of
companies.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 5
sin
t= (1.4)
g
Substituting in the known values for launch speed, angle, and gravitational accel-
eration and carrying out the arithmetic yields:
⎛ 10.0 m ⎞ sin(35.0°)
⎜ ⎟
t=⎝
s ⎠ (1.5)
⎛ 9.81 m ⎞
⎜ ⎟
⎝ s2 ⎠
or t = 0.585 seconds. This indicates that the ball will reach its peak height after
0.585 seconds of flight time. Substituting this value for time into Equation 1.1
yields:
To determine the total flight time and horizontal distance travelled, the engineer
uses Equation 1.1 to determine the time at which the height of the ball is zero:
The engineer reports the results in Table 1.1, with appropriate units:
The engineer has an equation to compute the height of the ball at any time t. The
engineer recognizes that the cannonball starts and ends at a height of zero, and
will reach its peak somewhere in the middle. For the first part of the flight, height
is increasing; during the second part of the flight, height is decreasing. If the engi-
neer can identify the point where the height stops increasing and starts decreas-
ing, the point of peak height will be identified. The engineer constructs the
following algorithm for identifying the peak height; the solution steps, provided
in verbal descriptions called pseudocode, are as follows:
■ Step 1: Start at a time value of t = 0 and h = 0.
■ Step 2: Increase time by adding some small value Δ t to t (e.g., tnew = t +
Δt).
■ Step 3: Plug the new value of tnew into Equation 1.1 to get a new value of h,
which we will call hnew.
■ Step 4: Compare h and hnew:
■ If h < hnew, then the height is still increasing, and the peak has not been
reached. Set t = tnew, h = hnew , and return to Step 2.
■ If h > hnew, then the height has started decreasing. This tells us that the
ball reached its peak somewhere in the neighborhood of h (either in the
interval between h and hnew, or in the previous interval).
■ Step 5: Assume that the maximum height occurs at the height at the start of
the interval, or hmax = h.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 8
The algorithmic solution is a “road map” to the solution of the problem; it is not
an answer itself, but is a series of specified steps that will lead to an answer. The
main computational part of the algorithm, embodied in Steps 2 through 4, may
need to be repeated multiple times before a solution is reached; there is no par-
ticular way to tell ahead of time how many times the algorithm will “loop” back
to Step 2 before a solution is found. Note that this algorithmic solution uses arith-
metic operations only; unlike the analytic approach, no principles of calculus or
algebra are required. However, note that there is a critical approximation used in
the algorithm; the height is only computed for specific values of t, but it is likely
that the actual peak value occurs at some intermediate value.
The engineer carries out the algorithmic solution, using a time step value of
Δ t = 0.1 seconds. The values of each variable at each “loop” through Steps 2
through 4 are shown in Table 1.2:
The engineer proceeds to construct a solution algorithm for finding the point at
which the cannonball strikes the ground. The engineer recognizes that a height
value of zero indicates the point at which the cannonball hits the ground, and the
time at which this happens is the total flight time. The algorithm is as follows:
■ Step 1: Start at a time value of t = 0 and h = 0.
■ Step 2: Increase time by adding some small value Δ t to t (e.g., tnew =
t + Δ t).
■ Step 3: Plug the new value of tnew into Equation 1.1 to get a new value of h,
which we will call hnew.
■ Step 4: Check the value of hnew:
■ If hnew > 0, then the cannonball is still in flight. Set t = tnew, h = hnew,
and return to Step 2.
■ If hnew < 0, then the cannonball hits the ground somewhere between h
and hnew.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 9
t + tnew
■ Step 5: Approximate the total flight time by setting t flight = .
2
■ Step 6: Find the horizontal distance travelled during the flight by
substituting tflight into Equation 1.2. End the algorithm.
The engineer again executes the algorithm, with Δ t = .1 seconds. The values at
each step of the algorithm are shown in Table 1.3:
Table 1.3 Step-by-Step Solution Algorithm for Finding Flight Time and Distance Travelled
t tnew hnew
Loop (sec) (sec) (m) Step 4 Decision
1 0 0.1 .52 hnew > 0, loop back to Step 2
2 .1 .2 .95 hnew > 0, loop back to Step 2
3 .2 .3 1.28 hnew > 0, loop back to Step 2
4 .3 .4 1.51 hnew > 0, loop back to Step 2
5 .4 .5 1.64 hnew > 0, loop back to Step 2
6 .5 .6 1.68 hnew > 0, loop back to Step 2
7 .6 .7 1.61 hnew > 0, loop back to Step 2
8 .7 .8 1.45 hnew > 0, loop back to Step 2
9 .8 .9 1.19 hnew > 0, loop back to Step 2
10 .9 1.0 0.84 hnew > 0, loop back to Step 2
11 1.0 1.1 0.38 hnew > 0, loop back to Step 2
t + tnew
12 1.1 1.2 –0.17 hnew < 0, set tflight = . and find distance
2
using Equation 1.2. End the algorithm.
The results from these two algorithms are reported by the engineer, as shown in
Table 1.4:
at, or midway between, our discrete points. However, while the algorithm will
always produce an approximate solution, the spacing between the discrete points
is under the engineer’s control; the solution can be made more accurate by
decreasing the value of Δ t used in the algorithm. For example, if the algorithm
was repeated, but with a value of Δ t = 0.001 seconds, the results would be exactly
the same as those reported for the analytic solution. However, to achieve this
increased accuracy, the algorithm would need to “loop” through Steps 2 through
4 many more times (1680 times to find hmax, instead of seven).
Since analytic solutions are exact, and algorithmic solutions are approximate, why
should algorithmic solutions be used at all? In our example case, there is really no
need for an algorithmic solution, since the problem is readily solved using analytic
techniques. An engineer with a background in differential calculus and algebra
could readily arrive at an analytic solution. When this is the case, an analytic solu-
tion is the preferred approach. However, in the professional practice of engineer-
ing, this is not always the case. Even in your undergraduate studies, you will soon
encounter problems that you lack the mathematical background to solve, and even
some where no analytic solution exists. It is at these times that algorithmic solu-
tions become an important option. You have likely already used algorithmic solu-
tions to solve otherwise difficult or unsolvable problems; if you have used a root
finding function on your programmable graphic calculator to find the roots of a
higher-order algebraic equation, you have used an algorithmic solution technique
derived and implemented by the calculator’s manufacturer. (Did you realize that
the answers you obtained with your calculator were approximate?)
Another hallmark of an algorithmic solution is that there is not one unique algo-
rithm that will solve a specific problem. Development of solution algorithms
requires a combination of mathematical reasoning and creativity. Computer sci-
entists focus on the development of efficient computational algorithms that min-
imize the computer time and memory used when running a program based on
ch01_mus80164.qxd 8/27/08 2:49 PM Page 11
their algorithm. In this text, we will focus on implementing and using many stan-
dard solution algorithms; however, there is still much room in the field of engi-
neering computation for the development of new and creative algorithms for
solving engineering problems.
instruction sets provided by the programming tools available. While the look of
the programming languages and the interface used to communicate with the
machine have evolved significantly, the idea of translating an algorithm into
software-specific instructions is a classic paradigm for computation.
Figure 1.3
Figure 1.4
ch01_mus80164.qxd 8/27/08 2:49 PM Page 13
y−6
x= (1.11)
3
Does this mean that y is the independent variable? We must go beyond the equa-
tion and examine the problem that it represents in order to determine which one
is the independent variable. We do know that both x and y cannot be indepen-
dent, because when we assign a value to one of them, the value of the other can
be determined from the equation.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 14
1 2
h = vt sin − gt (1.12)
2
where ν = initial velocity
t = time
θ = launch angle
g = gravitational acceleration
There are five quantities related by symbols in this equation; however, they are
not all variables in the problem. We are considering the initial velocity, launch
angle, and gravitational acceleration to be constants rather than variables. This is
not evident in the equation, but rather in the problem statement. Suppose the
problem statement was changed so that we were asked to calculate the height at
time t = 2 seconds for various values of the launch angle. In this case, time would
be a constant and the launch angle a variable, but the equation would be
unchanged. In another version of the problem, we might be asked to find the max-
imum height that can be attained for any launch angle. In this case, height, launch
angle, and time would all be variables.
Going back to the original problem, with the initial velocity, launch angle, and
gravitational acceleration all considered to be constants, we say that the height is
a function of time, and will often write the left side of the equation as h(t), as in
Equation 1.1. Therefore, time t is the independent variable, while height h is
dependent on time. To be more precise, a function is defined as follows: A func-
tion is a mathematical operation that returns a single value for a given input
value or set of values. The input values are called the arguments of the function.
Both Excel and MATLAB have many built-in functions. Many of these functions
require a single argument. For example, the cos function in MATLAB returns the
cosine of an input value of an angle in radians. Other functions require a specific
number of multiple arguments. For example, Excel has a function called ROUND
which requires two arguments: the number to be rounded off and the number of
decimal places to which the number is to be rounded. Still other functions have a
variable number of arguments. An example is the AVERAGE function in Excel,
which finds the average of a group of values entered as arguments. In MATLAB,
there are a number of functions that use arrays or matrices as arguments, which
we shall discuss in subsequent chapters. (Note that the convention in this text is
to refer to MATLAB functions in italics, and Excel functions in capital letters).
at each increment. We continued to make calculations until the value of the height
began to decrease, indicating that the peak height was attained. We chose a time
increment of 0.1 seconds. The results of this analysis are repeated in Table 1.5:
■ Trying to use zero as an index. In our example, the first value of time is
zero. Therefore, it is tempting to start an array with t (0) = 0. This will
result in the following error in MATLAB:
>> t(0) = 0
??? Subscript indices must either be real positive
integers or logicals.
■ Trying to use non-integer indices. For example, the statement “t (.1) = 0.1”
would result in the same error as above.
■ Progressing index values by increments other than one. For example, sup-
pose that you are performing an experiment in which you take temperature
readings every 10 seconds. Your first reading is 100°C, so you enter this as
T(10) = 100. In this case, there will not be an error, but rather an array is
created with T(1) through T(9) all having values of zero:
The arrays shown above are one-dimensional arrays. That is, a single index num-
ber is used to establish the identity of a value in the array. Arrays can also be mul-
tidimensional. In the example illustrated in Table 1.5, note that there are two
values of time for each loop: t and tnew. Instead of storing these values in two one-
dimensional arrays, we can store them in a single two-dimensional array. If we
assign the first index a value of 1 or 2, representing t and tnew, respectively, and
assign the second index the value of the loop number, then all 14 values will be
stored in an array. As an example of this scheme, t(1,5) = 0.4 and t(2,5) = 0.5.
The size of a matrix is defined by its number of rows and columns. For example,
the matrix below is a (3 × 2) matrix (pronounced “three by two matrix”), with
three rows and two columns:
⎡3 2⎤
⎢7 −5 ⎥
⎢ ⎥
⎣6 12 ⎦
It is important to note here that there is another definition of the term vector that
you will encounter in physics and engineering mechanics. In that context, a vec-
tor quantity is one that is defined by a magnitude and a direction. For example,
velocity is a vector quantity. In addition to its magnitude (speed), the direction of
motion is necessary to completely define a velocity. One method to define a vec-
tor quantity is to define its components in the x, y, and z directions. Of course,
these three components can be placed in a one-dimensional array, fitting the
MATLAB definition of a vector. Because of the confusion that can be created by
the two definitions, in this text we will avoid using the term vector when refer-
ring to a one-dimensional array. Instead, we will use the more general term array
when referring to the storage of multivalue variables, and matrix when referring
to one- and two-dimensional arrays for which we will perform matrix mathe-
matics operations.
Excel also has the ability to represent and manipulate arrays. Data entered into
the cells of spreadsheets can be interpreted as matrices, and operated upon using
matrix mathematics. In Excel, these operations are performed using prewritten
functions (like those described in Section 1.3.1) specifically developed for matrix
computation. Unlike MATLAB, which was developed specifically for matrix
operations and where matrix and scalar computations are performed with the
same mathematical operators, matrices require special handling when using
Excel. These methods will be described in Chapter 7 of this text.
The precision of the solution depends on how well the input variables are known,
and on how numerical values are stored from one calculation to another. In the
cannonball problem, the launch angle was given as 35°. But how precise is this
value? Depending on how the cannon’s launch angle is set and measured, the
value might be precise to the nearest degree, the nearest one-tenth of a degree, or
the nearest 5°.
In the sciences, the precision of measured input variables are usually known, and
calculation results are reported based on the number of significant digits of the
input. For numbers containing decimal points, the number of significant digits of
a number is defined as the number of digits between the first non-zero digit and
the last digit. Consider these examples:
When making calculations, the answer can only be as precise as the least precise
of the input values. For addition and subtraction, this means that the number of
digits to the right of the decimal point in the answer must be equal to the least
number of digits to the right of the decimal point in any of the inputs. Examples
include:
For multiplication and division, the number of significant digits in the answer
must equal the least number of significant digits of the input values. Examples
include:
Some quantities are exact. For example, there are exactly 12 inches in a foot. So
if we want to convert 11.556 inches to feet, the answer is:
⎛ 1 ft ⎞
(11.556 in) ⎜
⎝ 12 in ⎟⎠
= 0.96300 ft
In this case, the exact value of 12 inches per foot is considered to have an infinite
number of significant digits.
The precision of quantities without a decimal point is not always known. For
example, as we discussed previously, we may not know the precision of the 35°
ch01_mus80164.qxd 8/27/08 2:49 PM Page 19
elevation angle in the cannonball problem. This is a typical situation in most engi-
neering problems, with at least some of the input quantities of unknown preci-
sion. Therefore, the rules for calculations described previously cannot be applied.
Rather, a reasonable number of significant digits should be reported. Many engi-
neering texts suggest three significant digits for final answers (some recommend
four significant digits if the first significant digit is a one). When performing cal-
culations by hand, intermediate results should be carried to more significant dig-
its than will be reported for the final answer. For example, you cannot round the
value of the sine of 35° to 0.57 and then report the final answer to more than two
significant digits.
With computing solutions, intermediate calculations are not rounded off, so the
precision of the final answer is usually dependent only on the precision of the input
values. The qualifier “usually” in the previous sentence must be added because
there are some instances, when working with combinations of very large and very
small values, where errors will accumulate in computing solutions as well. For
example, when analyzing mechanical structures using a computational technique
known as finite element analysis, tens or hundreds of thousands of simultaneous
equations are solved. If the numerical values in these equations differ by orders of
magnitude, then the solution algorithm of the program must be designed in a way
that minimizes computational errors. For the problems encountered by most engi-
neering students and practicing engineers, this is not a concern. How precise are
the values stored in Excel and MATLAB? Excel carries values to 15 significant
digits. By default, MATLAB stores values as double-precision values, which also
have approximately 15 significant digits. The term double-precision refers to the
fact that these values require two 8-bit units of computer memory to store, while
single-precision values are stored in a single unit of memory. In the early days of
computing, storage space was severely limited, so double-precision values were
used only when necessary to ensure sufficient precision of calculations. Process-
ing times were also increased when double-precision values were used. With
today’s inexpensive computer hardware and fast processors, there is rarely a need
to use single-precision values, although MATLAB does support single-precision
values for working with extremely large data sets.
One final thought about accuracy and precision is warranted. When formulating
a computer solution to a problem, many students will report the final answer to
whatever precision is displayed on the computer screen, even though they rou-
tinely round the answers of hand calculations to a reasonable precision. In doing
so, they are treating the computer solution as a “black box,” with no considera-
tion of what is happening between the inputs and outputs. When a computer solu-
tion is reported to a reasonable number of significant figures, a student conveys
the impression that he or she is aware of the assumptions and approximations
associated with the problem. Engineering students and practicing engineers
should take care to interpret the results of their computations, and report the
results to a reasonable level of precision, regardless of the computer’s output.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 20
Problems
1.1 Describe the differences between analytic and algorithmic solutions.
1.2 Develop the pseudocode for an algorithmic solution for finding the two
points where the function f (x) = 3x2 – 12.4 x + 3 crosses the x-axis.
1.3 Consider the cannon model developed in Section 1.1.1.
a) Using the equations developed and a launch speed of 10.0 m/s,
develop the pseudocode for an algorithmic solution to determine the
launch angle required to reach a peak height of at least 2.5 meters.
b) Using discrete values spaced 5° apart, carry out the algorithmic solu-
tion by hand. Report each step of the algorithm in a table.
c) Perform an analytic solution for this problem, and compare the result
with your algorithmic solution.
1.4 Consider the cannonball problem described in Section 1.1.1. You have been
asked to determine a combination of launch speed and angle required to
clear a 5-meter wall erected 8 meters from the launch point. The maximum
launch speed of the cannon is a known value. Develop the pseudocode for
an algorithmic solution to this problem.
1.5 Develop and write the pseudocode for an algorithm that can take a list of
10 integers and determine how many are even numbers.
1.6 An engineer measures the diameters and lengths of a number of steel rods.
Calculate the cross-sectional area and total volume of each of the rods, and
report the answer using the correct number of significant digits.
Rod Diameter Length
A 0.125 in 12.80 in
B 0.13 in 1.1 ft
C 0.1250 in 1.1 ft
D 0.01250 in 1.067 ft
E 0.38 in 8.11 in
F 0.3750 in 8.110 in
G 0.3750 in 8.1 in
H 1.2 in 5.29 in
I 1.20 in 5.290 in
J 1.200 in 5.3 in
1.7 Using your computer, research and document a value for the density of steel.
Use the value to determine the weight of each rod described in Problem 1.6,
reporting each answer using the correct number of significant digits.
1.8 Find and read the article entitled “Failed Promises” by noted engineering
historian Henry Petroski, published in the January–February 1994 issue of
American Scientist. Write a short summary of the article, describing its rel-
evance to the field of engineering computation.
1.9 In July 1969, the United States achieved the monumental goal of landing a
man on the moon, an achievement even more remarkable considering the
computing hardware and software available at that time. From the NASA
History Division’s Apollo Flight Journal (http://history.nasa.gov/afj), find
and read the journal essay “The Apollo On-board Computers” by Phill
Parker. Write a short summary of the article, comparing the tools available
to the Apollo program to those available to you today.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 21
C H A P T E R 2
Excel Fundamentals
Introduction
The Excel computing environment is widely used for both technical and non-
technical problem solving, data analysis, and display. It is employed in most
industrial, business, and academic institutions. Excel uses a format known as a
spreadsheet that can be used to complete simple calculations, sort and analyze
data, and create charts or graphs of the results. It also has powerful built-in cal-
culation and analysis tools that can be used to solve many engineering problems
as well as other related problems in areas such as statistics and finance. Data
from most engineering analysis instruments is easily imported into the Excel
environment where additional analyses and calculations can be performed. The
results (generally graphs and tables) can be easily imported into Microsoft Word
and PowerPoint for use in reports and presentations.
21
ch02_mus80164.qxd 8/27/08 2:49 PM Page 22
Figure 2.2
Focusing on the top region of the spreadsheet, there are several toolbars and win-
dows that appear, as shown in Figure 2.3:
■ The Office Button: This button is contained in all Microsoft Office 2007
products. Clicking on the Office Button in Excel opens up a menu box
where you can perform tasks such as creating, opening, saving, printing,
and e-mailing a spreadsheet. The Office Button also contains a link for set-
ting custom options or adding additional features to a spreadsheet
■ The Quick Access Toolbar: This is where you can open a new or existing
spreadsheet, and save, print, and e-mail a spreadsheet. It also contains the
“undo” and “redo” tools. By clicking on the down arrow located to the
right of the Quick Access Toolbar, you can customize the toolbar as you
see fit.
■ The Title Window: The title of the Excel spreadsheet appears in this win-
dow. Knowing the title can be convenient when working simultaneously
with several spreadsheets.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 23
Figure 2.3
■ The Ribbon: This is the main toolbar where most of the commands
required to complete the tasks to create and edit the spreadsheet reside.
Commands are tabulated by logical groups. The most commonly accessed
commands are under the “Home” tab. The tools available in the Ribbon
depend on the activity that is currently being worked on, so the tabs change
as activities change. Within each tab, tools are grouped by category with
the most commonly used tools displayed. As an example, under the
“Home” tab, the Font tool allows you to easily change the font type, size,
appearance, fill color, and more. The tutorials in this chapter are designed
to help you become familiar with many of the tools located on the Ribbon.
Also located in the upper right-hand corner of the Ribbon (but not shown
on Figure 2.3) is the “Excel Help” icon which is shaped like a question
mark. Clicking on this icon will activate a help window that can be navi-
gated by keywords.
■ The Workbook Window: This is the core of the spreadsheet where data and
formulas reside. The Workbook Window is divided up into cells. Cells are
addressed by their column and row. For example, the cell in the uppermost
left corner is in column “A” and row “1” and is addressed as cell A1. Cells
are “activated” for entering data and editing by clicking on the cell. The
active cell will have a bold box around it and the respective column and
row will be highlighted.
■ The Active Cell Address: This window displays the active cell or range of
active cells and is convenient to reference when selecting or editing large
ranges of data.
■ The Formula Window: This window displays the formula or data entered
into the active cell. Formulas and data can be entered or edited in this
window.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 24
There are also several features located at the bottom of the Workbook Window,
as shown in Figure 2.4:
■ The Worksheet Tabs: These tabs allow you to select any of the worksheets
that may be in your spreadsheet or workbook. Each sheet may contain
independent calculations or may be linked via the data or formulas. By
right-clicking on the worksheet name, you can move, copy, delete, hide,
unhide, insert, or rename a worksheet. The arrow icons to the left of the
worksheet tabs allow you to scroll through the tabs when there are too
many worksheets to display. The icon to the right of the worksheet tabs
allows you to insert a new blank worksheet.
■ The Status Bar: This area is used to display information such as cell count,
permission status, and macro recording status. The information displayed
can be controlled by right-clicking on the status bar and selecting from the
menu.
■ The View Toolbar: This toolbar allows you to change the appearance of the
Workbook Window. By changing from “Normal” to “Page Layout” mode
you can see what the spreadsheet will look like when printed while still
building or editing the spreadsheet. This function is very handy when you
are using the spreadsheet to create a form. The “Page Break Preview Tool”
is used to set the page break locations. These View tools can also be
accessed through the Ribbon under the View tab.
■ The Zoom Slider: This slider tool allows you to zoom out or in on the
workbook window from 10% to 400%. It is very useful to zoom in when
working on a laptop computer.
Figure 2.4
Next, enter the following aircraft classes into cells A2:A8: “Autogyro”, “Rotor-
craft”, “Biplane”, “Piston Powered”, “Turboprop Powered”, “Jet Powered”,
and “Rocket Powered”.
Now enter the following record setters into cells B2:B8: WA-116F, Westland
Lynx, Fiat CR42B, Grumman F8F Bearcat, Tupolev Tu-114, Lockheed SR-
71A, North American X-15A-2. Now enter the following dates into cells C2:C8:
“9/18/1986”, “8/11/1986”, “1941”, “8/21/1989”, “4/9/1960”, “7/28/1976”, and
“10/3/1967”.
Finally, enter the following speeds into cells D2:D8: “120.5”, “249.1”, “323”,
“528.33”, “545.07”, “2193.16”, and “4520”.
Figure 2.7
ch02_mus80164.qxd 8/27/08 2:49 PM Page 26
Next, center all of the data by selecting cells A1:D8 and then
clicking the Center tool in the Alignment group on the Ribbon,
as shown in Figure 2.8.
Now let’s put some borders around the table. The order in which
you apply borders is important, as one step can undo a previous
step. First, apply a border around the data (excluding the table
headers) by selecting cells A2:D8. Next, click on the drop-
down menu for the Borders tool located in the Font group on
Figure 2.8
the Ribbon and then select All Borders, as shown in Figure
2.9.
With cells A2:D8 still selected, apply a thick border around the perimeter by
selecting the Thick Box Border tool.
Next, we can apply thick borders around each of the header titles. We could do
this one at a time, or save some steps by selecting each cell first before applying
the border. To select each cell, click on cell A1, hold the CTRL key, and then
click on cells B1, C1, and D1 one at a time. After selecting the cells, apply a
thick border around the perimeter of each cell by selecting the Thick Box Bor-
der tool.
Finally, we can add a little color to the header. Select cells A1:D1, click the drop-
down menu for the Fill Color tool located in the Font group on the Ribbon, and
then select a color, as shown in Figure 2.10. Notice how the color is previewed
as you place the cursor above the palette. Be sure to select a color that keeps your
headers readable.
Your table is now very readable and presentable and should look similar to Fig-
ure 2.11. As you build spreadsheets, appearance is very important to consider
even if you do not plan to use the spreadsheet in a report or presentation. Having
data and formulas grouped, organized, and labeled facilitates programming,
debugging, sharing, and general usability of the spreadsheet. Good formatting in
Excel is emphasized throughout this textbook.
Figure 2.11
Excel also has the ability to sort data. In our table, it may be interesting to sort the
speed records chronologically. Select cells A1:D8, select the Sort and Filter
tool, and then Custom Sort from the Editing group on the Ribbon, as shown in
Figure 2.12. Figure 2.12
The Sort dialog box, as shown in Figure 2.13, appears. Select Date from the
Sort by drop-down box, ensure My data has headers is checked and then select
OK. The aircraft speed records are now sorted chronologically and it is easy to
see that the oldest-standing speed record is the biplane, whereas the most recent
speed record is the piston-powered Grumman F8F Bearcat.
To return the table to the speed sorted format, we could use the Sort tool again
and select Sort by Speed; however, there is a quicker method. Excel has Undo
Figure 2.13
ch02_mus80164.qxd 8/27/08 2:49 PM Page 28
and Redo tools that are very useful. Click on the Undo tool located in
the Quick Access Toolbar, as shown in Figure 2.14, to undo the Sort
by date.
Figure 2.14
It is a good idea to periodically save your work. To save this spread-
sheet, select the Save icon on the Quick Access Toolbar, as shown in
Figure 2.15, and then give the file a name of your choice.
Now with cells A1:A8 still highlighted, select the Format as Table tool
from the Styles group located on the Ribbon, and then select any one
of the table formats, as shown in Figure 2.17. Next, make sure the
“My table has headers” box is checked in the pop-up Format As
Table dialog box, as shown in Figure 2.18, and then click OK.
Figure 2.16
Your table should look similar to Figure 2.19. Notice that the format of the date
is no longer correct. When you originally typed in the dates in the month/day/year
format, Excel automatically recognized the date format. When the format was
cleared, Excel changed the format to General. Under this format, the date is
displayed as a value based on a sequence that starts with the numeral 1 on
January 1, 1900. Each day after January 1, 1900, is indexed by one such that the
date of December 31, 1900, is assigned the numeral of 366 (1 + 365); hence, the
values displayed in the table now represent the number of days past December
31, 1899. This assignment of a value to the date allows us to calculate the num-
ch02_mus80164.qxd 8/27/08 2:49 PM Page 29
Figure 2.19
ber of days between events and it should be noted that the value assigned exists
regardless of the display format. Excel does not assign values to dates prior to
January 1, 1900, and therefore calculations with earlier dates cannot be easily
performed.
Let’s change the date back to month/day/year format. Select column C by click-
ing on the column header and select the Short Date format from the pull-down
menu located on the Number group on the Ribbon, as shown in Figure 2.20.
Your dates should return to the desired format with the exception of the Biplane.
Since the Biplane date was entered as just the year, Excel interprets that as the Figure 2.20
number of days past December 31, 1899, which is April 24, 1905.
This highlights the necessity of ensuring your data is in a consistent
format. Since we do not know the precise date in 1941 on which the
record was set, we have several options. We could do additional
research to try to pin down the date, or we could display only the
year for this date. First let’s assume a midyear date of June 30, 1941.
To edit the date, click on the incorrect Biplane date, type in
“6/30/1941”, and press the Enter key on your keyboard or click on
the Enter checkmark located on the left side of the Formula Win-
dow. Next, select the cell containing the Biplane date and then
select More Number Formats from the pull-down menu located
on the Number group on the Ribbon. Finally, select custom as the
Category and type “yyyy” as the Type and then select OK as shown
in Figure 2.21 Figure 2.21
Figure 2.23
Open Excel, or if Excel is already open, open a new workbook by selecting the
Office Button, and then selecting New. The New Workbook dialog box
will appear, as shown in Figure 2.24. Select Blank Workbook and then click
Create.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 31
We can label the gear ratios as gear numbers 1–10, representing the possible num-
ber of ratios between the front and rear sprocket diameters or number of teeth for
a given chainring. The gear ratio represents the number of times the rear wheel
will rotate with one revolution of the pedals. In this example, a low gear number
will have the lowest gear ratio and be easiest to pedal.
There are many times that you may want to create a sequence in Excel. In this
case, we would like to continue the sequence of indexing each
cell by an increment of one. Excel can recognize this and con-
tinue the sequence automatically. Select cells A6 and A7 and
then grab the “fill handle” on the lower right-hand side of the
selection box, as shown in Figure 2.25. Drag the box down-
ward to cell A15 to fill in the sequence to the number 10. Figure 2.25
Notice how the value in the last cell is displayed as you drag
downward.
Cassettes are available with various size cogs. A rider may choose to change a
cassette based on the terrain. For example, if you were planning on riding in the
mountains, you would want a cassette that had larger cogs available to provide
the lower gear ratio needed to climb. The cassette in this example has ten cogs
with 12, 13, 14, 15, 16, 17, 19, 21, 24, and 27 teeth, respectively.
Now type in the number of teeth, starting with the largest cog and working to
the smallest, into cells B6:B15.
Now we will calculate the gear ratio between the small chainring and each cog of
the cassette. The gear ratio can be defined as the number of teeth on the chainring
ch02_mus80164.qxd 8/27/08 2:49 PM Page 32
divided by the number of teeth on the cassette. We can enter a formula into Excel
to perform this calculation.
Excel can perform basic arithmetic as well as advanced calculations using built-
in functions. In all cases, formulas must begin with an “=” sign. For example, the
formula =3+4*2 multiplies 4 by 2 and then adds 3 to the result. Formulas may
contain functions, operators, references, or constants. Excel is not case sensitive;
however, Excel automatically capitalizes formulas and for consistency, Excel
formulas are capitalized in this text. A formula that calculates the area of a circle
based on its radius could be = PI()*B4^2, where PI() is the Excel function for π,
B4 is a reference cell that contains the value of the radius, * and ^ are operators
for multiplication and exponentiation, and 2 is a constant. Other operators com-
monly used in Excel are +, -, and / for addition, subtraction, and division, respec-
tively. There are many other operators available for mathematical operation; a
subset of the most common operators that you may use is shown in Table 2.1.
Type the formula “=B1/B6” into cell C6, and press the Enter key. This formula
takes the value in cell B1, which is the number of teeth on the small chainring,
and divides it by the value in cell B6, which is the number of teeth on the cassette
cog. Instead of typing the formula from the keyboard, an alternate method of
entering the formula is: select the location of the formula (cell C6) and type “=”,
select cell B1 by clicking on the cell, type the “/”, select cell B6 by clicking on
the cell, and finally close the formula by hitting the Enter key or clicking on the
checkmark in the Formula Window. It is normally faster to enter formulas using
this point-and-click method since you do not have to worry about the actual cell
reference number and you are less likely to make an error. Throughout the
remainder of the text, directions to enter formulas will continue to be given as if
they are to be typed in; however, it is expected that you will use the point-and-
click method as you become more proficient.
One of Excel’s powerful features is the ability to easily perform repetitive calcu-
lations. We can copy this formula down the column by using the fill handle.
Select cell C6, grab the fill handle, and drag down to cell C15. Your
Small Ring Gear Ratio calculations should look like Figure 2.26.
Hopefully you agree that something is not correct!
Click on cell C7. The formula should read “B3/B8”. Since there is no
value in cell B3, Excel assigns a value of zero and returns an answer
of zero. What we really want in this cell is the formula “B1/B8”.
When we copy formulas from one cell to another, Excel changes the
reference cells in the formula by the number of columns and rows
between the copy and paste cell locations. In this example, we copied
the formula “B1/B6” from cell C6 to cell C8, so that the row num-
Figure 2.26
bers indexed by +2 and the formula became “B3/B8”. In many cases,
such as this one, we desire to hold one of the references constant. We
can do this by modifying the formula. The “$” placed in a reference prior to the
column letter fixes the column as the formula is copied. Similarly, a “$” placed
in a reference prior to the row number fixes the row as the formula is copied. Plac-
ing the “$” prior to the column and row fixes the cell as the formula is copied.
Before we correct this, look at cell C10. The term “#VALUE!” means
that Excel cannot evaluate the formula in the cell. Double-click on
cell C10. Notice that the formula is displayed in the cell as well as
the Formula Window and that it is color-coded with the reference
cells boxed in with the same color as in the formula, as shown in
Figure 2.27.
Figure 2.27
ch02_mus80164.qxd 8/27/08 2:49 PM Page 34
This display is very handy for troubleshooting incorrect formulas. Here we see
that the formula is incorrectly referencing cell B5, which contains a label, result-
ing in the error message. We can quickly correct this. Place the cursor at the edge
of the blue box around cell B5 until the move arrows
appear, as shown in Figure 2.28, and then drag the box up
to the correct location, cell B1. Click on the checkmark in
the Formula Window or hit Enter to close the formula.
Figure 2.28 Now let’s correct all the cells by adding a fixed (also called
absolute) reference for cell B1.
Double-click on cell C6 and then click next to the reference cell B1 (it does not
matter if you click before, after, or within the reference), as shown in Figure
2.29. Next, press the F4 key on your keyboard and Excel will add the “$” before
both the column letter and the row number. Notice that each time you press F4,
the cell reference changes from fixed cell, to fixed row, to fixed column, and then
back to relative. The F4 key also works when you are first entering
the formula and is a handy way to change references, especially
when you are using the point-and-click method of selecting cells.
Close the formula using the checkmark or the Enter key, select cell
Figure 2.29 C6, and then grab the fill handle and recopy the corrected formula
downward to cell C15. Your calculated Small Ring Gear Ratios
should be similar to those illustrated in Figure 2.30.
Figure 2.31
ch02_mus80164.qxd 8/27/08 2:49 PM Page 35
Next, we will calculate the gear ratios for the large chainring and cassette cogs.
Type “Large Ring Gear Ratio” into cell D5.
Type the formula for the gear ratio between the large chainring and 27-tooth
cog, “=$B$2/B6”, into cell D6. Now, select cell D6 and double-click on the fill
handle to automatically copy the formula down to the bottom of the adjacent
column. The double-click method is faster than dragging the fill handle, but only
works if there is an immediately adjacent filled column.
With cells D6:D15 selected, use the Decrease Decimal tool to display two deci-
mal places.
Next, we will calculate the distance that the bicycle travels per one revolution of
the pedals for each gear ratio. The rear wheel is directly coupled to the cassette
such that every time the cassette completes one revolution, the rear wheel com-
pletes one revolution. The distance that the rear wheel travels is its circumfer-
ence, or πD. Most road bikes have a wheel diameter, D, of 700 mm, so we will
assume this diameter for this analysis. Since the gear ratio, GR, represents the
number of times the cassette rotates per one revolution of the pedals, the distance
in feet travelled per one revolution, d, is calculated in Equation 2.1:
1 ft
d = GR × π × D × (2.1)
304.8 mm
Type “Wheel Diameter (mm)” and “700” into cells A3 and B3, respectively.
Type “Small Distance (ft)” and “Large Distance (ft)” into cells E5 and F5,
respectively.
To calculate the Small Distance for the 27-tooth cog, type the formula
“=C6*PI()*$B$3/304.8” into cell E6. Next, use the fill handle and copy this
formula to the right into cell F6, as shown in Figure 2.32, and then double-click
on the fill handle to simultaneously copy the formula down in both columns.
Figure 2.32
ch02_mus80164.qxd 8/27/08 2:49 PM Page 36
Next, change the number format to display two decimal places for the distance
travelled, adjust all column widths so that the headings correctly display, and
align all the data to the center of the cell. Your spreadsheet should look similar
to Figure 2.33.
Figure 2.33
Our final calculation of this analysis is to calculate the speed of the bicycle, which
of course depends on the gear selected and how fast the rider is pedaling. The
pedaling speed, or cadence, N, is normally expressed in revolutions per minute
(RPM). In order to maintain a fairly steady cadence, riders adjust the gears as
required by the terrain, wind, or other conditions. A common cadence is 90 RPM.
The bicycle speed in miles per hour (mph) is given in Equation 2.2:
⎛ 60 min ⎞ ⎛ 1 mile ⎞
Speed = N × d × ⎜ × (2.2)
⎝ 1 hr ⎟⎠ ⎜⎝ 5280 ft ⎟⎠
We can insert new rows or columns as needed and Excel automatically changes
the references in the formulas so that they are correct. To add a new row 4, select
ch02_mus80164.qxd 8/27/08 2:49 PM Page 37
Next, insert a row by clicking on the Insert Cells tool from the Cells
group located on the Ribbon, as shown in Figure 2.35.
Figure 2.34
Now type “Cadence (RPM)” and “90” into cells A4 and B4, respec-
tively.
Type “Small Speed (mph)” and “Large Speed (mph)” into cells G6
and H6, respectively. Then type in the formula for speed,
“=$B$4*E7*60/5280”, into cell G7 to calculate the speed for the
small chainring on the 27-tooth cog. Next, use the fill handle to
copy the formula to the right and then down. Now, change the num-
ber format to display two decimal places, adjust all column widths
so that the headings correctly display, and align all the data to the
center of the cell. Finally, add some borders around each of the two Figure 2.35
tables and some color to the cell background of the table headers.
Save your spreadsheet. Your completed spreadsheet should look
similar to Figure 2.36.
Figure 2.36
An inspection of our analysis reveals that a 20-speed road bike really does not
have 20 different speeds or gear ratios. Looking at the gear ratios in this exam-
ple, they run from 1.44 to 3.25 on the small chainring and from 1.93 to 4.33 on
the large chainring. Although there is only one ratio common to both chainrings
(3.25), most riders will use no more than 14 gear combinations. The lowest gear
will be utilized as a rider starts from a stop. As the rider accelerates, he or she will
shift to a higher gear by shifting to a smaller cassette cog. Normally at about the
eighth gear on the small chainring, instead of shifting to the ninth gear, the rider
will shift to the large chainring and then immediately downshift three gears on
the cassette, ending up in fifth gear on the large chainring (effectively going from
ch02_mus80164.qxd 8/27/08 2:49 PM Page 38
a gear ratio of 2.79 to 3.06). In this scenario the rider utilizes the first 8 gears of
the small chainring and the last 6 gears of the large chainring, for an effective
number of 14 gears.
Each function has a specific format or syntax that must be followed and all func-
tions must begin with the “=” sign unless they are embedded within another func-
tion. In general, functions have the following format or syntax:
where FUN_NAME is the name of the function and arg1, arg2, ... are the argu-
ments of the function. A function generally has one or more arguments, but as
seen in the previous tutorial, the function PI() has a blank argument. We
will learn the formatting details of functions as we work through the following
exercises.
XAMPLE 2.1:
EXAMPLE 2.1 Use Excel to calculate y = ex for x = 0, 1, 2, and 3.
■ Solution
Type “x” and “y” into cells A1:B1,
respectively.
Figure 2.37
ch02_mus80164.qxd 8/27/08 2:49 PM Page 39
Note that you can use the slider bar to view all
the functions in this group and, as you place
your cursor over a given function, a window
shows the syntax of the function and describes
what the function does. For more information on
a given function, you can hit the F1 key on your
keyboard and navigate to a detailed description
of a function.
Figure 2.38
In the Function Arguments pop-up box, we can
enter a number or cell reference for the argument Number. In our
case, we would like to use a cell reference. Type in A2 and then
select OK, as shown in Figure 2.38.
Use the fill handle tool to copy the formula down to cell B5. Align
your column headers to the center, align the “x” values in cells
A2:A5 to the center, and place a double underline under the col-
umn headers. Your completed spreadsheet should look similar to
Figure 2.39. Figure 2.39
Use Excel to calculate the sine, cosine, and tangent of angles from 0° to 360° at EXAMPLE 2.2
5° increments.
■ Solution
Type “Angle, degrees” into cell A1.
Next, we will use a slightly different technique from the fill handle to input
the angle from 0° to 360° at 5° increments. This technique is more suitable
for large series.
Type the number “0” into cell A2 and with cell A2 selected, select the
Home tab on the Ribbon, select the Fill tool from the Edit group, and
then select Series, as shown in Figure 2.40.
Figure 2.40
ch02_mus80164.qxd 8/27/08 2:49 PM Page 40
Now we will enter the formula for sine. The syntax for the sine func-
tion is:
SIN(number)
Figure 2.41 where number is the angle in radians. Since our angle is in degrees,
we will convert it to radians within the formula. There are π radians
in 180°.
We do not have to enter functions using the Formulas tab on the Ribbon. For com-
monly used functions it is generally easier to type them into the cell; this is the
technique that we will use in this tutorial.
Type the formula “=SIN(A2*PI()/180)” into cell B2. Close the formula and
then use the fill handle to fill the formula down to the bot-
tom of the table.
Type the formula “=COS(RADIANS(A2))” into cell C2. Close the formula and
Figure 2.43 then use the fill handle to fill the formula down to the bottom of the table.
Next, type the formula “=TAN(RADIANS(A2))” into cell D2. Close the for-
mula and then use the fill handle to fill the formula down to the bottom of the
table.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 41
You should notice that the cells containing the tangents of 90°
and 270° display very large numbers. As you may recall from
trigonometry, the tangent approaches infinity as the angle
Figure 2.44
approaches 90° or 270°. At 90° and 270°, we say that the tan-
gent function is undefined. To correct this, let’s delete the
function at these two locations. Right-click on cell D21 and then select Clear
Contents from the pop-up menu, as shown in Figure 2.44. Repeat this for cell
D57 and then adjust the width of column D.
Next, we will add a title above our table. To insert a new row, select row 1 and
select Insert by right-clicking, as shown in Figure 2.45.
Select cells A1:D1 and then select the Merge & Center tool from the Alignment
group on the Ribbon, as shown in Figure 2.46.
Now type “Trigonometric Functions” into cell A1. Finally, apply a Thick Box
Border around the title, around the column headers, and around
the perimeter of the table. Add some fill color to the column headers. Your com-
pleted spreadsheet should look similar to Figure 2.47.
Figure 2.45
Figure 2.46
Figure 2.47
ch02_mus80164.qxd 8/27/08 2:49 PM Page 42
EXAMPLE 2.3 In the manufacturing of ball bearings, the components are hardened through a
process of heating and then rapid cooling or “quenching” by submersion in an oil
or water bath. The temperature of the ball bearing as a function of time, T(t) may
be estimated by Equation 2.3:
T(t) = (Ti – T∞)e–t/τ + T∞ (2.3)
where t is the time in seconds in the bath; Ti is the initial ball temperature; T∞ is
the oil temperature; and τ is the time constant in seconds and depends upon the
material of the ball, the geometry of the ball, and oil properties. Create a spread-
sheet that utilizes Ti, T∞, and τ as input variables and calculates the ball temper-
ature for times from 0 to 10 seconds. Assume the time constant τ = 40 s.
■ Solution
Type “Ti, degrees C”, “Tinf, degrees C”, and “Tau, seconds” and the values
“600”, “30”, and “40” into cells A1:B3 and properly format, as shown in Fig-
ure 2.48.
Type “time, seconds” and “Temp, degrees C” in cells D1 and E1, respectively.
Then fill down the numbers from 0 to 10 into cells D2:D12. Properly format the
table, as shown in Figure 2.49.
An analysis of the solution shows that the bearing indeed starts out at an initial
temperature of 600°C, as stated in the problem statement. Many engineering
Figure 2.48
problems have initial and final conditions where the answer is already known.
These known conditions are useful in evaluating if our computer solution is cor-
rect. In this problem, we know that the temperature of the ball bearing will
approach the oil temperature after a long period of time. We can quickly check
this final condition by typing a large value of time into cell D12.
Type “300” into cell D12 and determine the bearing temperature after 300 sec-
onds of cooling. Answer: 30.3°C.
Our problem statement asks for the time required for the ball bearing to cool
below 60°C. There are several methods that we could use to determine this time.
In this example, we will hunt for the solution by bracketing the time and zoom-
ing in to a precise time. Better techniques, such as graphical methods, for deter-
mining solutions will be covered in Chapter 5 and specialized tools, such as Goal
Seek, will be covered in Chapter 6.
In this case, we know that the solution resides somewhere between 0 and 300 sec-
onds. To better bracket the time, let’s increment the time by 30 seconds. Type the
values of “0” and “30” into cells D2 and D3 and then fill down to cell D12.
Now we can see that between 90 seconds and 120 seconds the bearing tempera-
ture drops below 60°C. Let’s zoom in on this time period by incrementing time
by 3 seconds. Type the values of “90” and “93” into cells D2 and D3 and then
fill down to cell D12.
We can now see that the bearing temperature drops below 60°C slightly after 117
seconds. If a more precise answer is required, you could again zoom in on the
time period between 117 and 120 seconds and incrementing by 0.3 seconds. The
more precise answer is 117.9 seconds.
<> (not equal to). The argument value_if_true is the value that is returned if the
logical_test is true. The argument value_if_false is the value that is returned if the
logical_test is false. The returned value can be a number, text string, or another
formula.
In this tutorial, we will learn how to apply the IF statement through several
exercises.
EXAMPLE 2.4 Use the IF statement to calculate the absolute value of a number.
■ Solution
The absolute value of a number is defined as follows: If the value of a number
is greater than or equal to zero, then its absolute value equals the number. If
the number’s value is less than zero, then its absolute value equals the number
times –1.
Type “Number” and “Absolute Value” into cells A1 and A2, respectively. Adjust
the column width so the labels fit correctly.
Type “=IF(B1<0, –B1, B1)” into cell B2. Cell B2 should read “5”.
Now test your formula by typing in “–3” into cell B1. Cell B2 should read “3”.
EXAMPLE 2.5 In manufacturing, extremely tight tolerances are required for parts that are to be
mated. It is common to use hardened steel dowel pins to precisely align each half
of a mold used for injection molding, as illustrated in Figure 2.51. Each time a
part is molded, the two halves of the mold must be separated to release the part.
When initially machining the mold, the alignment hole diameter must be very
precise: too small of a diameter and the mold will not easily assemble and disas-
semble, too large of a diameter will result in poor alignment and a bad molded
part. In this exercise, we will use the IF statement to accept or reject measure-
ments of the diameter of the alignment holes.
Figure 2.51
ch02_mus80164.qxd 8/27/08 2:49 PM Page 45
■ Solution
We want to make the spreadsheet as generic as possible, such that if we decide to
change the target diameter of the hole, or the tolerance, then we do not have to
rewrite all the formulas. We will start by assigning each of these as a variable.
Type “Target Diameter (in)”, “Plus Tolerance (in)”, and “Minus Tolerance
(in)” into cells A1:A3, respectively, and then type “0.25”, “0.0010”, and
“–0.0005” into cells B1:B3, respectively.
Type “Measured Diameter (in)” and “Tolerance Check” into cells A5 and B5,
respectively.
There are several methods of applying the IF statement to solve this problem. We
will use the following approach. First, we will compare the measured diameter to
the target diameter by taking the difference and then checking to see if the dif-
ference is greater than the high tolerance. If this first condition is satisfied, we
will return a text string of “REJECT HIGH”. If the first condition is not satisfied,
we will use a second IF statement embedded inside the first IF statement to see
if the difference in measured diameter and target diameter is less than the low tol-
erance, and if this condition is satisfied we will return a text string of “REJECT
LOW”. Finally, if neither of the first two conditions is satisfied, the diameter must
be inside the tolerances and we will return “ACCEPT.”
Adjust the number format to display four decimal places on all numbers and
adjust the column widths to properly display the text and align the data to the
center of the columns. Your spreadsheet should look similar to Figure 2.52.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 46
Adjust the column widths and align the data to the center
of the cells so that this table is similar in appearance to
Figure 2.54.
Next, type “Accept” into the Format cells that contain the
text dialog box and then select “Green Fill with Dark Green
Text” for the cell format, as shown in Figure 2.56. Select OK
to close the dialog box. Figure 2.55
To finish your spreadsheet, add some borders around each of the tables, high-
light the table headers, and align the data so that your spreadsheet looks good.
Your completed spreadsheet should look similar to Figure 2.59.
Figure 2.59
Now let’s look at a short example that illustrates the power of assigning variables.
Assume that you have a large inventory of parts with the previous measurements
and a customer places a special order for parts with a tolerance of +0.0010,
–0.0000. What percent of your inventory can you immediately ship to satisfy this
customer? To answer this question, type in “0.0000” into cell B3. Answer: 40%.
EXAMPLE 2.6 An inspection process tests parts three consecutive times. Each part is assigned a
sequential part number and either a “Pass” or “Fail” for each of the tests. Let’s
assume two acceptance criteria: 1) the part is acceptable only if the part passes
all three tests, and 2) the part is acceptable if the part passes at least one of the
tests. Use Excel to determine if the parts shown in Table 2.2 are accepted or
rejected per each acceptance criterion.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 49
■ Solution
In this problem we could use embedded IF statements to determine the solution.
However, a simpler approach exists using the logical AND and OR functions.
The AND function has the following syntax:
AND(logical test1, logical test2,...)
where logical test1 and logical test2 are logical tests. The AND function returns
a value of TRUE if all of the logical tests are true and a value of FALSE if any of
the logical tests are false.
Now let’s enter the logical test for criterion 1. We Figure 2.60
can embed the AND function into the IF statement.
Next, we will enter the logical test for criterion 2. Since only one passing test is
required for accepting the part, we will use the OR function.
Figure 2.61
The VLOOKUP function looks up values from tables where the data is tabulated
in vertical (hence the V) columns, whereas the HLOOKUP function looks up data
tabulated in horizontal (hence the H) rows. The syntax of the VLOOKUP func-
tion is:
VLOOKUP(lookup_value, table_array, col_index_num, range_lookup)
where the arguments of the function are as described as follows:
■ lookup_value is the value to search for in the first column of the table. This
can be thought of as the independent variable of the tabulated data.
■ table_array consists of two or more columns of data in the form of the
range of cells that make up the table.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 51
■ col_index _num is the column number (2, 3, 4, etc.) in the table in which
the value that you are looking for can be found. The independent variable,
which will be matched against the lookup_value, is in column 1.
■ range_lookup is a logical value that is set to specify whether you want an
exact match or an approximate match to lookup_value.
■ If set to TRUE or omitted, either an exact match to lookup_value is
found and the corresponding value located in col_index_num is
returned or an approximate match is determined. The approximate
match uses the next lowest value from lookup_value in the table and
returns the corresponding value located in col_index_num. To use the
approximate match, the values in the first column of the table must be
in ascending order.
■ If set to FALSE, Excel only applies the exact match case described
previously. In the event there is not an exact match, an error value of
#NA is returned.
The syntax for HLOOKUP is similar, except that the references are relative to
rows instead of columns.
The boiling temperature of water depends upon the pressure of the water. Higher EXAMPLE 2.7
pressure forces the liquid water molecules closer together, thus requiring more
kinetic energy to break the bonds and transition into a vapor. A measure of a mol-
ecule’s kinetic energy is temperature and the higher the temperature, the greater
the kinetic energy. Therefore as we raise the pressure of the water, the boiling
temperature also increases. For example, we all know that the boiling tempera-
ture of water at standard atmospheric pressure is 212°F. At 2 atm, the boiling
temperature increases to 248.8°F. Thus, we can say that for a given pressure there
is a unique vaporization temperature, and for a given temperature, there is a
unique vaporization pressure.
Given the temperature and mass as input variables, construct a spreadsheet that
uses a lookup table to determine hv and the pressure and then calculate the
required amount of heat to completely vaporize the water.
■ Solution
Input the data shown in Table 2.3 into Excel, starting with the column header
titles in cells A1:C1.
Type in “150” and “5” for the temperature and mass, respectively. Your cal-
culations should look similar to Figure 2.67. Now change the temperature to
“170”. Notice that the results of the calculations do not change. This is because
there is no 170°C data listed in our table, so Excel returns an approximation
using the values for the next lowest temperature, 150°C. If we needed more
resolution we could add more data to our table. Figure 2.67
ch02_mus80164.qxd 8/27/08 2:49 PM Page 54
EXAMPLE 2.8 A town has a population census every 10 years. The results of the census are
shown in Figure 2.70. Create a spreadsheet that uses linear interpolation to return
the estimation of the value of the population of the town for any year between
1900 and 2000.
■ Solution
Create a spreadsheet similar to Figure 2.70.
Equation 2.5 expresses the relationship between the dependent variable and the
independent variable and tabulated values:
( y2 − y1 ) x − x
y = y1 + ( 1)
( x2 − x1 ) (2.5)
So, for example, we could estimate the population of the year 1956:
Enter the formula, shown in Figure 2.72, into cell C7 and then fill down the
formula to cell C16.
Figure 2.72
ch02_mus80164.qxd 8/27/08 2:49 PM Page 56
Note that we inserted a space in the cells for which the interpolation
formula will not apply for the input value. We could have inserted
a value of zero instead, and our solution would be the same. How-
ever, insertion of the space has two advantages. Only the solution
value is shown in column C, resulting in a less cluttered appearance.
Also, in general, a table may have both positive and negative val-
ues. By inserting spaces in the non-applicable cells, the MAX for-
mula will find the correct answer, regardless of whether the value is
positive or negative.
The estimated value of the population for the year 1956 is now dis-
played in cell C12. We would like to scan down column C and
extract the value of the population and display the value in cell B2.
We can use the MAX(range) function to return the maximum value
of a range of cells.
Problems
2.1 Use Excel to create a weekly calendar (5 days or 7 days) of your classes and
activities. Color-code each class and activity, similar to the spreadsheet
shown in Figure P2.1.
Figure P2.1
ch02_mus80164.qxd 8/27/08 2:49 PM Page 57
2.2 Table P2.2a shows some basic activities, durations, and the dependence of
activities required to build a house.
Excel is a good tool to visually display these activities and their relation-
ships in what is known as a Gantt chart, or timeline. Figure P2.2 shows a
Gantt chart for the activities of building a house. This timeline is made by
shading the appropriate cells to indicate the duration of the activities.
Some activities, such as D and F, are completed prior to a subsequent
activity starting. This is free or slack time in the schedule and is indicated
as such. Activities with slack time can slip without impacting the overall
schedule. The activities that cannot slip without adversely impacting the
overall schedule are called critical path activities. The critical path activi-
ties in this project are A, B, C, E, G, and H.
Figure P2.2
ch02_mus80164.qxd 8/27/08 2:49 PM Page 58
2.3 Lightbulbs are rated by their power consumption in watts (W). Electricity
is sold in units of energy, which is power multiplied by time. Electricity
costs vary widely across the United States and are on the order of
0.06–0.23 $/kW-hr for residential customers. Create a spreadsheet that
utilizes electricity costs and the number of hours per day that a lightbulb
is on as input variables. Then calculate the annual cost to operate a 60-W,
75-W, and 100-W incandescent bulb and a 15-W compact fluorescent
bulb. Assuming the average household operates six 60-W, four 75-W, and
two 100-W incandescent bulbs for 6 hours a day, how much money can
they save in a year by changing all the bulbs to compact fluorescent?
2.4 Create a spreadsheet that calculates the log10 and loge (natural log) of
integers from 1 to 100.
2.5 Create a spreadsheet that calculates the square root and cube root of inte-
gers from 1 to 100.
2.6 Create a spreadsheet that calculates the circumference and area of circles
with diameters ranging from 1 cm to 100 cm in 1-cm increments.
2.7 Create a spreadsheet that calculates the perimeter and area of squares with
side lengths ranging from 1 cm to 100 cm in 1-cm increments.
2.8 Create a spreadsheet that calculates the surface area and volume of cubes
with side lengths ranging from 1 inch to 100 inches using 1-inch incre-
ments.
2.9 Create a spreadsheet that calculates the surface area and volume of
spheres with diameters ranging from 1 inch to 100 inches using 1-inch
increments.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 59
Figure P2.17
2.18 Solve the boiling temperature problem from Example 2.7 in the chapter
using linear interpolation in place of the lookup table.
2.19 At sea level, average atmospheric pressure is about 14.7 pounds per
square inch (psi). At altitude, pressure decreases. As the pressure
decreases, there are fewer air molecules in a given volume. Therefore,
baseballs fly farther at Coors Field in Denver (elevation = 5280 feet) than
at sea level, and it is very difficult to breathe on Mt. Everest (elevation =
29,035 feet). Create a spreadsheet that allows a user to input an elevation
between
0 and 50,000 feet and estimates the atmospheric pressure based on
Table P2.19. Use linear interpolation to estimate values between the
data points shown in the table. If a value of less than 0 or greater than
50,000 feet is entered, then “Out of Range” should be displayed in the
spreadsheet.
C H A P T E R 3
MATLAB
Fundamentals
Introduction
The MATLAB computing environment is a powerful and widely used technical
computing tool. It is employed in numerous industrial and academic environ-
ments. MATLAB can be used as a very sophisticated calculation tool, as a lower-
level engineering programming language, or as a high-level graphical
programming language (through its SIMULINK interface). It has numerous
built-in functions for mathematical, graphical, and engineering applications, and
has a variety of specialized “toolboxes” for targeted applications (control sys-
tems, signal processing, optimization, fuzzy logic, etc.).
63
ch03_mus80164.qxd 8/27/08 2:49 PM Page 64
The MATLAB interface, shown in Figure 3.2, will appear. In addition to the stan-
dard “Windows” toolbar, there are four default windows that appear:
■ The Command Window: This is where we will type the computational com-
mands to be executed.
■ The Current Directory Window: This shows the list of files that exist in the
directory set as the current working directory in MATLAB.
■ The Workspace Window: This will show a list of all of the variables that we
have defined during our session.
■ The Command History Window: This will show a running log of the com-
putational commands we have executed during our session.
By default, the Command Window, Current Directory Window, and Command
History Window are visible; you can toggle between the display of the Current
Directory Window and the Workspace Window by clicking on the labeled tabs.
Figure 3.2
The default display is easily customizable; by selecting “Desktop” from the Win-
dows Toolbar, the various MATLAB windows can be closed, minimized, or
opened to customize the display, as shown in Figure 3.3.
In this chapter, we will primarily use the Command and Workspace Windows.
Figure 3.3
A rectangle has a base of 7.500 inches and a height of 3.300 inches. We will use EXAMPLE 3.1
MATLAB to find the area of this rectangle.
■ Solution
From geometry, we remember that the area, a, of a rectangle is the product of the
base b, and the height, h:
a = bh (3.1)
Click inside the Command Window. The “>>” symbol is the command prompt,
and is the location at which we enter our commands. Type the following com-
mand at the prompt in the Command Window, as shown in Figure 3.4.
Figure 3.4
The asterisk symbol (Shift-8) is the multiplication operator; when we hit the
Enter key, the numbers on either side of this symbol will be multiplied together:
>> 7.5*3.3
ans =
24.75
ch03_mus80164.qxd 8/27/08 2:49 PM Page 66
■ Alternative Solution
In our solution to the area computation problem, we simply typed the numeric
expression we wanted to evaluate directly into the Command Window. The result
was stored into a variable named ans, which is the “default” variable name used
when MATLAB performs a numerical computation. In order to move to more
complicated computations, and to exploit the power of MATLAB as a program-
ming language, we will need to employ more sophisticated use of variables. In
this alternative solution, we will further explore the creation of variables in a
computational environment.
We will begin by creating a variable named b1, and assigning it the value asso-
ciated with the base dimension of the rectangle. We will do this in the Command
Window as follows:
>> b1=7.5
ch03_mus80164.qxd 8/27/08 2:49 PM Page 67
Hitting the Enter key will execute the command, create a variable called b1,
and assign the number 7.5 to the name. The result is echoed to the screen:
>> b1=7.5
b1 =
7.5000
Note that the variable b1 has been added to the Workspace Window, as shown in
Figure 3.6.
Figure 3.6
What we have done is known as an assignment operation. The “=” symbol is the
assignment operator; while it resembles the “equal sign,” it is used in a very dif-
ferent way. When the assignment operator is encountered by MATLAB, it is
interpreted as: “Take the number located on the right-hand side of the operator,
and assign it to the variable name located on the left-hand side of the operator.”
Proper interpretation and use of the assignment operator is critical in MATLAB
programming; many students new to programming struggle with the difference
between the assignment operator and the mathematical equal sign. Keep in mind
that while “b1=7.5” and “7.5=b1” might be equivalent mathematically, they are
different when used in MATLAB programming; only the first expression can
actually be interpreted using the assignment operator.
We will now define a second variable for the rectangle height. Using the assign-
ment operator, we will also define a variable h1 and assign the value of the rec-
tangle height to it:
>> h1=3.3
Again, hitting the Enter key will complete this operation; the result will be
echoed to the screen, and the Workspace Window will be updated to include this
new variable.
We will now set up an equation to compute the area of the rectangle. We will use
our defined variables, the multiplication operator, and the assignment operator to
ch03_mus80164.qxd 8/27/08 2:49 PM Page 68
store the result in an appropriate variable. In the Command Window, type the
command:
>> a=b1*h1
Hitting the Enter key will perform the multiplication operation (substituting
the current values of the variables into the equation), and assign the result to
variable a.
>> a=b1*h1
a =
24.7500
EXAMPLE 3.2 Use MATLAB to find the perimeter of the rectangle described in Example 3.1
(base of 7.500 inches and height of 3.300 inches).
■ Solution
We remember from geometry that the perimeter p of a rectangle is given as fol-
lows:
p = 2b + 2h (3.2)
Recall that the base and height dimensions are identical to those used in Exam-
ple 3.1. Since we have not closed MATLAB or cleared out our variables, the base
and height are already defined in our Workspace, and we can easily reuse these
ch03_mus80164.qxd 8/27/08 2:49 PM Page 69
>> p=(2*b1)+(2*h1)
The perimeter is computed as 21.60 inches, and is assigned to the variable p. Note
that parentheses were used to explicitly describe the order of operations to be per-
formed; in this example, we wanted the multiplication operations to be performed
before the addition operation. Recall from Chapter 2 that most computing soft-
ware, including MATLAB, uses a standard hierarchy for interpreting the order in
which mathematical operations are performed. As with Excel, the general rule in
which mathematical operations are performed using MATLAB is as follows:
■ Equations are interpreted from left to right.
■ All exponentiations are given highest priority.
■ Multiplications and divisions are given secondary priority.
■ Additions and subtractions are given tertiary priority.
This standard order of operations can be overridden by the use of parentheses;
when parentheses are added to an expression, operations are performed starting
with the innermost set of parenthesis and moving outward. A good rule of thumb
is to use parentheses liberally, to be sure that your expression is evaluated as
desired. When results of calculations using a computational tool do not seem to
agree with known results (from hand calculations or other sources), the erroneous
results can often be traced to order of operations problems.
Note that in our example, the parentheses are not truly necessary; the standard
order of operations would have given the multiplication operations priority over
the addition operation, and the expression would have been evaluated properly
without the parentheses. Many engineers would choose to use the parentheses
anyway, since they do help to visually “organize” the equation and make the pro-
grammer’s intent clear.
A right triangle is shown in Figure 3.7. We will use MATLAB to find the values EXAMPLE 3.3
of x and y.
■ Solution
In Examples 3.1 and 3.2, we only needed to use the basic mathe-
matical operators to solve the problems at hand. This example
requires the use of trigonometric functions, since we recall from
trigonometry that:
x = h sinθ (3.3) Figure 3.7
ch03_mus80164.qxd 8/27/08 2:49 PM Page 70
y = h cosθ (3.4)
Since we are done with our rectangle example, we can reset the Workspace
(clearing out all of our defined variables) by typing the following at the prompt:
>> clear
Note that the Workspace is now empty. We can also reset the Command Window
as follows:
>> clc
We will create a variable containing the hypotenuse value by typing the follow-
ing and hitting the Enter key:
>> hyp=6;
Note the presence of the semicolon following the expression. The purpose of the
semicolon is to suppress the “echo” to the screen when the command is executed.
Note that the variable hyp was created in the Workspace, but the value was not
output in the Command Window. Generally, when we are defining variables,
there is no need to display the results in the Command Window, so the semicolon
can be used. We will continue to omit the semicolon at the end of our computed
expressions, since we will need to see the results of these operations.
> x=hyp*sin(30*pi/180)
When we omitted the semicolon and hit Enter, the result was output to the Com-
mand Window:
>> x=hyp*sin(30*pi/180)
x =
3.0000
ch03_mus80164.qxd 8/27/08 2:49 PM Page 71
or x = 3.0 in.
There are a number of things to note in this expression. First, note the use of the
sine function, sin. This is one of many prewritten functions that are available in
the MATLAB environment to perform complex computations. In general, a func-
tion is a MATLAB program that takes a number (or numbers) provided inside of
parentheses (called the “argument” of the function) and returns a computational
result. This general syntax of using a function with a parenthetical argument will
be used over and over again in the MATLAB environment. To see a list of the ele-
mentary mathematical functions available in MATLAB, including trigonometric,
exponential, and complex math functions, you can use the online help files. You
can access the online help files at any time by typing:
>> help
A list of the available help topics will be listed. To see the list of elementary func-
tions, either select the hyperlink matlab\elfun from the list of help topics, or
type the following at the command prompt:
The list of functions will be displayed in the Command Window. You may need
to use the scroll bar to see the complete list.
As we examine our use of the sin function, the other important thing to note is
that the “argument” of the sine function was provided in units of radians rather
than in units of degrees. In our expression, we embedded this unit conversion
directly into the parenthetical argument. In general, most programming lan-
guages and computational tools used by engineers use radians as the basic unit
for trigonometric calculations. We can verify this in MATLAB by consulting the
online help file for the sin function by either selecting the appropriate hyper-
link from the elfun list, or by typing the following at the command prompt:
Indeed, the documentation in the help file indicates that the sin function requires
an argument in units of radians. The use of radians rather than degrees in engi-
neering computation packages is a common source of computing errors for
ch03_mus80164.qxd 8/27/08 2:49 PM Page 72
beginning programmers and engineering students. Note that MATLAB does pro-
vide an alternate set of trigonometric functions that use units of degrees; for
example, the sind function is an alternative to the sin function that allows the user
to work in units of degrees. You can consult the online help file to verify this:
You should also note that in our unit conversion in the argument of the sin func-
tion, we made use of the variable pi. Since it is used so often in engineering com-
putations, MATLAB has predefined this variable for your use. While it does not
show up in the Workspace, it is a variable that is always available for your use.
Be careful not to redefine this variable in your programs! MATLAB will let you
overwrite the default value of this variable, so avoid using the variable name pi
on the left-hand side of the assignment operator.
To finish this example, we can find the value of y. We can do this by using
either:
>> y=hyp*cos(30*pi/180)
or:
>> y=hyp*cosd(30)
y =
5.1962
Note that while MATLAB carries more decimal places in the calculation than it
displays; by default, MATLAB uses the short format, displaying four decimal
places. We can expand the number of decimal places displayed by issuing the
following command:
>> y=hyp*cosd(30)
y =
5.196152422706632
Issuing the format short command will return the default format:
Regardless of the number of decimal places displayed, the precision of our cal-
culation is set by the precision of the input data; we will interpret the result as
y = 5.2 in.
Before we proceed, we will check our work in a couple of ways. First, let’s check
and be sure that the x and y values we computed yield the input value of 30° by
typing:
> theta=atand(x/y)
which will compute the arctangent, in degrees, of the argument. The result does
indeed yield the input value of 30°.
We can also check the hypotenuse value, using the Pythagorean theorem and
the square root function sqrt() available in MATLAB:
>> h=sqrt(x^2+y^2)
Note that this expression computes the sum of the squares of the “legs” of the tri-
angle and uses this value as the “argument” of the square root function. The
result, 6.0 inches, corresponds with the input value.
This square root function is another of the elementary functions available; a sub-
set of commonly used functions from the matlab\elfun directory is shown in
Table 3.2.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 74
We will develop an automated script to perform the area and perimeter computa-
tions we performed manually in Examples 3.1 and 3.2. Before we begin, we must
set up a directory in which to store our MATLAB script files. On the Windows
Toolbar, the “Current Directory” is displayed. Select the “...” icon to open the
Browse For Folder dialog box, as shown in Figure 3.8.
Figure 3.8
ch03_mus80164.qxd 8/27/08 2:49 PM Page 75
Figure 3.12
ch03_mus80164.qxd 8/27/08 2:49 PM Page 76
EXAMPLE 3.4 We want to find the area and perimeter of the three rectangles described in
Table 3.3:
■ Solution
We could use the approach taken in Example 3.1 to solve this problem. However,
the repetitive nature of the calculation would make an automated approach more
effective. We will use a script, or m-file, to automate the process.
Click the New M-File icon on the toolbar, as shown in Figure 3.13.
Figure 3.16
ch03_mus80164.qxd 8/27/08 2:49 PM Page 77
Close the Editor Window and return to the Command Window. Clear the Work-
space and the Command Window by typing the clear and the clc commands at
the prompt.
Before we execute our script, we must define our variables base and height. We
will do this for Rectangle 1 in the Command Window by typing:
>> base=6.5;
and:
>> height=2.1;
Recall that the semicolon at the end of these commands suppresses the “echo” of
the command to the screen. Note that the variables base and height have been
added to the Workspace.
With these variables defined, we will execute our script for computing area and
perimeter. We execute the script by typing its name in the Command Window:
>> rect
Hitting the Enter key will execute the script. MATLAB will interpret your script
just as if you had typed the formulas in the Command Window and (since no
semicolons were added to the commands in the script file) the results are echoed
to the screen:
>> rect
rect_area =
13.6500
rect_perim =
17.2000
ch03_mus80164.qxd 8/27/08 2:49 PM Page 78
For the subsequent rectangles, the variables can simply be set to their new val-
ues in the Command Window and the rect script can be executed again:
>> base=7.2;
>> height=3.0;
>> rect
rect_area =
21.6000
rect_perim =
20.4000
■ Alternative Solution
We, alternatively, could have written a script that would automate the perfor-
mance of all three computations. Using “File: Open” from the Windows Tool-
bar, reopen your rect script. Modify it as follows (you may use traditional
Windows copy/paste functions to minimize your typing; note that the line num-
bers are added automatically in the Editor Window and do not need to be
typed):
Note that lines 1, 4, 7, 10, 13, and 16 begin with the percent sign (“%”); these
script lines are called comments. They are not interpreted at all by MATLAB;
they simply serve as written reminders of what the various sections of the script
do. While the comments do not affect how the program runs, they are useful for
explaining your script to others (or for reminding yourself what the script does,
when returning to your work at a future date). You should get in the habit of using
comments liberally in your programs.
This shortcut will save our changes to the script file and execute the script in the
Command Window. The output from the script in the Command Window is as
follows:
rect_area1 =
13.6500
rect_perimeter1 =
17.2000
rect_area2 =
21.6000
rect_perimeter2 =
20.4000
rect_area3 =
24.7500
rect_perimeter3 =
21.6000
Careful examination of the output will show the effect of the semicolon at the end
of the command lines. The base/height definitions, where semicolons were used,
do not echo to the screen. The results of the area/perimeter computations, where
semicolons were omitted, show up in the Command Window. This is a simple
way of outputting desired results to the user.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 80
EXAMPLE 3.5 A user wants to be able to calculate the area and perimeter of any rectangle. We
will develop a script that will allow this.
■ Solution
We will develop an interactive script that prompts the user to enter base and
height dimensions, and outputs the area and perimeter. To do this, we need to use
a MATLAB function called input(). The function displays a message to the
screen, waits for the user to type a response, and (upon the user pressing the Enter
key) assigns the response to a desired variable name. For example, the command:
y = input(‘Enter a number between 1 and 10’);
would display the message contained in single quotes, and assign the inputted
value to the variable y. The variable y could then be used in subsequent calcula-
tions and would take the value input by the user (for more information, you may
consult the online help by typing “help input” in the Command Window).
Save this file with the name “rect2”. Note the following in the script:
■ Lines 2 and 3 make use of the input() function to allow the user to type in
base and height dimensions and assign those values to variables b1 and h1.
■ Lines 5 and 8 are essentially “dummy” inputs; they simply delay execution
of subsequent lines until the user presses the Enter key. Note that the input
is not assigned to any variable, since the results are not needed or used.
This type of “dummy” input is merely for the convenience of the user, and
is not necessarily required.
Run the script by typing the script name into the Command Window or by using
the Editor shortcut. In the Command Window, the script will display the first
input message and will pause:
Type in the value “6.5”, and hit the Enter key. The program will display the next
input message and pause again:
Type in the value “2.1”, and hit the Enter key. By hitting the Enter key in
response to the next two prompts, the area and perimeter will be calculated and
displayed:
Note that each and every variable that we have defined since clearing the Work-
space is now shown in the Workspace Window. These variables are all available
for use in additional computations and scripts. Such variables are called global
variables; until we clear them out with the clear command or close the MATLAB
environment, these variables will exist with their values as defined.
In this section, we will create a number of script files; each script file we create
will need a unique name so it can be accessed from the Command Window. Good
programming conventions dictate that our script names should be descriptive; for
example, our “rectangle area” script is called rect. Following this convention will
allow you to better organize your work. In addition, the MATLAB environment
has some strict rules that must be followed when creating your own script names:
■ Filenames must be all one word, with no spaces allowed. If you would like
to use spaces in your file name to make it more descriptive, you could use
the “underscore” character (Shift with the “-” sign) instead of a space. For
example, rectangle area would not be an acceptable filename, since it has a
space in it; however, rectangle_area would be acceptable.
■ Characters with special meaning in MATLAB are not allowed in
filenames. Characters like “+”, “-”, “/”, “*”, “.”, and others cannot appear
in filenames; MATLAB will attempt to interpret them as mathematical
ch03_mus80164.qxd 8/27/08 2:49 PM Page 82
A user wants to be able to calculate the area of any rectangle. We will develop a EXAMPLE 3.6
function that will allow this.
■ Solution
In order to compute area, the function will require two input arguments: the base
of the rectangle and the height of the rectangle. Our function will take the form:
area_rect(base,height)
To create a function, we use the same Editor that was used for script files. From
the MATLAB environment, start a new m-file. In the Editor, type in the fol-
lowing function:
1 function A=area_rect(base,height)
2 % This function takes the user-defined base
3 % and height of a rectangle, and computes area
4 A=base*height;
This is not a script file; it is a function. Therefore, it cannot be executed using the
“Save and run” shortcut from the Editor. It must be saved, using either “File:
Save” from the menu or the “Save” button from the toolbar. It is also critical that
the function file be saved with a filename that is the same as the function name;
if the filename and the function name are not identical, the function will not
work! Save this function with the filename area_rect; the Editor will default to
this name when the save operation is begun.
While this is a short and very simple function, it contains many important ele-
ments that are important to note. Look closely at the first line of the function:
■ The first line of the function starts with the word function. All functions
must start with this word. When MATLAB interprets programs, the word
function at the start of the program is what differentiates a script and a
function.
■ The variable to the right of the word function and to the left of the assign-
ment operator is the output variable. After the function is executed, the
only value that is “passed back” to the Workspace is the value assigned to
the output variable when the function finishes.
■ The word to the right of the assignment operator is the function name. This
is also the name of the file in which the function is stored. When we exe-
cute the function, we will do so by referring to this name.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 84
■ The variable or variables inside the parentheses which follow the function
name are the input variables; these will contain the numerical values that
are “passed” into the function, and are the only numerical values defined
external to the function that are available to the function.
Summarizing, the first line of every function we develop in MATLAB will take
the generic form:
function output_variable = function_name(input_variable_1, input_variable_2, ...)
Beyond this first line, a function will look exactly like a script file. Our function
in this example contains two comment lines and only one computational state-
ment (line 4), but it could contain a much longer program if needed. All mathe-
matical operations and functions available in the Command Window and in
scripts are available in functions as well.
To use the function, return to the Command Window. In order to clearly demon-
strate the differences between scripts and functions, we will start with a clean
workspace. Enter the clear command at the prompt to empty the workspace.
To use our function in its simplest form, enter the following command at the
prompt:
>> area_rect(6.5,2.1)
The command will initiate our area_rect function, assigning the value 6.5 to the
input variable base and 2.1 to the input variable height. When the Enter key is
pressed, the function will execute and (since the semicolon was omitted from
the statement) the value of the output variable will be output to the Command
Window:
>> area_rect(6.5,2.1)
ans =
13.6500
Figure 3.18
Note that while the variables base, height, and A were all defined and used inside
our function, these variables do not exist in the Workspace. This highlights the
definition of a local variable; the variables were used locally within the function,
but disappear after the function executes. Since the variables defined inside a
function are only used locally, we do not need to worry about duplication or reuse
of variable names in functions.
In this execution of the function, we did not assign the output of the function to
any specific variable; it was therefore assigned to the default “temporary” vari-
able ans. If we wanted to store the result in a variable name of our choice, we
could do so with the following command:
>> Area=area_rect(6.5,2.1);
When we execute this command, the output of our function will be assigned to
the global variable Area, which is available in the Workspace.
>> B=6.5;
>> H=2.1;
Call the function with these variables as the input with the following command:
>> Area1=area_rect(B,H)
With the semicolon omitted, the result is echoed to the screen and the Workspace
is updated with the new global variable.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 86
Of course, since any command entered in the Command Window can also be
automated in a script, we can also call our new function from within a script file.
To demonstrate this, open a new m-file and enter the script as shown:
1 rb=6.5;
2 rh=2.1;
3 ra=area_rect(rb,rh)
Use the “Save and run” shortcut to execute the script (saving with a filename
of your choice), and note the output in the Command Window and Workspace.
Another interesting feature of the functions created is that they also are available
as part of the MATLAB online help menu. To demonstrate, type the following
help command at the command prompt:
When the Enter key is pressed, the comment lines that immediately follow the
first “function” line are displayed as the “help file” for the function:
By taking advantage of this, we can offer ourselves (or others) reminders of what
our function does and how we use it.
Begin this tutorial with a clean Workspace by issuing the clear command. We
will now define a one-dimensional array that contains a list of numbers. To do
this, type the following expression at the command line:
ch03_mus80164.qxd 8/27/08 2:49 PM Page 87
When we hit the Enter key, the result of this assignment is echoed to the screen:
Note that a list of three numbers has been assigned to variable a. This is con-
firmed by checking the Workspace Window.
Again, when we hit the Enter key, the result is echoed to the screen:
b =
0.7000
–3.0000
0
Note the difference between a and b. The list assigned to variable a is known as
a row array; it contains a list of numbers in a horizontal row. The elements in the
array may be separated by either a space (as in our example) or by commas. The
list assigned to variable b is known as a column array; it contains a list of num-
bers in a vertical column. Note that in the definition of a column array, a semi-
colon is used to separate row entries.
When we deal with these arrays, we need to carefully consider how we assign and
use the numbers in these lists, as described in Chapter 1. When addressing vari-
able a, we are referring to the whole list of numbers; however, we will often wish
to address or operate on a single value from the list. In these cases, we will
address a certain cell in the list index (or element number), where the first
number in the list is said to occupy cell number 1.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 88
For example, suppose we wish to double all of the values currently stored in
array a.
>> a=2*a
In words, this command states: “Take all of the values associated with variable a,
multiply each by 2, and assign them to the variable a.” The list of numbers will
be doubled and the new values will be “overwritten.” This command highlights
the difference between the assignment operator (=) and the “equal sign” used in
algebra; while the expression “a = 2a” in algebra seems contradictory (unless a
happens to be zero), the expression “a = 2*a” is a valid assignment operation in
programming regardless of the current value of a.
>> a=2*a
a =
2.0000 6.0000 12.4000
Now let’s assume that we would like to restore only the second value in the list
(6.000) to its previous value (3.000). Issue the following command:
>> a(2)=.5*a(2)
In words, what this command states is: “Take the second value from array a, mul-
tiply it by 0.5, and assign the result to the second value in array a.” The number
2 in parentheses in variable a(2) indicates that we are operating on the number
assigned to the second “slot” in the list of numbers assigned to variable a.
>> a(2)=.5*a(2)
a =
2.0000 3.0000 12.4000
ch03_mus80164.qxd 8/27/08 2:49 PM Page 89
Before we proceed, think carefully about what the number in parentheses fol-
lowing variable a means. It is a specific reference to a very particular element
from the list of numbers associated with a. As of now, these elements are as fol-
lows:
This is how we specify specific elements from the list. Note that as of now, there
is no element a(4), a(5), etc. Also note that since the parenthetical number is a
reference to a specifically numbered position in the list, such references as a(–1),
a(0), a(1.34), etc. are simply incorrect; the first element in the list will always be
referenced as number 1, the second as number 2, and so on.
>> a(4)=2*b(1)
In words, this states: “Take the first number in the list associated with b, double
it, and assign it to the fourth value in array a.” Hit the Enter key, and note the
result:
>> a(4)=2*b(1)
a =
2.0000 3.0000 12.4000 1.4000
A new element, the fourth in the list, has been added to list a. Our variable is as
follows:
>> b(7)=3
ch03_mus80164.qxd 8/27/08 2:49 PM Page 90
>> b(7)=3
b =
0.7000
–3.0000
0
0
0
0
3.0000
Note that the value 3.0000 is appended to list b as the seventh value. However,
since no value has been defined for elements 4, 5, and 6, MATLAB has assigned
zero values by default.
We will now address some of the common errors made when learning to use
arrays in computations. Type in the following command:
>> b(5)=2*a(0)
In words, this command states: “Take the value assigned element number zero in
array a, double it, and assign it to the fifth value in array b.” Hit the Enter key
and note the message that results:
>> b(5)=2*a(0)
??? Subscript indices must either be real positive
integers or logicals.
This is an error message that indicates the operation could not be performed. As
indicated by the message, the number in parentheses following the variable a
must be a positive integer, since it represents the position in the list of numbers.
Since there is no “zero” position, this command is meaningless.
Now, type in the following command and hit the Enter key.
>> a(1)=3*b(10)
ch03_mus80164.qxd 8/27/08 2:49 PM Page 91
In words, this command states: “Take the tenth value from the list of numbers
stored in b, multiply it by three, and assign the value to the first slot in array a.”
Note that, again, an error results:
>> a(1)=3*b(10)
??? Index exceeds matrix dimensions.
This error resulted because we attempted to read the tenth element from array b;
however, array b only contains seven elements. We have attempted to reference
a variable that does not exist.
The errors demonstrated in this section are common errors encountered when
dealing with arrays in MATLAB. As your programs get more complex, learning
to understand and interpret these error messages will lead you to discover errors
in your programming logic.
While all of these array examples have been performed at the command prompt,
we can use array variables in scripts and functions as well. We will demonstrate
the use of an array variable in the following example.
A user wants to be able to calculate the area and perimeter of any rectangle. We EXAMPLE 3.7
will develop a function that will allow this.
■ Solution
To add the perimeter calculation, we will create a function similar to our Exam-
ple 3.6 solution. However, in this case, our output variable will be an array that
contains area in the first “slot” and perimeter in the second “slot.”
1 function AP=area_perim(base,height)
2 % This function computes area and perimeter
3 % for a rectangle defined by base and height.
4 % The output variable takes the form:
5 % [area, perimeter]
6
7 %Compute area
8 AP(1)=base*height;
9 %Compute perimeter
10 AP(2)=(2*base)+(2*height);
ch03_mus80164.qxd 8/27/08 2:49 PM Page 92
Save the function (remembering to give the file the name “area_perim”). Return
to the Command Window to use the function. Type the following command:
>> area_perim(6.5,2.1)
Hit the Enter key. Note that a variable containing two numbers is returned; as our
function defines it, the first number in the list is the area and the second number
is the perimeter:
>> area_perim(6.5,2.1)
ans =
13.6500 17.2000
Note that we could also use an array for the input argument. Open your
area_perim function and modify it as shown:
1 function AP=area_perim(Dimensions)
2 % This function computes area and perimeter
3 % for a rectangle defined by base and height.
4 % The output variable takes the form:
5 % [area, perimeter]
6
7 %Compute area
8 AP(1)=Dimensions(1)*Dimensions(2);
9 %Compute perimeter
10 AP(2)=(2*Dimensions(1))+(2*Dimensions(2));
Save the modified function. Note that in this function, the input argument has
been redefined as an array as well, where the first element in the array is the base
and the second element is the height. We can execute the function by first defin-
ing an input variable that contains both the base and the height by entering the
following command:
We can then execute the function with dims as the input argument. For demon-
stration, we will also assign the output of the function to a variable this time:
>> a_and_p=area_perim(dims)
>> a_and_p=area_perim(dims)
a_and_p =
13.6500 17.2000
Clear out your Workspace by issuing the clear command. Begin by defining
matrix A by issuing the following command:
The semicolons indicate where one row of the matrix ends and a new row begins.
When the Enter key is pressed, matrix A is defined as follows:
Figure 3.19
Any element in the matrix can be addressed using the unique row/column coor-
dinates associated with it. For example, to view the element that occupies the
slot in the second row and third column, issue the following command:
>> A(2,3)
We can similarly use or reassign values in the matrix by using these row/column
coordinates. Issue the command:
>> A(4,1)=-A(2,3)
This command takes the element located in the second row/third column of
matrix A, makes it negative, and assigns it the fourth row/first column of matrix
A. The results of this computation are as follows:
>> A(4,1)=-A(2,3)
A =
1 -1 3
4 -2 -4
2 3 1
4 -3 0
ch03_mus80164.qxd 8/27/08 2:49 PM Page 95
We can also operate on an entire row or entire column of the matrix by using a
similar coordinate address. For instance, let’s replace the entire second row of
the matrix with zeros. We can do this with the following command:
>> A(2,:)=[0 0 0]
>> A(:,1)=A(:,2)+A(:,3)
Figure 3.20
The Array Editor will open, displaying the values of the array, as shown in Fig-
ure 3.21.
Figure 3.21
ch03_mus80164.qxd 8/27/08 2:49 PM Page 96
Not only can the values in the array be viewed, they can also be modified in this
window. Click on the cell located in row 3, column 3, and type in the value “10”
in place of the value “1”, as shown in Figure 3.22.
Figure 3.22
Hit the Enter key to accept the change. The variable will be modified to include
this new value. To close the Array Editor, click on the × in the upper right cor-
ner, as shown in Figure 3.23.
Figure 3.23
To verify that the change has been made, display it by typing the following state-
ment in the Command Window:
>> A
In many applications, matrix variables are useful within scripts and functions. In
the following example, we will demonstrate the use of matrix variables within a
script.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 97
Create a script to find the area and perimeter of all of the rectangles listed in EXAMPLE 3.8
Table 3.4 (repeated from Example 3.4).
■ Solution
As a demonstration, we will create a single matrix variable that contains the
information from Table 3.4 and then use the area_perim function created in
Example 3.7 to perform the calculations.
Save and run the script, giving it a name of your choice. Note that line 11 con-
tains simply the name of the matrix variable containing the area and perimeter
values with the semicolon omitted; this is a simple way of printing the values to
the screen:
Props =
13.6500 17.2000
21.6000 20.4000
24.7500 21.6000
The variable Props contains the areas in the first column and the perimeters in the
second column.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 98
If you have been following along through Section 3.6 of this chapter, you should
have four variables defined in your Workspace Window, as shown in Figure 3.24.
The variable ans is not useful to us at this point; it was created by default by
MATLAB when we outputted our result to the screen from our script file, and it
duplicates the information stored in the Props variable. We have used the clear
Figure 3.24
command previously to clear out the entire Workspace; we can also use it selec-
tively to clear out one or more unwanted variables. To clear just the variable ans
from the Workspace, issue the following command at the prompt:
The remaining three variables may be used in future MATLAB sessions. We can
save them in a proprietary MATLAB format using the save command. We must
designate a filename in which to store the variables; in this example, we will
save the variables to a file called “rectangles.mat” by issuing the following
command:
ch03_mus80164.qxd 8/27/08 2:49 PM Page 99
All variables in the Workspace will be saved in the working directory in the file
rectangles.mat. The file extension .mat is added by default, and need not be
included in the command.
We can recall these three variables at any time using the load command. To
demonstrate this, first clear out the Workspace by using the clear command:
>> clear
Note that the Workspace is now empty. To restore the saved variables to the
Workspace, issue the load command (with the appropriate filename) as follows:
We can also save specific selected variables to a file. For example, if we would
like to store just the Dims and Props variable to a file named “rectdata”, we
can issue the following command:
>> clear
To reload the saved variables, issue the load command (with the appropriate
filename):
Problems
3.1 Using MATLAB, determine the area and perimeter of the shapes shown
in Figures P3.1a–P3.1c.
Figure P3.1a
Figure P3.1b
Figure P3.1c
ch03_mus80164.qxd 8/27/08 2:49 PM Page 101
3.2 A conical tank is shown in Figure P3.2. The tank is filled with water.
Using MATLAB, determine:
a. the volume of water in the tank
b. the weight of the water in the tank.
Figure P3.2
3.3 Using MATLAB, size a spherical tank that has the same volume as the
conical tank in Problem 3.2.
3.4 The manufacturers of the tank described in Problem 3.2 would like to
design another model, with twice the capacity of the one described in Fig-
ure P3.2. The ratio of height to diameter must remain the same as in the
previous model. Use MATLAB to determine the dimensions of the new
model.
3.5 The manufacturers of the tank described in Problem 3.2 would like to
design another model, with half the capacity of the one described in Fig-
ure P3.2. The ratio of height to diameter must remain the same as in the
previous model. Use MATLAB to determine the dimensions of the new
model.
3.6 Write a MATLAB script that will calculate the volume and weight of the
water in any conical tank (as in Figure P3.2), using the input function to
allow the user to enter a diameter and height.
3.7 Write a MATLAB script that will prompt the user to enter the length of
two of the legs of a right triangle (e.g., x and y in Figure 3.6), and will
compute the hypotenuse value using the Pythagorean theorem.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 102
3.8 Write a MATLAB script that will prompt the user to enter the hypotenuse
and the length of one leg of a right triangle, and will compute both the
length of the remaining leg and the area of the triangle.
3.9 Write a MATLAB script that will prompt the user to enter the length of
two of the legs of a right triangle (e.g., x and y in Figure 3.6), and will
compute the two included angles in the triangle.
3.10 Refer to Figure P3.1a. Write a MATLAB script that will allow the user to
enter the width and height of the rectangular portion of the shape, and will
compute the area and perimeter of the shape defined by those dimensions.
3.11 Consider the analytic solution of the projectile problem described in Sec-
tion 1.1.2. Write a MATLAB script that will prompt the user to enter the
launch speed and angle, and will compute the peak height, flight time,
and horizontal distance travelled using the analytic equations.
3.12 Write a MATLAB function called rad2deg that will take an angle in radi-
ans as the input argument and return the angle converted to degrees.
3.13 Write a MATLAB function that will calculate the volume and weight of
the water in any conical tank (as in Figure P3.2). The function should
have two input arguments (diameter and height) and return an array con-
taining the volume and weight of the water.
3.14 Write MATLAB functions to perform the following unit conversions, tak-
ing a value in SI units as the input argument and returning the value con-
verted to U.S. Customary units:
a. Centimeters to inches
b. °C to °F
c. Newtons to pounds
d. Meters per second to miles per hour
Use comments in your function to cite the reference used to determine the
unit conversion values.
3.15 Write a MATLAB function that will take a one-dimensional array con-
taining five numbers as an input argument and return the average of the
five numbers.
3.16 Write a MATLAB function named circles that will calculate the circum-
ference and area of five circles. The function should have five input argu-
ments (diameter) and return a two-dimensional array containing the
circumference and area of the five circles. Calculate the circumference
and area for circles with diameters of 1, 2, 3, 4, and 5 cm.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 103
3.17 Write a MATLAB function named squares that will calculate the perime-
ter and area of five squares. The function should have five input argu-
ments (side length) and return a two-dimensional array containing the
perimeter and area of the five squares. Calculate the perimeter and area
for squares with side lengths of 1, 2, 3, 4, and 5 cm.
3.18 Write a MATLAB function named spheres that will calculate the surface
area and volume of five spheres. The function should have five input
arguments (diameter) and return a two-dimensional array containing the
surface area and volume of the five spheres. Calculate the surface area
and volume for spheres with diameters of 1, 2, 3, 4, and 5 cm.
3.19 Write a MATLAB function named cubes that will calculate the surface
area and volume of five cubes. The function should have five input argu-
ments (side length) and return a two-dimensional array containing the sur-
face area and volume of the five cubes. Calculate the surface area and
volume for cubes with side lengths of 1, 2, 3, 4, and 5 cm.
3.20 In the manufacturing of ball bearings, the components, such as the ball,
are hardened through a process of heating and then rapid cooling or
“quenching” by submersion in an oil or water bath. The temperature of
the ball as a function of time, T(t), in the bath may be estimated as:
T(t) = (Ti – T∞)e–t/τ + T∞
where t is the time in seconds in the bath; Ti is the initial ball temperature;
T∞ is the oil temperature; and τ is the time constant in seconds and
depends upon the material of the ball, the geometry of the ball, and oil
properties. Write a MATLAB function that utilizes Ti; T∞; τ; and three
separate times, t, as input arguments and returns the ball temperature for
the three times as a one-dimensional array.
Assuming an initial ball temperature of 1000°C, an oil temperature of
60°C, and the time contant τ = 60 s, determine the ball temperature for
times of 1, 10, and 100 seconds.
3.21 Write a MATLAB function that will:
■ take a (3 × 3) matrix as the input argument,
■ create a new (3 × 3) matrix by taking the rows of the input matrix and
making them the columns of the new matrix, and
■ return the new (3 × 3) matrix as the output.
For example, if the input matrix is:
⎡ a1 a2 a3 ⎤
⎢b b2 b3 ⎥
⎢ 1 ⎥
⎣ c1 c2 c3 ⎦
ch03_mus80164.qxd 8/27/08 2:49 PM Page 104
⎡ a1 b1 c1 ⎤
⎢a b2 c2 ⎥
⎢ 2 ⎥
⎣ a3 b3 c3 ⎦
3.22 Write a MATLAB function that will take a (4 × 4) matrix as an input
argument and will return a (1 × 4) array containing the averages of each
of the four columns of the input matrix.
3.23 Write a MATLAB function that will take a (4 × 4) matrix as an input
argument and will return a (4 × 1) array containing the averages of each
of the four rows of the input matrix.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 105
C H A P T E R 4
MATLAB
Programming
Introduction
In Chapter 3, we learned how to use MATLAB to perform many calculations. In
this respect, we have used MATLAB in a similar way that we would use a calcu-
lator or a spreadsheet. The power of a programming language is in its ability to
control calculations. The programming features we will learn about in this chap-
ter fall into two categories: loops, which cause a program to perform calculations
repetitively, and logic statements, which cause a program to selectively execute
portions of code, depending on the logical conditions of certain program variables.
4.1 Flowcharts
A flowchart is a diagram that illustrates the steps of a program. Preparing a flow-
chart was once considered an essential step in writing a program. Since computer
time was expensive, a great deal of time was spent planning a program before
actually running it for the first time. With the introduction of the personal com-
puter, debugging of computer programs “on the fly” became the standard prac-
tice, as computer time was essentially free. While drawing flowcharts for the
105
ch04_mus80164.qxd 8/27/08 2:50 PM Page 106
small programs in this book may seem to be unnecessary, there are reasons for
becoming familiar with flowcharts:
■ They can help plan complex programs.
■ They can help to explain a program more easily than with words.
■ They are widely used in other applications; for example, to illustrate the
process flow in design and manufacturing operations.
Some typical flowchart symbols are shown in Figure 4.1. There is a standard set
of symbols designated by the American National Standards Institute (ANSI), but
usage of symbols varies widely. For simplicity, we will use only three symbols:
rectangles to designate program steps, diamonds to represent decision points, and
circles as connectors to show where program paths converge. Arrows are used to
connect the steps and indicate the direction of the progression or “flow” of the
steps.
Figure 4.1
As noted, usage of flowchart symbols varies widely. However, the use of the dia-
mond shape to designate a decision point can be considered universal. Consider
a decision point to be similar to a path that reaches an intersection. Two or more
paths lead away from the intersection. When shown on a flowchart, a decision
point will have one arrow leading in and more than one (usually two) arrows lead-
ing out, as shown in Figure 4.2.
Figure 4.2
ch04_mus80164.qxd 8/27/08 2:50 PM Page 107
Figure 4.3
The choice of the path taken from each decision point in the design process flow
is made by managers and engineers based on an evaluation of the design data
ch04_mus80164.qxd 8/27/08 2:50 PM Page 108
presented at the design review. In programming, the choice of a path from the
decision point will be made based on a logical mathematical condition. For exam-
ple, suppose that at some point in a program, you need to take the absolute value
of a number (ignore for a moment the fact that MATLAB has a built-in function
to do this). If the number is positive or zero, then we do not need to do anything.
If it is negative, then we need to change its sign.
The decision point symbol in Figure 4.4 shows the logical condition (a < 0) as a
question. The arrows leading out of the diamond are labeled with the possible
answers to the question: “Yes” and “No.” If the answer is yes (a is less than zero),
then the flow of the program is to the step below, where the sign of a is changed.
If the answer is no, then that step is skipped. In either case, the program flow then
proceeds to the next step. Note the use of the connector to show where the diver-
gent paths join. Although not required, showing the connectors is good practice
when detailing MATLAB programs, as each connector corresponds to an end
statement in the MATLAB code.
Figure 4.4
In many cases, it will be more logical and compact to describe repetitive calcu-
lations just once, using a single set of instructions. We can then simply indicate
in our program how many times we would like the repetitive calculations
repeated, and let the computer handle the repetition. We will now introduce two
powerful programming constructs that can be used for repetitive calculations: the
for loop and the while loop. The for loop is used to repeat calculations a definite
number of times. The while loop is used to repeat calculations until a certain con-
dition is reached. We will illustrate both types of loops in the following sections.
Figure 4.5
In the for loop, the incrementing of the counter and the decision point evaluation
are embedded within the command itself. The structure of a simple for command
is as follows:
for counter = 1:limit
(Repeated Instructions)
end
(Actually, the counter can begin at a value other than one and increment by a dif-
ferent value, but we will keep the structure simple here and use a counter that cor-
responds to the number of passes through the loop.) The flowchart representation
of the for loop can be condensed into the form shown in Figure 4.6.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 110
Figure 4.6
1 a = 0;
2 for m = 1:10;
3 m
4 a=a+m
5 pause
6 end;
Note that the MATLAB Editor automatically indents the lines between the for
command and the end statement. Indenting the repeated steps in this manner is
helpful when interpreting or debugging script files. Also note that the semicolons
at the ends of lines 2 and 6 are optional; nothing will be written to the screen if
they are omitted.
When we run the script from the Command Window, the lines will be interpreted
as follows:
1. The variable a will be created and set to zero.
2. The for loop will begin. The variable m will be set to the number 1 (the
first number following “=”).
3. The list of statements following the for line will be executed; in this case:
a. The variable m will be printed to the screen.
b. The variable m will be added to the variable a, and the result will be
assigned to the variable a (and printed to the screen).
c. The program will pause, waiting for a keystroke (we have added this
just to monitor the values of the variables; in practice, we will rarely
use a pause command).
ch04_mus80164.qxd 8/27/08 2:50 PM Page 111
4. When the end statement is encountered, the value of the variable m will be
checked against the limit specified in the for command:
■ If increasing the value of m by one will cause it to be greater than the
upper limit set for m in the for line (after the colon; 10 in our example),
the loop will end and the program will continue with the next line after
the end statement.
■ If increasing the value of m by one will not cause m to be greater than
the upper limit, the program will increase the value of m by one and
repeat the steps between the for and end lines (step 3).
Execute the script and monitor the value of each of the variables as the pro-
gram evolves. Press the Enter key to continue the execution at every pause com-
mand. When the execution is completed, the command prompt (>>) will appear.
In this example, we have programmed the statements such that lines 3–5 of the
script are executed 10 times.
The real power of the for loop can be seen when we both automate the repetitive
computations and make use of the counter variable as a useful part of the com-
putations. To demonstrate this, we will plot the sine function for angles from 0 to
2π, using a for loop to automate the repetitive computations. A flowchart of the
program to accomplish this is shown in Figure 4.7.
Figure 4.7
Note the use of the variable i as both our “loop counter” and our “indexing” vari-
able of the arrays; the counter essentially allows us to fill up a long array, one slot
at a time, while still writing the actual command only once. Note that we have
ch04_mus80164.qxd 8/27/08 2:50 PM Page 112
chosen 10 intervals of the angle (given the variable name x) between 0 and 2π.
There will be 11 data points calculated, corresponding to x values:
x = 0, 0.2π, 0.4π, 0.6π, ... 2.0π
This scenario, where the independent variable is to begin at zero and span n inter-
vals (10 in this example), is encountered frequently in programming applications,
especially when the results are to be plotted. In these applications, the for loop
counter should start at one and progress by ones to n + 1 (for i = 1:n + 1), and the
value of the independent variable at each step is as follows:
x(i) = (i – 1) * increment
where
increment = (Upper Limit)/n
The upper limit in this example is 2π.
Save the file as “sinewave” and execute the script by entering its name in the
Command Window. We have introduced the plot command, which creates a
graph in a new window labeled “Figure 1”, as shown in Figure 4.8. The plot com-
mand creates a graph from the two arrays listed as arguments. The first array
defines points along the horizontal axis and the second array contains the corre-
sponding values of the function to be plotted against the vertical axis. Note that
the arrays must be one dimensional and must be the same size. In Chapter 5, we
will learn much more about creating, editing, and formatting graphs. Also note
the clear command on line 2. As we learned in Chapter 3, the clear command
erases the values of variables from memory. When we assign a new value to a
scalar quantity, the new value overwrites the old value. However, when we assign
a value to an element in an array, the rest of the array is unchanged. Therefore,
when working with arrays, it is good practice to clear the variables before per-
forming calculations.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 113
Figure 4.8
The curve in Figure 4.8 is not very smooth because MATLAB creates the
curve as a series of straight-line segments between the data points. However, we
can easily change the number of elements in each array from 11 (10 intervals) to
1001 (1000 intervals). Modify the script as shown (note the changes on lines
6 and 7):
To execute the script, we can use a shortcut from the command prompt. As you
can see in the Command History Window, MATLAB remembers the recent com-
mands that you have entered. You can repeat any of these commands by using the
“up” arrow key to scroll through them, starting with the most recent one entered.
Note that if you execute a script from the Editor with the Save and run command,
the command will not appear in the Command History and this shortcut will not
work.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 114
From the command prompt, press the “up” arrow key once, which will display
the name of our script, sinewave. Press the Enter key to execute the script.
Notice how, by using a greater number of points, we get a much smoother, more
accurate curve, as shown in Figure 4.9; however, there is no change in the com-
plexity or length of the code.
Figure 4.9
while loop. In most cases, however, we will want to add one because the number
of times that the program passes through the loop will often be of importance to
us. The while loop must contain a logical condition to control the looping. As long
as the condition is true, the looping will continue. A consideration when using
while loops is the possibility of creating an infinite loop. It is possible to inad-
vertently define a logical condition that is never false. If that is the case, then the
looping will continue until the execution of the program is stopped manually.
(Pressing the C key while holding down the Ctrl key terminates the execution of
a MATLAB program.) On a PC, this is an inconvenience. For a complex program
being executed on a mainframe computer, such an error can be costly.
The while loop command in MATLAB contains the logical condition in the first
line:
while (condition)
(Repeated instructions)
end
1 % Initialize variables
2 m = 0;
3 a = 0;
4
5 while a < 54;
6 m = m + 1
7 a = a + m
8 pause
9 end;
10
11 a
Save the script as “whiletest” and execute it. When you execute the script, notice
that this script performs exactly the same task as our fortest script; the difference
is that the value of the variable a is monitored to determine the point at which the
loop ends. Notice also that in a while loop, there is no variable that automatically
increases; if we want to keep track of the number of times that the program passes
through the loop, we must assign a variable as a “counter” (m) and advance the
counter’s value within the loop (as in line 6). In this case, the final value of m is
10, so the program passed through the loop 10 times.
Note that if we change the “stopping criteria,” the number of times the loop exe-
cutes will change. For example, modify the script as follows (note the addition
of the clear command in line 1 and the change in the while line). Execute the
script.
1 clear;
2 % Initialize variables
3 m = 0;
4 a = 0;
5
6 while a < 100;
7 m = m + 1
8 a = a + m
9 pause
10 end;
11
12 a
ch04_mus80164.qxd 8/27/08 2:50 PM Page 117
Note that after 14 passes through the loop, the value of a is 105. Since the condi-
tion no longer meets the condition set in the while line (a < 100), the execution
terminates.
In the while line, we can check other conditions beside the “less than” (<) condi-
tion. For example, modify the script as follows:
1 clear;
2 % Initialize variables
3 m = 0;
4 a = 0;
5 b = 200;
6
7 while a < 100 & b >= 50;
8 m = m + 1
9 a = a + m
10 b = b - 10
11 pause
12 end;
13
14 a
15 b
Save and execute the script and monitor the output. The loop will now continue
to be executed as long as both of these conditions are true: a is less than 100 and
b is greater than or equal to 50. As an exercise, experiment with different initial
values of a and b and observe the effect on the number of passes the program
makes through the loop.
“If a variable takes on a specified value, then execute the following lines of code.”
if (condition)
(Instructions executed only if the condition is true)
end
To demonstrate the use of the MATLAB if statement, initiate a new m-file and
enter the following script:
Note that we have introduced a new MATLAB command, fprintf, in this script.
It is useful for displaying formatted output to the screen. The \n at the end of the
fprintf command causes the display to skip to the next line. We will learn more
about this command later in this chapter. Also note that lines 2, 5, and 7 are
scrolled over two lines each because of space limitations on the page. When you
enter these lines, type each on a single line.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 119
The logic built into the program is illustrated in Figure 4.13. If the logical
condition following the if statement (in this case, y > 10 ) is true, then all
of the statements between the if line and end line are executed; if the logi-
cal condition is false (in this case, y ≤ 10), then the program skips to the
end line. We call this logical branching because the program “branches”
into different section of code, depending on the value of the logical condi-
tion.
Save this script under the name “iftest” and run it a few times to verify
that the programming logic is correct.
Of course, the logical condition used in the if statement can be more com-
plex than that used in our script. Commonly used relational operators are
listed in Table 4.1. Statements using these relational operators can be com-
bined using logical operators, which are also listed in Table 4.1. For exam-
ple, consider this statement:
Figure 4.13
if x == 5
The command(s) following the statement will be executed only if the value of x
is equal to 5. Note that a single equal sign is used to assign a value (for example,
x = 3); the double equal sign is used to define a condition. As another example,
consider this statement:
if x >= 5 & x ~= 10
The command(s) following this statement will be executed for all values of x
greater than or equal to 5, except for x = 10.
Consider this example, in which we modify our iftest script to include addi-
tional logical checks:
Note that the logical “or” (entered as “|” on line 6; this symbol is inserted from
the keyboard as Shift + \) has been used to check multiple conditions. Test the
program three times, inputting the numbers 0, 4, and 11.
We can also imbed logical branches within logical branches to achieve complex
logical conditions. Further modify your script as follows:
12 if y < 1
13 y = 1;
14 fprintf(‘The number has been changed
to 1.\n’);
15 end;
16 end;
17
18 % Display the number
19 y
Test the program three times, inputting the numbers 0, 4, and 11.
A flowchart for this algorithm is shown in Figure 4.14. Note that although the
logic is more complex than the previous example, the if statement is the basic
“building block” of the logical statements. Each if statement is followed by a
command or commands that are executed only if the relevant condition is true.
The program flow then proceeds to the next step. Note in the flowchart that when
two paths join together, there is a connector shown, and each connector corre-
sponds to an end statement in the MATLAB code.
Figure 4.14
ch04_mus80164.qxd 8/27/08 2:50 PM Page 122
By now, you might have noticed that the functioning of the if statement in MAT-
LAB works somewhat differently than the IF function in Excel. In Excel, we saw
that the IF function returned one value if the condition was true and another value
if the condition was false. In MATLAB, an if statement does something if the con-
dition is true and does nothing if the condition is false. The MATLAB construct
analogous to the Excel IF function is the if-else block. The if-else block, as well
as the if-elseif-else block, is discussed in the next section.
Figure 4.15
ch04_mus80164.qxd 8/27/08 2:50 PM Page 123
the first decision point, there are program steps corresponding to each output
path, rather than to only the “yes” path.
Modify your iftest script as follows (the first 15 lines are unchanged):
Test the program three times, inputting the numbers 0, 4, and 11.
Note that the statement following the else statement (line 17) is only executed if
the logical condition presented in its matching if statement (line 6) is false.
While the if-else block allows the program flow to be directed in one of two direc-
tions, we often encounter conditions where more than two outcomes are possi-
ble. In these cases, we can “ladder” together multiple condition checks, using the
addition of one or more elseif statements to our if block.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 124
For example, we will rewrite our complex logic in this preceding script using
an if-elseif-else block:
Again, test this script for values of 0, 4, and 11. Notice that the logic of the script
is identical to the previous version, but the code is more readable and compact.
The flowchart, as shown in Figure 4.16, is also more compact and easier to
follow.
We can “ladder” together much more complex logic once we understand this log-
ical branching.
6 if y > 15
7 fprintf(‘The number is much too high. This
program will terminate\n.’)
8 elseif y > 10
9 fprintf(‘The number is a little too high.
It will be changed to 10\n’)
10 y = 10
11 elseif y == 10
12 fprintf(‘The number is right at the upper
limit\n’)
13 y
14 elseif y <1
15 fprintf(‘Your number is too low. It will be
changed to 1\n’)
16 y = 1
17 else
18 fprintf(‘The number is in the range\n’)
19 y
20 end;
Figure 4.16
ch04_mus80164.qxd 8/27/08 2:50 PM Page 126
Notice carefully the output for the case of y = 16; while this criteria would make
both the first (y > 15) and second (y > 10) conditions true, only the first branch
(associated with the y > 15 condition) is executed. In an if-elseif-else block, the
logical conditions will be tested in order; once one of the conditions is met, no
further testing of conditions will be done. The code block associated with the first
“true” condition will be executed, and the program will proceed with the line of
code following the end statement. This concept is illustrated in the flowchart of
Figure 4.17. The first decision point corresponds to the if statement; each of the
subsequent conditions corresponds to an elseif statement. At each decision point,
if the condition is true, then the program flow branches off. If the condition is
false, then the flow proceeds to the next condition. This repeats until the last con-
dition, where the program again branches off if the condition is true, but also has
instructions to execute if all of the conditions are false (the else case). All of the
divergent parts re-join at the connector corresponding to the single end statement
required.
Figure 4.17
ch04_mus80164.qxd 8/27/08 2:50 PM Page 127
Generate and plot on the same axes both a sine wave and a square wave, for x val- EXAMPLE 4.1
ues from 0 to 4π. Square waves are encountered frequently in digital electronics.
Like a sine wave, a square wave is a periodic function, but transitions instantly
from one value (+1) to a second value (–1). One way to define a square wave is
to compare it to a sine wave of the same period. The value of the square wave
function is +1 if the sine is positive, –1 if the sine is negative, and zero if the sine
is zero.
■ Solution
We will need a for loop to calculate and store values to be plotted. We will use
1000 intervals of the independent variable x. Therefore, each pass through the
loop, x will progress by a value of 4π/1000. The loop counter, i, will start at one
and increment by one to a value of 1001. The two dependent variables to be cal-
culated and stored will be called ysine and ysquare.
Figure 4.18
ch04_mus80164.qxd 8/27/08 2:50 PM Page 128
The flowchart for our program is shown in Figure 4.18. For each value of x,
we will calculate the sine and store its value in the ysine array. Then we will
examine the sign of ysine and calculate the correct value of ysquare. Since there
are three possible values of ysquare, an if-ifelse-else logical block will be the
most efficient.
1 %Clear Variables
2 clear;
3
4 %Wave Generation Loop
5 for i = 1:1001;
6 %Create Sine Wave
7 x(i) = (i–1)*(4*pi/1000);
8 ysine(i) = sin(x(i));
9 %Create Square Wave
10 if ysine(i) > 0;
11 ysquare(i) = 1;
12 elseif ysine(i) < 0;
13 ysquare(i) = –1;
14 else
15 ysquare(i) = 0;
16 end;
17 end;
18
19 %Plot data
20 hold off;
21 plot(x,ysine);
22 hold on;
23 plot(x,ysquare,’r’);
24 axis([0 max(x) –1.2 1.2]);
Save and execute this script. Note how if-elseif-else logic is used to test the ysine
values, and how branching is used to create the ysquare values. As an aside, also
note that we have added some plot formatting commands. The square wave is
shown with a red line because of the ‘r’ added to its plot command. The axis com-
mand, used in conjunction with the max command, is used to properly scale the
axes for this plot, which is shown in Figure 4.19. Note that both functions are
plotted on the same graph as a result of the hold on command of line 22. This
command causes the current plot to be “held” so that additional data can be
added. In Chapter 5, we will learn about many other plotting options.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 129
Figure 4.19
In many textbook problems, particularly in statics, a 3-4-5 triangle is encoun- EXAMPLE 4.2
tered. The geometry of the 3-4-5 triangle, as shown in Figure 4.20, simplifies
many calculations. It is obviously a right triangle, and it is easy to see that the
cosine of the angle theta is 4/5, the sine of theta is 3/5, and the tangent of theta
is 3/4.
Figure 4.20
The property that makes this triangle so useful is that the sum of the squares of
the two short sides, which are integers, is a perfect square—a number that is the
square of an integer. Therefore, the hypotenuse of the triangle is an integer.
We want to find more of these triangles with integer side lengths. We will search
for triangles with lengths of the short sides up to 25 units.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 130
■ Solution
We will call the lengths of the short sides x and y. Our calculations will need to
progress through two nested loops, as shown in Figure 4.21.
Figure 4.21
In the first loop, the value of x progresses from 1 to 25. For each value of x, we
will evaluate all values of y from 1 to 25. Therefore, we will be evaluating all
25 × 25, or 625 combinations of x and y. How do we know if the hypotenuse of
each triangle is an integer? Consider the MATLAB function floor. We can get
details about this function by typing “help floor” at the command prompt:
>> help floor
FLOOR Round towards minus infinity.
FLOOR(X) rounds the elements of X to the nearest integers
towards minus infinity.
As you might expect, there is also a ceil (for ceiling) function that rounds values
up to the next integer. If the hypotenuse h is an integer, then rounding it with the
floor function will have no effect. Therefore, if h is equal to floor(h), then h is an
integer.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 131
The program will find 22 triangles with integer sides, beginning with 3-4-5, fol-
lowed by 4-3-5, 5-12-13, 6-8-10, 7-24-25, and so on. The manner in which the
results are displayed to the screen makes viewing the results difficult. In the next
section, we will learn more about formatting MATLAB output. Before doing so,
however, you might have noticed that the second triangle found, 4-3-5, is actu-
ally the same as the 3-4-5, with x and y switched. Since the order of x and y is
arbitrary, we are essentially reporting the same answer twice.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 132
x=1
y = 1, 2, 3,..., 25
The next time through the “outer” loop, x is 2 and y again progresses from 1 to 25:
x=2
y = 1, 2, 3,..., 25
But the case where one variable is 1 and the other is 2 has already been evaluated.
Therefore, the “inner” loop should begin at y = 2 to eliminate duplicates.
x=3
y = 1, 2, 3,..., 25
Now there are two cases that have already been evaluated: (1,3) and (2,3). There-
fore, the inner loop should begin at y = 3.
We can generalize the analysis above to say that the inner loop should begin with
a value of y equal to the current value of x. This is easy to implement in our MAT-
LAB script; we simply change the definition of the inner loop in line 10:
for y = x:25
Change the “1” in line 10 to “x”, as shown previously, and save and run the
modified script.
The final value of m, the number of triangles with integral triangles found, is now
11. This makes sense, as we found 22 before, half of which were duplicates.
Keep the script file open for the formatting tutorial that follows.
For example, %8.1e indicates that the variable will be printed in a space that is
eight characters wide, will be displayed in scientific notation, and will be rounded
to one decimal place.
The text string can also contain the special characters \n, which advance the print-
ing to the next line. There are several other special characters that can be used,
such as \t for a tab. A search for fprintf in the MATLAB help files will show all
of the formatting options available; the options presented in this section will be
sufficient for most applications.
To illustrate use of the fprintf function, consider the examples shown in Table 4.2.
In all of these examples, m = 12 and d = 7532.1234.
In our file Triangle from the previous section, each triangle found was defined by
its side lengths x, y, and h. We would like to print these lengths on the same line
for each triangle found.
In the file Triangle, change the lines where x, y, and h are printed to the screen
to a single fprintf command, as shown here. Also, modify the last line, which
controls the display of the counter m (the rest of the file is unchanged):
20 if h == floor(h)
21 m = m + 1;
22 fprintf(‘%5i%5i%5i\n’,x,y,h)
23 end
24 end
25 end
26 fprintf(‘\nThe number of triangles found =
%i\n’,m)
ch04_mus80164.qxd 8/27/08 2:50 PM Page 134
Note that the “\n” character in line 22 causes the display to skip to a new line after
the values of x, y, and h for each triangle is written. In line 26, a “\n” at the begin-
ning of the text output string causes a line to be skipped after the last values of x,
y, and h are written, and the “\n” at the end of the string causes the command
prompt to be displayed to a new line.
Save the modified file. In the Command Window, enter “clc” to clear the dis-
play. Run the file Triangle. The results are shown in Figure 4.22.
The values from the screen can be easily copied and pasted into Word
or Excel files. However, when large amounts of data are generated,
we would sometimes like to write the data directly to an output file.
To do so, we need to first define the name of the file. This is done with
the fopen command. The format for defining a filename is as follows:
fid = fopen(‘filename’, ‘attribute’)
The filename is assigned to the identifying variable fid (any variable
name can be used). If you are writing to a text file, it is good prac-
tice to add a .txt extension to the filename. This will cause the file to
open in the default text editor (usually Notepad) when the filename
is double-clicked in Windows. The file attribute that we will be Figure 4.22
using is ‘wt’, which stands for write text. If the file does not exist, it
will be created. If it does exist, then its contents will be overwritten with the new
data. If you want to add (append) data to a file already created, use ‘at’ as the file
attribute.
We will now write the results of the Triangle program to a file named output.txt.
13 for x = 1:25
14 for y = x:25
15
16 % Calculate the hypotenuse h
17
18 h = sqrt(x^2 + y^2);
19
20 % Check to see if h is an integer
21 % If it is, write x, y, and h to the
screen
22 % and advance the value of the counter m
23
24 if h == floor(h)
25 m = m + 1;
26 fprintf(fid,’%5i%5i%5i\n’,x,y,h);
27 end
28 end
29 end
30 fprintf(‘\nThe number of triangles found =
%i\n’,m);
In line 9, the command to open the file for write access is issued. Lines 10 and 11
define column headers to be written. Since they will only be written once, these
commands are placed before entering the loops. The fid as the first argument of
the fprintf commands specifies that the output is written to the file instead of the
screen. The fid identifier is also added to line 26. Note that for fprintf functions
that specify file output, it is good practice to add a semicolon to the end of the
line. Otherwise, the number of characters written to the file is reported to the
Command Window. For line 30, which prints the number of triangles found, we
will leave off the “fid” so that the output specified will still be printed to the
screen instead of the file.
In the Current Directory Window, notice that the file output.txt has been cre-
ated, as shown in Figure 4.24. This file can be opened in Notepad, Word, or
Excel, or in the MATLAB Editor. To open it in the MATLAB Editor, simply
double-click the filename.
Finally, change the upper limits of x and y to 1000 each on lines 13 and 14.
Save and run the program.
In the Command Window, we see that 456 triangles with integer side lengths have
been found. If you open the file output.txt, you will see that all 456 solutions have
been written to the file.
Problems
4.1 Determine the value of A after each of the following MATLAB scripts is
executed:
a. A = 0; c. A = 12;
for i = 1:5 if A > 10
A = A + 5; A = A/2;
end
end
if A >10
A = A/2;
b. A = 2; end
while A < 10
A = 2*A; d. for i = 1:5
end A(i) = i;
end
ch04_mus80164.qxd 8/27/08 2:50 PM Page 138
4.7 Suppose you borrow $1000 from a friend, who agrees to let you make any
monthly payment that you choose, as long as you pay 0.5% interest every
month on the unpaid balance. Create a MATLAB function that calculates
and outputs the number of months required to pay off the loan, with the pay-
ment amount as the argument of the function. Find the number of months
to pay off the loan if you make monthly payments of:
a. $100
b. $50
c. $10
What happens if you try to pay less than $5 per month?
4.8 In Chapter 1, we studied the problem of a projectile being launched at an
angle of θ at an initial velocity of ν. The equations for the height h and hor-
izontal location x as functions of time t are as follows:
1 2
h ( t ) = t sin − gt
2
x ( t ) = t cos
Write a MATLAB program to calculate and store h and x for time incre-
ments of 0.1 seconds for θ = 20° and ν = 200 feet per second. Use a value
for g of 32.2 feet/s2. Continue to make the calculations until the projectile
hits the ground. Use the plot command to create three graphs:
a. t along the horizontal axis, h along the vertical axis
b. t along the horizontal axis, x along the vertical axis
c. x along the horizontal axis, h along the vertical axis (this is a plot of
the trajectory of the projectile)
You can either run the file three times, changing the values to be plotted
each time, or you can include three separate plot commands. If you choose
the latter option, insert the command figure on a separate line between plot
commands. This will open a new plotting window, so the prior graph is not
overwritten.
4.9 In Problem 2.13, you created a spreadsheet for calculating the thickness of
a typical sheet of paper, 0.004 inches, which is folded multiple times. After
one fold, the thickness is doubled to 0.008 inches, after two folds, it is dou-
bled again to 0.016 inches, and so on. Write a MATLAB program to deter-
mine the number of folds necessary to achieve a theoretical thickness of:
a. 1 inch
b. 1 mile
c. The distance from Earth to the moon
ch04_mus80164.qxd 8/27/08 2:50 PM Page 140
4.10 In a mechanics of materials course, you will learn how to calculate the
deflections of beams. The use of discontinuity functions allows the equa-
tion for the deflection of a beam with multiple loadings to be written as a
single equation. The definition of a discontinuity function is as follows:
n ⎧( x − a )n if x ≥ a
x−a =⎨
⎩ 0 if x < a
For the steel beam shown in Figure P4.10, the deflection ν in inches of the
beam can be shown:
v=
1
3.190 e 9
(800 x 3 − 13.68 e 6 x − 2.5 x 4 + 2.5 x − 120
4
+ 600 x − 240
3
)
where x is also expressed in inches.
Figure P4.10
Write a MATLAB script to plot the deflected shape of the beam and find
the maximum absolute value of the deflection and its location from the left
end in inches. Use 1/2-inch increments for calculating the deflections.
4.11 Refer to the Triangle program written in Section 4.4. When examining the
output values, it is clear that many of the triangles are similar. For example,
consider the 3-4-5 and 6-8-10 triangles. The shape of these triangles is the
same; the side lengths of the second triangle are simply a multiple of two
greater than the sides of the first. Modify the program to eliminate similar
triangles from being printed to the screen. How many triangles will be
found for the limits of 1 to 25 for the short side lengths?
Hint: Save the x and y values of triangles meeting the criterion to arrays.
When you identify a new candidate triangle, check it against each of the
stored triangle values by dividing the new x value by the stored x value and
dividing the new y value by the stored y value. If these two ratios are iden-
tical, the candidate triangle is similar to one already stored, and so its val-
ues will not be stored and/or printed.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 141
4.12 Home loans are usually made for 15- or 30-year periods, with payments
made monthly. An amortization table is often useful for a borrower to see
how much interest is being paid each month, and the remaining balance of
the loan each month. Consider a 30-year $200,000 loan at an annual inter-
est rate of 6.0% (360 payment periods, interest = 0.5% per month). From
economic formulas, we can calculate that the monthly payment should be
$1199.10. Write a MATLAB program to create a text file containing an
amortization table for this loan. For each month, show the balance before
the payment is made (the previous balance times 1.005), the payment, and
the new balance after the payment is subtracted. Format the table similar to
Figure P4.12A (only 12 of 360 lines shown). Use a while loop to determine
when the balance goes below zero and add a formatted statement at the end
of the file to show the overpayment that will be refunded to the borrower,
as shown in Figure P4.12B. (Note: The $1,199.11 payment was rounded up
to the nearest cent, resulting in a slight overpayment over the 360 months.
If the payment had been rounded down to $1,199.10, then there would be a
small balance remaining after 360 payments.)
Figure P4.12A
Figure P4.12B
4.13 Modify the MATLAB program created in Problem 4.12 to see the effect of
increasing the monthly payment to $1,300.
4.14 Consider Problem 4.12. Suppose that you receive stock dividends every
year, beginning in month 12 of the loan, and want to make an additional
payment of $1,000 in every month that a dividend is received. Modify your
MATLAB program so the payment increases to $2,199.11 every 12 months,
but remains at $1,199.11 in other months. What is the effect of these pay-
ments?
ch04_mus80164.qxd 8/27/08 2:50 PM Page 142
ch05_mus80164.qxd 8/27/08 2:50 PM Page 143
C H A P T E R 5
Plotting Data
Introduction
When performing engineering computations, we typically generate a large vol-
ume of data. Sometimes the data can be adequately summarized in tables, but a
graphical representation of the data is almost always useful. A well-designed
graph can allow a reader to visually process data much easier than by reading a
large table of numbers. Graphs can often help us to interpret data, showing cause-
and-effect relationships that are otherwise not easily recognizable.
143
ch05_mus80164.qxd 8/27/08 2:50 PM Page 144
plot a smooth curve, such as the sine function of an angle, as shown in Figure 5.1.
Often, multiple variables are plotted on the same x-axis, such as the sine and
cosine functions shown in Figure 5.2. In this figure, a legend is used to distin-
guish the two curves.
When actual data points are to be plotted, those points are shown with data mark-
ers, as shown in Figure 5.3. When many points are plotted, they create a “scat-
tered” appearance, leading to the term scatter plot. However, it is unusual to
publish an XY graph without a line. When actual data points are plotted, they are
usually accompanied by one of these types of lines:
■ a theory curve, which shows how well the data points agree with theoreti-
cal values,
■ a fit line (called a trendline in Excel), which is a curve based on the values
of the data points, or
■ a series of straight-line segments connecting the data points, forming a
rough curve. This option is the least desirable of the options, since the line
segments do not represent any equation.
In Figure 5.4, a theory curve has been added. In this case, the data points repre-
sent tests in which slender steel rods are loaded with compressive forces along
their axes until they buckle. The smooth curve represents the theoretical buckling
load, calculated from an equation developed from mechanics of materials con-
cepts. In undergraduate engineering labs, this type of comparative graph is often
produced by students to show how well an experiment can be designed and con-
ducted to match a well-established theory. However, this type of graph also
appears often in technical literature, as new theories are verified with experi-
mental data.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 145
While XY graphs are the most commonly used in engineering reports and
papers, there are several other graph types that are useful for presenting data.
Among the simplest types of graphs are pie charts and bar graphs. These graphs
are used to show the relative values of items within a one-dimensional data set.
A pie chart, as the name implies, shows items as segments of a complete circle,
similar to slices of a pie. An advantage of a pie chart is that it allows for visual-
ization of the value of one item relative to another, and of an item relative to the
entire data (the whole pie). A pie chart of the distribution of a class’s exam
grades is shown in Figure 5.5. Note that we can make quick visual comparisons,
such as the number of A’s is about double the number of F’s, and that C’s make
up about one-third of the total grades, based on the rel-
ative size of the “slice” of the pie representing C’s.
Another type of bar chart that is widely used in quality control and process
improvement is the Pareto diagram. In a Pareto diagram, data is arranged in cat-
egories. For example, a certain new car model might need servicing during the
first few months after purchase. The cause of each service visit could be classi-
fied as an engine problem, a paint defect, trouble with the exhaust system, etc.
The number of service visits due to each problem is plotted on a bar graph, with
the categories arranged in order, from the greatest number of problems to the
least, as shown in Figure 5.9. A Pareto diagram also typically includes a cumula-
tive percentage line. This line shows the percentage of the total service visits for
the categories up to and including the one of interest. For example, the line is at
about 80% for the category of transmission problems. This means that the visits
classified as Exhaust, Electrical, or Transmission make up about 80% of all ser-
vice visits.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 147
5.2 XY Graphs
As noted previously, XY graphs are the most important type of graphs used in
engineering applications. The following two tutorials will take you through the
steps of creating XY graphs with Excel and MATLAB.
D = 1 − 2 (5.2)
This solution is valid for an initial velocity of zero; that is, the spring is stretched
by an amount equal to y0, and then released. We will be calculating and graphing
values of y, the dependent variable, for values of t, the independent variable. We
say that y is a function of t, since all of the other quantities in Equation 5.1 are
constants.
EXAMPLE 5.1 Plot displacement versus time for a spring-mass-damper system. Let y0 = 3 in,
ω = 2π radians/second, and ξ = 0.10.
■ Solution
Open a new Excel workbook. Label cells for the constants y0 , ω , and ξ and
enter the values given previously, as shown in Figure 5.10. Enter the natural
frequency value as “= 2*PI()”.
Figure 5.10
Recall that PI() is an Excel function that returns the value of π. Since all func-
tions in Excel require an argument in parentheses, it is necessary to enter the
empty parentheses for the function to be recognized.
It is not necessary to enter the symbols in the cell labels, but if you want to do so,
simply choose Insert: Symbol from the Ribbon when typing in the label. Change
the Font to Symbol, as shown in Figure 5.11, and select the desired character.
Click Insert to place the character in the label. You may want to reduce the num-
ber of decimal places displayed for the natural frequency value. If you do, show
at least three decimal places so that we can compare this value to that of the
damped frequency, which we will calculate next.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 149
Note the value that is calculated from this equation, 6.252 radians/
second, is very close to that of the natural frequency. When the damp-
ing coefficient is small, the natural frequency and damped frequency
are approximately equal.
Label cells for the time and displacement. Enter values of time from
zero to 1 second in 0.1-second increments, as shown in Figure 5.14.
In cell B8, enter the expression for the displacement given in Equa-
tion 5.1:
“=(B1*COS(B5*A8)+B1*B3*B2/B5*SIN(B5*A8))*
EXP(-B3*B2*A8)”.
The value returned from this expression should be 3.0 inches, since
that is the initial displacement. Figure 5.14
ch05_mus80164.qxd 8/27/08 2:50 PM Page 150
Before copying this equation to the other cells in the column, we need to fix the
references to cells B1:B5 so that they remain constant. In this case, we will fix
the row numbers of these cells, but not the column numbers. That way, if we cre-
ate a new column later in order to compare different input values, we can easily
copy our formulas to the new column.
Double-click cell B8 to edit the formula. For each reference to cells B1, B2, B3,
and B5, click to set the cursor between the column and row number and press
the F4 key twice. This fixes the row number in that cell reference, so that a dol-
lar sign appears before the row number (but not the column letter). The equa-
tion should now appear as shown in Figure 5.15.
Figure 5.15
Double-click the fill handle at the lower right-hand corner of cell B8, as shown
in Figure 5.16. This causes the formula to be copied to the cells in column B
that are adjacent to the input values in column A. Compare your values to those
shown in Figure 5.17.
Figure 5.16
Figure 5.17
ch05_mus80164.qxd 8/27/08 2:50 PM Page 151
Figure 5.18
The resulting graph is shown in Figure 5.19. By default, Excel graphs are placed
on the current page of the workbook. However, if the graph will be printed or
copied and pasted into another application, then placing the graph on its own
page allows for better control over its appearance.
Note that when a chart is created or selected, the Ribbon contains three groups of
Chart tools: Design, Layout, and Format.
Under the Chart tools, click Design, and select Move Chart, as shown in Fig-
ure 5.20. Next, choose New sheet and click OK.
We arbitrarily selected a time interval from zero to 1 second. From the graph, it
appears that we need to extend our time domain.
Select the cells containing the last two values of time (0.9 and 1 second), as
shown in Figure 5.22. Click and drag the fill handle downward until a value of
5 appears beside the cursor, as shown in Figure 5.23. Release the mouse but-
ton and the values up to 5 seconds in increments of 0.1 seconds will be filled
into the time column.
Recall that to perform this operation, you must select at least two cells initially in
order to define the pattern of the cells to be filled.
Select the last cell containing the formula for the value of y (next to the cell
containing the time value of 1 second). Double-click the fill handle, as shown
in Figure 5.24, and the formula will be copied to the cells below.
range is highlighted. Switch to the sheet containing the data and highlight the
entire new data range. The new data range is shown in Figure 5.26. Click OK.
The graph is now shown in Figure 5.27. By extending the time domain to 5 sec-
onds, we have a better visualization of the behavior of the system, as the ampli-
tude of the oscillations decreases with time.
With the chart selected, go to the Design tab. Beside the Chart Format choices,
click the More arrow, as shown in Figure 5.28, to display choices of line colors,
background colors, and line widths. Select a style with a plain white back-
ground and a relatively wide line.
The tools that we will use to change the appearance of the graph are located under
the Layout tab of the Ribbon.
Choose Layout: Chart Title: Above Chart, as shown in Figure 5.29. Enter the
title “Response of Spring-Mass-Damper System” in the formula bar, as shown
in Figure 5.30, and press the Enter key.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 154
Choose Layout: Axis Titles: Primary Horizontal Axis Title: Title Below Axis
and enter “Time, seconds” as the axis label. Choose Layout: Axis Titles: Pri-
mary Vertical Axis Title: Rotated Title and enter “Displacement, inches” as the
axis label.
Since there is only one data series plotted on this graph, a legend is not needed.
By default, horizontal gridlines are shown, but vertical gridlines are not. We often
would like to have vertical gridlines in order to better estimate specific values
from the graph.
The x-axis of our graph extends from zero to 6 seconds. Since our data extends
only to 5 seconds, we can override the automatic scaling of the axis and have our
axis extend to only 5 seconds.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 155
Note that you can also access these options by right-clicking on the axis and
choosing Format Axis. Many of the formatting options discussed in this section
can be accessed by either using the commands on the Ribbon or by right-
clicking the entity to be modified within the chart area.
We will now add a second curve that will allow us to see how the response of the
system changes with a different damping coefficient.
EXAMPLE 5.2 Add a second curve to the graph created in Example 5.1. The second curve will
correspond to a damping coefficient ξ = 0.20.
■ Solution
Copy and paste the cells defining the input quantities of the displacement equa-
tion, as shown in Figure 5.39. Change the value of the damping coefficient in
the second set of inputs to 0.2. Before copying the formula for the displacement,
double-click in the cell containing the first calculation of y (cell B8 in Figure
5.39) to edit the formula. For each of the three references to the cell contain-
ing time, press the F4 key three times, so that a dollar sign appears before the
column letter (but not the row number), as shown in Figure 5.40.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 157
Figure 5.39
Figure 5.40
Copy the formula to the first cell under the second “y” label. Double-click on
this cell (F8) to show the formula, as shown in Figure 5.41.
Figure 5.41
The color-coded cell references are excellent aids for checking and trou-
bleshooting formulas. Notice here that all references to the initial displacement,
frequency, damping coefficient, and damped frequency are
to the values in the columns above the cell containing the
formula, while references to the value of time are to Col-
umn A.
Copy this formula down the column until the last entry is
on the row containing the time value of 5 seconds.
For the Series name, enter “Damping Factor = 0.2”. Click the icon next to the
box labeled “Series X values”, as shown in Figure 5.43. Highlight the cells con-
taining the time values from zero to 5 and press Enter. Click the icon next to
the Series Y values box and highlight the y values in column F.
The definition of the new series should look like Figure 5.44.
Click OK, click Series 1, select Edit, change the Series Name to “Damping Fac-
tor = 0.1”, and press the Enter key. Click OK to close the Select Data Series box.
Right-click on the new curve in the graph and select Format Data Series, as
shown in Figure 5.45. Select Line Color and choose a color for the new line.
Then, select Line Style and select a dashed line, as shown in Figure 5.46. Adjust
the line width downward to show the space between the dashes more clearly.
From the Layout tab of the Ribbon, select Legend: Overlay Legend at Right, as
shown in Figure 5.47. Click on the legend and from the Home tab on the Rib-
bon, increase the font size. Right-click on the legend and select Format Leg-
end. Change the fill to solid fill with a fill color of white. Change the border
color to a solid line with black as the color.
Figure 5.48
⎡ y ⎤
y = ⎢ y0 cos D t + 0 sin D t ⎥ e − t (5.1)
⎣ D ⎦
where
D = 1 − 2
■ Solution
In this tutorial, we will be using two MATLAB commands: plot and fplot. With
the plot command, an array of y values is plotted against an array of x values. The
fplot command plots values of a function for a specified range of values of the
argument of the function. We will examine the plot command first.
To use the plot command, we must create two one-dimensional arrays. The for-
mat of the command is as follows:
plot(x,y)
ch05_mus80164.qxd 8/27/08 2:50 PM Page 160
where x is the array containing values to be plotted along the horizontal axis (in
our case, time) and y is the array containing values to be plotted on the vertical
axis (displacement). It is important that these arrays are the same size, so that
there is a value of displacement for each value of time. As with the Excel graph,
we will calculate displacements for a time domain of zero to 5 seconds. We will
use a time increment of 0.05 seconds, so each array will contain 101 values. We
will use a for loop to create the arrays. The counter of the for loop, i, will range
from 1 to 101. The time corresponding to counter i will be (i – 1) × 0.05, so that
the time value for our first point will be zero. The value of displacement, y, will
be calculated from Equation 5.1. Since we will be using a for loop, the use of a
smaller time increment does not require more effort, as it would for creating an
Excel graph.
Open a new m-file. Type the following lines into the editor. Save the file as
“SMD”.
Note that the equation for y could be written on a single line within the for loop
as follows:
y(i) = (3.0*cos(2*pi*sqrt(1-0.10^2)*t(i))+3.0*0.10*
2*pi/(2*pi*sqrt(1-0.10^2))*sin(2*pi*sqrt(1-0.10^2)*
t(i)))*exp(–0.10*2*pi*t(i))
However, there are several reasons for breaking a long equation into a series of
smaller steps.
■ If the constants in the equation—the initial displacement, damping coeffi-
cient, and natural frequency—are assigned variable names, as in lines
11–13, then they will be easier to change later. Rather than having to search
for every occurrence of a variable and changing each one, we need to
change only the one line where the variable name is assigned.
■ The damped frequency occurs three times in the equation for displacement.
If it is entered three times, then there is a greater chance of making an
error. Another reason for performing the calculation only once and assign-
ing the damped frequency to a variable name, as in line 14, is that its value
is not a function of time. Therefore, the calculation can be made before
entering the for loop, which is more efficient than making the same calcu-
lation repeatedly within the loop.
■ Performing the calculations for the sine, cosine, and exponential terms sep-
arately, as in lines 17–19, makes the final equation in line 20 much simpler.
There is only one pair of parentheses, compared to the 11 pairs on the right
side of the equation above. Incorrect placement of parentheses is a com-
mon cause of errors.
■ Checking the calculations is much
easier. Complex equations should
always be checked by hand, and
breaking equations into smaller
steps makes the checking process
easier.
Figure 5.49
ch05_mus80164.qxd 8/27/08 2:50 PM Page 162
Right-click in a blank area of the screen and choose Show Property Editor, as
shown in Figure 5.53.
When finished, click the X in the upper right-hand corner of the Prop-
erty Editor to close it, as shown in Figure 5.55. To change the color of
the area around the plot to white, right-click in that area, select Color,
and choose white.
When working in Excel, graphs and their formatting are saved when the
file is saved. In MATLAB, however, closing a session closes all graphs,
and they must be re-created by running the m-file. If formatting is done
interactively, as previously, then the formatting must also be redone.
Figure 5.55
Therefore, it is a good idea to save or
copy a graph that you have edited. If you
choose File: Save As from the main
menu, the graph can be saved as a MAT-
LAB graph or in a variety of graphics
formats such as jpeg or bitmap. These
files can then be imported into other
applications later. Another way to use the
graph is to copy it immediately into the
application where it is to be used, such as
Word or PowerPoint.
shown to turn on the grid and to add and format the title and axes labels. Note
that the last three commands (title, xlabel, and ylabel) continue over two lines
each. The ellipsis (...) at the end of a line indicates that the command is con-
tinued to the next line. You may write each of these commands on a single line,
if you prefer.
21 end
22 plot(t,y,’LineWidth’,4,’Color’,’Red’)
23 grid(‘on’)
24 title(‘Response of Spring-Mass-Damper System’,...
25 ‘FontSize’,20,’FontName’,’Arial’)
26 xlabel(‘Time, seconds’,’FontSize’,14,...
27 ‘FontName’,’Arial’);
28 ylabel(‘Displacement, inches’,’FontSize’,14,...
29 ‘FontName’,’Arial’);
Save the file. From the command prompt, run SMD. The new graph is shown
in Figure 5.58.
Not all formatting options are available as MATLAB commands, so you may
want to perform further editing interactively. However, adding some formatting
commands to the m-file can save editing time if the m-file is used repeatedly.
Figure 5.58
ch05_mus80164.qxd 8/27/08 2:50 PM Page 165
In Example 5.2, we added a second curve showing the effect of changing the
damping coefficient. We will repeat this example with MATLAB.
Add a second curve to the graph created in Example 5.3. The second curve will EXAMPLE 5.4
correspond to a damping coefficient ξ = 0.20.
■ Solution
At the end of the SMD file, add the lines shown below, which define the second
value of the damping coefficient, calculate the new damped frequency, and cal-
culate a new displacement for every value of time.
30 %
31 % Compute and plot displacements for a
32 % different damping coefficient
33 %
34 % dc2 = new damping coefficient
35 % fd2 = new damped frequency
36 % y2 = new displacement array
37 %
38 dc2 = 0.20;
39 fd2 = fr*sqrt(1-dc2^2);
40 for i = 1:101
41 c = cos(fd2*t(i));
42 s = sin(fd2*t(i));
43 e = exp(-dc2*fr*t(i));
44 y2(i) = (y0*c + y0*dc2*fr/fd2*s)*e;
45 end
46 plot(t,y2,’LineWidth’,3,’LineStyle’,...
47 ’—’,’Color’,’Blue’);
Save and run the m-file SMD. Note that it is not nec-
essary to define the time values again; we will use the
existing time array. The new graph is shown in
Figure 5.59.
In the SMD m-file, insert a figure command before the second plot command:
45 end
46 figure
47 plot(t,y2,’LineWidth’,3,’LineStyle’,...
48 ’—’,’Color’,’Blue’);
There will be two graphs created in windows labeled Figure 1 and Figure 2.
While this example showed how to create multiple graphs from an m-file, we
want to show both sets of data on a single graph. For this, we will need to use the
hold command. The hold on command keeps the current graph open so that sub-
sequent plotting commands will add to the current graph. There is also a hold off
command that closes the graph from further additions. The use of the hold com-
mand alone (without the value in parentheses) toggles the command between
hold on and hold off. To prevent ambiguity, it is recommended that on or off be
specified.
Since we will have more than one curve on the graph, we will need a legend to
distinguish them.
In the SMD file, replace the figure command with a hold on command. Also,
add the legend command as shown:
45 end
46 hold on
47 plot(t,y2,’LineWidth’,3,’LineStyle’,...
48 ’—’,’Color’,’Blue’);
49 legend(‘Damping Coefficient = 0.1’,...
50 ‘Damping Coefficient = 0.2’);
Note that in the legend command, the two curves are identified in the order in
which they are created.
Save and run the file. Make any desired edits (such as the font sizes of the leg-
end and numbers on the axes) to the graph with the Property Editor. Click and
drag the legend to the desired location.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 167
Figure 5.60
Another useful MATLAB plotting command is fplot. To use fplot, the function to
be plotted must be written as a MATLAB function m-file. The general form of
the fplot command is as follows:
fplot(‘functionname’,[xlower xupper])
where xlower and xupper are the lower and upper limits of the function arguments.
That is, xlower and xupper define the domain of the independent variable. The fplot
command can be used to plot built-in MATLAB functions in addition to function
files that you generate. For example, we can plot the sin function for values of
zero to 2π radians by entering this command:
Create the following file in the editor. You can cut and paste some of the lines
from the SMD file.
1 function y = displace(t)
2 y0 = 3.0;
3 dc = 0.10;
4 fr = 2*pi;
5 fd = fr*sqrt(1-dc^2);
6 c = cos(fd*t);
7 s = sin(fd*t);
8 e = exp(-dc*fr*t);
9 y = (y0*c + y0*dc*fr/fd*s)*e;
Save the file as displace. Check the function by finding the displacement at
2 seconds:
>> displace(2)
ans =
0.8467
Create a plot of this function from time = 0 to time = 5 seconds by calling the
fplot command:
Figure 5.61
ch05_mus80164.qxd 8/27/08 2:50 PM Page 169
Modify the first line of the function file, as shown here, and save the modified
file as displace2.
1 function y = displace2(y0,dc,fr,t)
Test this new function by finding the displacement for the values y0 = 3, dc =
0.1, fr = 2π, and t = 2:
>> displace2(3,.1,2*pi,2)
ans =
0.8467
In order to use the fplot command for this multiple-argument function, it is nec-
essary to input the values for all of the arguments except for the independent vari-
able to be plotted (time, in our case) and the limits of the independent variable.
EXAMPLE 5.5 Plot the spring test data shown in Table 5.1 and determine the spring constant.
■ Solution
In a new spreadsheet, enter
the values shown in Table 5.1
in two columns. Highlight the
entire data range. From the
Ribbon select Insert: Scatter,
and choose Scatter with only
Markers, as shown in Figure
5.64. Move the graph to a sep-
arate sheet of the workbook,
add titles and axis labels, and
format the graph as desired. Figure 5.64
ch05_mus80164.qxd 8/27/08 2:50 PM Page 171
Trendlines can be
selected for other
types of fits (we will
use the exponential fit
later in the tutorial).
The Forecast option
allows the line to be
extrapolated beyond
the first and last data
points, although you
Figure 5.66 should use this option
with caution. When
you extrapolate beyond the limits of your measured data,
you are making the assumption that the factors influenc-
ing the data values in the measured range will also have
the same effects outside this range. There is also an option Figure 5.67
for setting the y-intercept to a given value (for example, if
you wanted to force the line to pass through the origin).
ch05_mus80164.qxd 8/27/08 2:50 PM Page 172
Select the equation on the graph and change its font size. If desired, right-click
on the equation box and select Format Trendline Label to change the fill color
and border of the equation box.
The graph with the least-squares curve fit is shown in Figure 5.68. The R2 value
(the correlation coefficient) is a measure of the quality of the fit to the data. The
closer the value is to one, the better the line fits the data. In our case, where we
know that the theory predicts a linear relationship, then a value close to one is
expected. In other cases, where there are multiple independent variables affect-
ing the results, the correlation coefficient will be much lower. In these cases, the
correlation coefficient can be used to determine which of the independent vari-
ables has the greatest effect on the result.
Figure 5.68
EXAMPLE 5.6 A cup of water is placed in a microwave oven and heated until the water is almost
boiling. The cup is then removed from the microwave and a thermometer is
placed in the water. When the temperature cools to 200°F, a stopwatch is started.
As the water cools, the temperature is recorded at several times. The time-tem-
perature data is shown in Table 5.2. The air temperature of the room is 77°F. Plot
the temperature data from the test and fit a curve to the data points.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 173
■ Solution
Enter the data from Table 5.2 in an Excel sheet. Create and format a scatter
graph, with data markers and no lines, as shown in Figure 5.69.
smoothing option. This leaves the polynomial and exponential trendlines as pos-
sibilities.
With a polynomial fit, the order of the polynomial can be specified. The trendline
in Figure 5.70 was created with a second-order polynomial, so the curve has the
following form:
y = Ax2 + Bx + C
A better fit to the data can be realized by using a higher-order polynomial. The
trendline in Figure 5.71 was created with a fourth-order polynomial:
y = Ax4 + Bx3 + Cx2 + Dx + E
Both of these trendlines fit the data very well, as indicated by the R2 values very
close to one. An even better fit can be realized with higher-order polynomials.
However, both of the polynomial trendlines have a problem, one that is more evi-
dent with the fourth-order fit; that is, the trendlines predict that the temperature
will begin to increase over time. This observation leads to an important rule to
keep in mind when curve fitting:
The selected curve should be consistent with the nature of the actual data,
regardless of the quality of fit to the data points.
Clearly, a model which predicts that the cup of water will cool down and then
begin to heat up again is of no practical value.
We are left with the exponential trendline as the only remaining choice. This
makes sense, as exponential curves are used to model problems of growth and
decay where the rate of change is increasing or decreasing. Examples are the
decay of radioactive materials and the compound-interest growth of bank
accounts. In the first tutorial of this chapter, the displacement of the spring-mass-
ch05_mus80164.qxd 8/27/08 2:50 PM Page 175
Right-click on one of the data points and select Add Trendline. Select Expo-
nential as the type, check the boxes to show the equation on the chart and to
display the R-squared value, as shown in Figure 5.72, and click Close.
Five decimal places might seem more than necessary, but the exponent is a very
small number. Using only two or three decimal places will result in a loss of accu-
racy when applying the equation of the curve.
The finished graph is shown in Figure 5.80. Note the excellent agreement
between the data and the trendline, as well as the logical observation that the tem-
perature difference is approaching zero (that is, the water temperature is
approaching room temperature) as time increases.
Plot the spring test data, shown in Table 5.1, and determine the spring constant. EXAMPLE 5.7
■ Solution
In MATLAB, enter the data as two arrays. Since the displacement data is
equally spaced, you can use the colon operator to generate that array. Plot the
data.
>> d = 1:10;
>> F = [102 156 230 317 400 452 530 611 670 739];
>> plot(d,F)
Note that if you want to see the slope and intercept without displaying them on
the graph, checking the arrow at the lower right-hand corner of the Basic Fitting
box reveals the values of these parameters.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 178
Figure 5.83
The finished graph is shown in Figure 5.85. From the equation of the line, our
estimate of the spring constant is 72.3 N/mm.
■ When actual data points are plotted, they should be identified with data
markers. The points will often be connected with straight-line segments,
unless a theoretical curve or a trendline is shown on the graph. An excep-
tion to this guideline is often made when the number of data points is
extremely large and markers result in a cluttered appearance. In these
cases, a line only may be shown. The line should consist of straight-line
segments between data points.
■ When an equation is plotted, a smooth curve without data markers should
be shown. In this case, there is no special significance to the points chosen.
■ Consider the context of the data when determining the scale of the y-axis.
For example, consider the graphs showing the closing stock price of a com-
pany over a week of trading in Figures 5.86 and 5.87. In Figure 5.86, the
y-axis begins at zero and the stock price appears to be relatively stable dur-
ing the week. In Figure 5.87, the automatic scaling of the y-axis makes the
day-to-day changes appear greater. Which is correct? For this example,
Figure 5.87 is typical for a chart of stock prices. The changes in stock
prices shown in this example would be considered quite large, and
Figure 5.86 does not show the volatility of the price very well. A “broken
axis” is sometimes used to show that the axis does not extend to zero. An
example is shown in Figure 5.88. However, Excel and MATLAB do not
have built-in functions to create this type of axis break. This example was
created in Excel by manually adding a white-filled box over the axis to
create the break, drawing two lines, and adding a text box to create the
zero label.
■ When displaying multiple graphs for the purpose of making comparisons,
use consistent scales for the graphs.
■ Finally, keep in mind that in an engineering paper or report, a well-
designed graph can be a valuable and sometimes necessary component, but
should always be referred to and discussed in the text.
Figure 5.88
In these examples, we will look at the costs associated with manufacturing a cer-
tain product that we will call Product ABC. The costs are shown in Table 5.3 for
the previous year and for the current year.
EXAMPLE 5.8 Create a pie graph of the current year’s data from Table 5.3.
■ Solution
In a new worksheet, enter the data shown in Table 5.3. Format the cells con-
taining dollar amounts to Accounting Number Format by clicking the dollar
ch05_mus80164.qxd 8/27/08 2:50 PM Page 181
sign in the Home group of the Ribbon, as shown in Figure 5.89. Highlight the
cost values for the current year only, as shown in Figure 5.90.
From the Ribbon, select Insert: Pie and select a 2-D Pie, as shown in Figure 5.91.
From the Design group, select a black-and-white color scheme, as shown in
Figure 5.92.
First, we will make the pie smaller to allow more room for the labels.
Right-click on the pie and choose Add Data Labels, as shown in Fig-
ure 5.95. The value of each slice will appear, as shown in Figure 5.96.
Figure 5.94
Right-click on one of the data labels and choose Format Data Labels, as shown
in Figure 5.97. Check the options shown in Figure 5.98, and click Close. With
the data labels selected, change to a larger font size from the Home group of
the Ribbon.
and dragging on the pie itself. Also, it is sometimes desirable to separate one slice
from the rest of the pie to highlight it. To do this, click on the pie to select it and
then click again on the slice to be moved. You can then click and drag that seg-
ment to a new location.
Right-click in the white space around the pie and select Change Chart Type.
Choose a 3-D pie, as shown in Figure 5.107.
Right-click on the pie and choose 3-D rotation, as shown in Figure 5.108. Set
the rotation about the y-axis to a new value, as shown in Figure 5.109. A value
of 90° leaves the graph as 2-D, while a lower angle produces a “flatter” graph.
Experiment with different values of rotation.
Figure 5.110
We will now present the same data with a bar graph. (As noted before, bar graph
is a commonly accepted term for this type of graph, regardless of the orientation
of the bars. In Excel, a bar graph in which the bars are vertical is referred to as a
column chart.)
Create a bar graph showing the data for both years from Table 5.3. EXAMPLE 5.9
■ Solution
Select the current-year cost data, as shown in Figure 5.111. From the Ribbon,
select Insert: 2-D Column: Clustered Column, as shown in Figure 5.112.
Move the graph to a separate sheet. Right-click on the graph and choose Select
Data. Next, click Edit under the Horizontal (Category) Axis Labels, select the
cells containing the category names, and click OK. Click OK again to close the
Select Data box. Then, add and format a title and a label for the y-axis. Right-
click on the chart and select Format Plot Area: Border Color: Solid line, choose
black as the border color, and change the color of the gridlines to gray.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 186
Figure 5.113
If the graph is to show only one set of data, then we would delete the legend.
However, we will now add the data for the prior year and will use the legend to
distinguish the two years.
Right-click on the graph and choose Select Data. Click Add, as shown in Fig-
ure 5.114. For the Series values, select the data for the previous year, as shown
in Figure 5.115.
Click on Series 1, select Edit, and rename the series “Current Year”. Click the
Move Down arrow, as shown in Figure 5.117, so that the previous year’s values
will be displayed before the current year’s.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 187
Figure 5.119
ch05_mus80164.qxd 8/27/08 2:50 PM Page 188
EXAMPLE 5.10 Create a Pareto graph from Table 5.3’s current year data.
■ Solution
A Pareto graph combines a bar graph and a line graph. Even if you never have the
occasion to use a Pareto graph, this exercise will show you how to combine two
graph types and how to use a secondary y-axis.
Copy and paste the categories and current year cost data to a new region, as
shown in Figure 5.120.
Figure 5.120 In a Pareto graph, the categories are arranged by their values, from high to low.
Therefore, we need to sort the data.
Select the categories and their cost values. From the Data group of the Ribbon,
select Sort, as shown in Figure 5.121. In the Sort box, make sure that the data
is to be sorted by the column containing the costs, from largest to smallest, as
shown in Figure 5.122. Make sure the box labeled “My data has headers” is
unchecked and click OK.
Below the cost data, add a formula to sum the cost data. In the cell immediately
to the right of the labor cost, add a formula to divide the labor cost by the total
cost, as shown in Figure 5.124.
In the cell immediately to the right of the overhead cost, add a formula to divide
Figure 5.123 the overhead cost by the total cost and add it to the value of the cell immediately
above, as shown in Figure 5.125. Make sure to fix the reference to the total
value cell so that it will not change as this formula is copied.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 189
Copy the last formula to the cells below it. Note that by default, the num-
bers are displayed in Accounting Number Format. Highlight this col-
umn and click on the Percent Style icon in the Home group of the
Ribbon, as shown in Figure 5.126.
The column that we have just created contains the cumulative percentage
of the total cost that is made by each cost category; that is, the first cell
indicates that labor accounts for 34% of the total cost. The second cell
indicates that labor and overhead make up 66% of the total cost, and so
on.
Create and format a new bar graph with the cost data, as shown in
Figure 5.128. A legend is not needed and should be deleted.
Right-click in the graph area and choose Select Data. Click Add to create a new
series and choose the cumulative percentage values as the Series values, as
shown in Figure 5.129. You do not need to give the new series a name.
The new series will appear as a new group of bars on the graph.
Right-click on one of the bars corresponding to the series just created. Select
Change Series Chart Type, as shown in Figure 5.130.
Note that if you right-click in the white space of the graph, you get an option to
change the chart type. We used this option to change the pie graph from a 2-D to
a 3-D chart. When you have multiple series and you right-click on one of the
series representations in the graph, then you have the option to change the chart
type for that series only.
Figure 5.131
ch05_mus80164.qxd 8/27/08 2:50 PM Page 191
The line will be close to the horizontal axis, since it is based on the same y-axis
as the cost numbers. To spread the line over the vertical range available, we need
to plot the cumulative percentage data on a secondary y-axis.
Note that the gridlines correspond to the primary axis and not the secondary axis.
In order to align the gridlines to both axes, it is necessary to adjust the axis ranges
so that the divisions will match up. For example, if we set the primary axis range
from 0 to $20 and the secondary axis range from 0 to 1 (100%), then the axes will
both be divided naturally into 10 even intervals.
Set the maximum value of the primary y-axis to 20 and the maximum value of
the secondary y-axis to 1. Next, add a label to the secondary axis.
Problems
5.1 Plot the following equation with Excel, for values of x from -3 to 6.
y = x4 – 4x3 – 6x2 + 15
5.2 With Excel, plot the cosine of an angle versus the angle in degrees, for
values from 0 to 360°.
5.3 Plot the following equation with Excel, for values of x from 0 to 10:
y=3 x
5.4 Repeat Problem 5.1 with MATLAB, using a for loop and the plot com-
mand.
5.5 Repeat Problem 5.1 with MATLAB by creating a function and using the
fplot command.
5.6 Repeat Problem 5.2 with MATLAB, using a for loop and the plot com-
mand.
5.7 Repeat Problem 5.2 with MATLAB using the fplot command.
5.8 Repeat Problem 5.3 with MATLAB, using a for loop and the plot com-
mand.
5.9 Repeat Problem 5.3 with MATLAB by creating a function and using the
fplot command.
5.10 The hyperbolic functions cosh and sinh are occasionally encountered in
engineering applications (for example, a rope or cable hanging under its
own weight forms a curve called a catenary, which is defined by a cosh
function). These functions relate to a hyperbola in the same way that
cosine and sine relate to a circle. Both Excel and MATLAB have built-in
cosh and sinh functions. Plot both functions on the same set of axes for x
values from –2 to 2, using Excel. Comment on the shapes of the curves.
5.11 Add a curve representing tanh, the hyberbolic tangent, to the graph cre-
ated in Problem 5.10.
5.12 Repeat Problems 5.10 and 5.11 with MATLAB.
5.13 We learned in Chapter 2 that ball bearings are hardened through a process
of heating and then rapid cooling, or “quenching,” by submersion in an
oil or water. The temperature of the ball during the quenching process can
be estimated from Equation 2.3, which is repeated here:
T(t) = (Ti – T∞)e–t/τ + T∞
ch05_mus80164.qxd 8/27/08 2:50 PM Page 193
where t is the time in seconds in the bath; Ti is the initial ball temperature;
T∞ is the oil temperature; and τ is the time constant in seconds and
depends upon the material of the ball, the geometry of the ball, and oil
properties. In Excel, create a spreadsheet that calculates the ball tempera-
ture for times from 0–180 seconds at 1-second intervals. Assume that the
initial ball temperature = 800°C, the oil temperature = 40°C, and the time
constant = 50 seconds. Create a graph showing ball temperature versus
time.
5.14 Add two curves to the graph created in Problem 5.13, representing time
constants of 20 seconds and 100 seconds. Extend the time values plotted
until the temperature is less than 80°C for all three curves.
5.15 Repeat Problems 5.13 and 5.14 in MATLAB. Use a while loop to gener-
ate the arrays to be plotted, with a stopping condition that the value of
temperature for all three arrays to be plotted is less than 80°C. Make a
second graph, with the time values extended until the temperature is less
than 60°C for all three curves.
5.16 When a rope is pulled across a fixed cylinder, such as shown in Figure
P5.16, the tension in the rope is greater on one side than on the other due
to friction between the rope and the cylinder. In this example, the force
required to lift the 500-N weight will be greater than 500 N, since the
friction force is resisting the movement. In statics, you will learn that the
relationship between the two forces is as follows:
T2 = T1eμθ
where μ = the coefficient of friction, a property of the two contacting
materials, and θ = the contact angle in radians.
Figure P5.16
Use Excel to plot T2, the force required to lift the weight, versus the angle
in degrees from 0 to 720 (the rope wrapped completely around the cylin-
der twice), using μ = 0.3 and T1 = 500 N. Comment on the results.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 194
Figure P5.17
5.18 The diameters of 30 marbles are shown in Table P5.18. Use Excel to cre-
ate a histogram showing the distribution of the marble diameters.
Note that when selecting your bin sizes, it is a good rule of thumb to have
somewhere between 5 and 15 bins. Select a logical value for the bin
ranges, such as 0.0025 or 0.0050 inches. You may sort the data into bins
manually, by using IF statements, or by using the Histogram function
available in the Data Analysis Add-In.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 195
PART 2
Engineering Applications
Chapter 6: Finding the Roots of Equations
195
ch06_mus80164.qxd 8/27/08 2:51 PM Page 196
ch06_mus80164.qxd 8/27/08 2:51 PM Page 197
C H A P T E R 6
Finding the Roots of
Equations
Introduction
The solution of algebraic equations is a common application for computational
tools. Both MATLAB and Excel contain powerful utilities for the solution of
algebraic equations. In this chapter, the various forms of algebraic equations will
be explored, and the proper choice and application of the appropriate solution
tool will be investigated.
197
ch06_mus80164.qxd 8/27/08 2:51 PM Page 198
6.1 Motivation
Suppose we are designing a beam for a structural engineering application. A
schematic of the beam is shown in Figure 6.1.
Figure 6.1
We want to choose the dimension of the cross section of the square steel beam so
that the beam is strong enough to support the 500-lb weight hanging from the end.
In order to minimize the amount of material that we will use, we want to size the
beam so that the amount of stress that the beam experiences at its most critical
point is exactly equal to the strength of the steel beam. From knowledge of
mechanics of materials, and using the dimensions shown in Figure 6.1, we know
that the largest stress (σ ) that the beam experiences is shown in Equation 6.1:
300, 000 85, 800
= + (6.1)
x3 x
where σ is the stress in units of pounds per square inch and x is the unknown
cross-sectional dimension in inches. This takes into account both the 500-lb
weight and the weight of the steel beam itself.
Using knowledge of material science, we know that our steel beam has a strength
(or allowable stress) of 12,000 pounds per square inch. Therefore, we want to
choose the dimension of the square cross section (x) such that:
300, 000 85, 800
+ = 12, 000 (6.2)
x3 x
This will be the smallest cross section that will support the 500 lb load. In order
to size our beam properly, we need to find a solution to Equation 6.2.
f ( z ) = z + 24 = 0 (6.10)
f ( x) = 3x − 7 = 0 (6.11)
Linear algebraic equations are the type encountered in most introductory algebra
classes; they have exactly one root, and they can be solved exactly using analytic
methods.
Any equation that cannot be rearranged and classified as a linear algebraic equa-
tion is classified as a nonlinear algebraic equation. It may contain the indepen-
dent variables raised to powers other than one (i.e., x2 and x1/2) and/or nonlinear
functions of the independent variable (i.e., sin(x) and log(x)). Nonlinear algebraic
equations can have no roots, a single root, multiple roots, or an infinite number
of roots; they can have both real and imaginary roots. Except in a few simple spe-
cial cases, they are not easy to solve; in fact, quite often no closed-form analytic
solution exists.
− B ± B 2 − 4 AC
y= (6.16)
2A
yielding at most two real roots. However, in general, solution of polynomial
equations will require an algorithmic or graphical solution.
Figure 6.2
root finding will be described. Initially, we will use a simple linear algebraic
equation as the case study; this will allow us to introduce some of the important
points of root finding while keeping the mathematics as simple as possible.
For this case, consider the function described in Equation 6.9, repeated here:
f ( y) = 7 y − 6 (6.18)
If we want to determine the location of the root, or the value of y that makes
f (y) = 0, graphically, we could plot the function over some range, and read the
value of y at the point where the function f (y) crosses the horizontal axis, as
shown in Figure 6.3.
Examining this figure, at the scale at which the plot is constructed, we could esti-
mate the root; concluding from the plot that the root occurs somewhere in the
interval between a lower estimate, rl = 0, and an upper estimate, ru = 1. We might
provide a ballpark estimate by reporting a value in the middle of these endpoints,
and report that the root is approximately r = 0.5. This is shown graphically in Fig-
ure 6.4.
Is this an accurate enough estimate of the root? Perhaps, depending on the spe-
cific application. If we needed a more accurate estimate, we could plot the func-
tion on a finer scale, using more closely spaced values on the horizontal axis.
From the scale shown in Figure 6.5, we could conclude that the root is somewhere
between rl = 0.5 and ru = 1; we might approximate the root in the middle as r =
0.75.
This may be accurate enough, or we might resort to an even finer scale for our
plot. From Figure 6.6, we would report that the root is somewhere between rl =
0.75 and ru = 1.0, approximating the root as r = 0.875.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 203
Figure 6.7
ch06_mus80164.qxd 8/27/08 2:51 PM Page 204
If we were to program the Bisection Method using MATLAB, and run the pro-
gram with an initial interval between 0 and 1, the root would eventually converge
on a very accurate estimate. This is demonstrated in Table 6.1, which shows 15
iterations of the Bisection Method for this example problem.
Note that the flowchart for the Bisection Method includes some “stopping crite-
rion”; when the interval gets “very small,” the program will terminate, and the
final estimate of the root will be reported. In the results shown in Table 6.1, the
algorithm was terminated when the upper and lower limits of the interval differed
by less than 0.0001. We could always keep going; repeated iterations would con-
tinue to move us closer and closer to the “true” solution. However, at some point
we terminate the program and assume that our estimate is accurate enough for our
application.
These observations about the Bisection Method lead to some important charac-
teristics of most algorithmic root finding methods:
■ They generally require some type of initial guess at a root: In the Bisection
Method, this took the form of an interval (low and high value) that was
known to contain a root. In other methods, it may be a single guess in the
neighborhood of a root. In either case, we need to know an approximate
location of the root we are trying to find before invoking the method.
■ They provide estimates of the root(s), to some level of predetermined accu-
racy: In our Bisection Method, a final interval was specified. In other
methods, we might check to see if our estimates are still changing signifi-
cantly as we keep “improving” our estimates. In any case, it is important to
remember that algorithmic root finding techniques, as with any algorithmic
solution method, provide approximations, not exact solutions.
Table 6.1 Fifteen Iterations of the Bisection Method for Equation 6.18
yl yu yr f(yl) f(yr)
With these observations in mind, we will explore a second algorithm for finding
the root of an equation. This algorithm is known as Newton’s Method (or the
Newton-Raphson Method). Like the Bisection Method, this solution technique
uses an estimate of the root of an equation to generate an improved estimate of
the root, which will become closer and closer to the actual solution as the algo-
rithm is repeated. Unlike the Bisection Method, however, Newton’s Method uses
a single estimate of the root, and uses the projection of the slope of the function
at the estimate to obtain the improved root estimate.
These steps are repeated over and over again, until an estimate that is close
enough to the true root is determined.
To begin, we will arbitrarily guess that the root occurs at the point x = 10. This is
strictly an arbitrary guess; we could certainly come up with a more accurate guess
by plotting Equation 6.20 over a range of x values, but for this demonstration an
arbitrary guess will suffice. Applying Newton’s Method, we:
■ Evaluate Equation 6.20 at the point xi = 10. In this case:
Checking the actual value of Equation 6.20 at this improved estimate yields a
value of y = 368.494. If this is close enough to zero, we could stop here. If not,
we would set xi = 7.6724, and repeat the algorithm again. Table 6.2 shows seven
iterations of Newton’s Method; note that after five iterations, the root has settled
on the same value to four decimal places.
Figure 6.10
■ When a function has multiple roots, a bracketing method will always find
the one root that exists between the upper and lower guesses. In an open
method, the algorithm will converge on one of the roots, but it is some-
times difficult to predict which of the multiple roots an open method will
find. In general, an open method will converge on the root closest to the
initial guess, but not always; it depends on the shape of the curve as well.
■ While both methods require repeated evaluation of the function, Newton’s
Method requires additional information on the slope of the function. This
requires evaluation of the derivative of the function, either using principles
of calculus or a numerical approximation of the derivative.
While bracketing methods do have the advantage of guaranteed convergence,
most commercial root finding software programs employ open methods.
To demonstrate these differences, Table 6.3 shows the results of applying the
Bisection Method to the solution of Equation 6.20, which was solved using New-
ton’s Method in Table 6.2. Initial guesses of xl = 5.0000 and xu = 6.0000 were used
to begin the algorithm. Note that while the Bisection Method eventually con-
verged to the same solution as Newton’s Method, the algorithm required 15 iter-
ations to find the same root.
In the remainder of this chapter, we will explore the use of MATLAB and Excel
in the solution of nonlinear algebraic equations. As we do, keep these observa-
tions about algorithmic root finding in mind.
Table 6.3 Fifteen Iterations of the Bisection Method for Equation 6.20
xl xu xr y (xl) y (xr)
5.0000 6.0000 5.5000 –50.0000 –14.6250
5.5000 6.0000 5.7500 –14.6250 9.3906
5.5000 5.7500 5.6250 –14.6250 –3.1738
5.6250 5.7500 5.6875 –3.1738 2.9670
5.6250 5.6875 5.6563 –3.1738 –0.1385
5.6563 5.6875 5.6719 –0.1385 1.4055
5.6563 5.6719 5.6641 –0.1385 0.6313
5.6563 5.6641 5.6602 –0.1385 0.2459
5.6563 5.6602 5.6582 –0.1385 0.0536
5.6563 5.6582 5.6572 –0.1385 –0.0425
5.6572 5.6582 5.6577 –0.0425 0.0055
5.6572 5.6577 5.6575 –0.0425 –0.0185
5.6575 5.6577 5.6576 –0.0185 –0.0065
5.6576 5.6577 5.6577 –0.0065 –0.0005
5.6577 5.6577 5.6577 –0.0005 0.0025
ch06_mus80164.qxd 8/27/08 2:51 PM Page 209
The method for solution described in this section for the solution of a nonlinear
equation can be summarized as follows:
1. Write the equation in standard form f(x).
2. Develop a MATLAB function to compute the value of f (x) for any input
value x.
3. Use the fplot command to obtain an estimate of a root of the equation.
4. Use the fzero command (along with the estimate of the root) to compute the
root.
5. Check the root, to be sure that f (x) = 0.
Using an example case, we will now explore this solution method step by step.
Find a value for x that makes the following expression true: EXAMPLE 6.1
■ Solution
Step 1: Write the equation in standard form. Recall that the “standard form”
results when we recast the problem in the form f(x) = 0. Therefore:
f ( x ) = x tan x − 0.4 (6.26)
Step 2: Develop a MATLAB function to compute the value of f(x) for any input
value x. In the MATLAB Editor, create the following function, and save it
under the name “ex6_1”.
1 function f = ex6_1(x)
2 f = x*tan(x) - 0.4;
ch06_mus80164.qxd 8/27/08 2:51 PM Page 210
This function can now be used to evaluate f(x) for any input x. Check the func-
tion for an x value of 4 from the command prompt:
>> ex6_1(4)
ans =
4.2313
Step 3: Use the fplot command to obtain an estimate of a root of the equation.
The root finding technique that we will use requires a single estimate in the neigh-
borhood of the root of interest. Since our equation has been defined as a MAT-
LAB function, we can use the intelligent plotting command fplot to develop a plot
of the equation (as described in Chapter 5). From there, we can estimate a root of
the function graphically. We first need to guess a plotting interval that will show
us at least one root. We will try the interval between 0 and 1.5. Issue the follow-
ing command at the prompt:
fzero(‘function_name’, guess)
ch06_mus80164.qxd 8/27/08 2:51 PM Page 211
The fzero function returns a root of the equation defined in the function file func-
tion_name in the neighborhood of the initial guess of the root. Note that the fzero
function requires only a single guess of the root; therefore, this function uses an
open method as its root finding algorithm. To find a root of the equation
described in our ex6_1 function file in the neighborhood of our initial guess of
x = 0.5, and to store its value as r, issue the following command at the prompt:
>> r = fzero(‘ex6_1’,.5)
r =
0.5932
The value 0.5932 is returned as the root of the function. It should be noted that
there are multiple roots to this equation; we have only determined the closest one
to our initial guess.
Step 5: Check the root to be sure that f(x) = 0. It is always good practice to check
your results. In the root finding problem, we should evaluate our function at the
final root value to be sure that it yields f (x) = 0. Since our root is stored in the
variable r, and we have our equation coded in a function file, we can do this by
typing the following command at the prompt:
>> ex6_1(r)
ans =
-5.5511e-017
This five-step method using the fzero command as our root finding algorithm is
applicable in the general case of any algebraic equation. However, since MAT-
LAB has a simpler and more powerful tool especially suited to polynomial equa-
tions, we will generally employ this five-step method to the general nonlinear
case.
EXAMPLE 6.2 Find a value for x that makes the following expression true:
144
2 x 2 + 10 x = (6.27)
x
■ Solution
Step 1: Write the equation in standard form. Recall that the standard form results
when we recast the problem in the form f(x) = 0. In addition, for a polynomial
equation the independent variable x can appear raised to positive integer powers
only. Therefore, the equation must be rearranged as follows:
f ( x ) = 2 x 3 + 10 x 2 − 144 (6.28)
Note that the equation was written in decreasing powers of x from left to right,
starting with the x3 term and ending with the x0 (or constant) term. This will facil-
itate Step 2.
Step 2: Define a MATLAB array containing the constant coefficients of the poly-
nomial equation. MATLAB has powerful prewritten functions that can be used
to simplify computation with polynomial equations. To use these, we must first
develop a row array that contains the coefficients of our polynomial equation. For
example, if our polynomial is of the following form:
f ( x ) = A1 x n + A2 x n −1 + A3 x n − 2 + … + An −1 x + An (6.29)
then our array of polynomial coefficients would be:
p = [ A1 A2 A3 … An −1 An ]
Define our array of polynomial coefficients by entering the following expres-
sion at the MATLAB command line:
>> p = [2 10 0 –144];
Note that the coefficient of the x1 term has been entered as a 0 element.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 213
Step 3: Find the roots of the polynomial using the MATLAB roots command. The
roots command in MATLAB is a powerful algorithmic tool that provides all of
the roots of a polynomial equation. It has the following syntax:
roots(coefficient_array)
where coefficient_array is the array containing the polynomial coefficients (as
defined in Step 2). To find the roots of our polynomial, issue the following com-
mand at the MATLAB prompt:
>> r = roots(p)
r =
–4.0000 + 2.8284i
–4.0000 – 2.8284i
3.0000
All three roots of our polynomial are displayed and stored in the column array r.
Note that two of the roots are imaginary.
Step 4: Check your answers, using the MATLAB polyval command. It is always
good practice to provide a check of our results. In a root finding problem, we
should be able to evaluate our equation at each of the roots, and the result should
compute to zero. Since we have our equation defined as an array of polynomial
coefficients, we can use the MATLAB function polyval to evaluate our equation
at any value of the independent variable. The syntax of the function is as follows:
polyval(coefficient_array, value)
where coefficient_array is the array containing the polynomial coefficients and
value is the numerical value at which we would like to evaluate our polynomial.
For example, with the coefficient array p as defined in Step 2, the command:
z=polyval(p,2.5)
would evaluate Equation 6.28 with a value of x = 2.5, and store the result in the
variable z, resulting in the value z = 9.75.
Since we have already found the roots of our polynomial, and stored them in the
variable r, we can readily evaluate our polynomial at each of these roots and
check that the value of the polynomial equation is zero. Issue the following com-
mand at the prompt:
ch06_mus80164.qxd 8/27/08 2:51 PM Page 214
>> polyval(p,r)
ans =
1.0e–012 *
–0.1990 – 0.0426i
–0.1990 + 0.0426i
0
Note that polynomial equations can certainly be solved using the method
described in Section 6.3; however, each root would need to be found separately,
and finding the imaginary roots would be difficult. The method described in this
section is the preferred technique for polynomial equations.
Goal Seek employs an algorithmic method similar to that used in the MATLAB
fzero command. We will need to define the equation that we are trying to solve,
and also an initial guess of the solution. Goal Seek will find one root of the equa-
tion, in the neighborhood of the initial guess. We will demonstrate Goal Seek by
revisiting Example 6.1.
EXAMPLE 6.3 Find a value for x that makes the following expression true:
■ Solution
Begin a new Excel worksheet. Enter the text shown in Figure 6.13 in cells A1
and A2.
worked with this function, we will use the same initial guess used in the
earlier MATLAB solution (x = 0.5). Enter the guess value of 0.5 in cell
B1. In cell B2, enter the equation described in Equation 6.30, refer-
encing cell B1 as the x value, as shown in Figure 6.14. Hit the Enter key
to accept the equation. Figure 6.14
Click in cell B2 to select it. Select the Data tab from the Ribbon. Under the
What-If Analysis pull-down menu, select Goal Seek, as shown in Figure 6.15.
Figure 6.15
Figure 6.18
This defines the value in cell B1 as the independent variable in our equation.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 216
Goal Seek can now be used to search for a root of the equation defined in cell B2
by starting with the value in cell B1 and modifying it until the target value is
reached. To perform this task, click OK in the Goal Seek dialog box. The Goal
Seek tool will execute, and will terminate when the goal state is reached, as
shown in Figure 6.19:
Figure 6.19
Examining the spreadsheet shows that the value in cell B2 has indeed been driven
to approximately zero; the value of the root, x = 0.593, now appears in cell B1.
To find other roots of this equation, we would need to enter a different value for
the initial guess in cell B1, and rerun the Goal Seek tool.
Problems
6.1 Write a MATLAB function file for each equation and find a root of each
equation within the range shown, using MATLAB’s fzero command:
a. f(x) = 4x3 – 3x2 – 30 = 0, 0≤x≤5
b. f(x) = 3e2x – 10 = 0, 0≤x≤1
c. f(x) = 5(10x) – 10x2 = 0, –1≤x≤1
6.2 Repeat Problem 6.1, using Excel Goal Seek.
6.3 Solve the beam problem described in Section 6.1 using:
a. The method described for polynomial equations using MATLAB.
b. The method described for general nonlinear equations using
MATLAB.
c. The method described for general nonlinear equations using Excel.
Comment on the results and the applicability of each method.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 217
6.6 Rework Problem 6.5, using the Excel Goal Seek tool.
6.7 In an Excel spreadsheet, apply the Bisection Method, as described in Sec-
tion 6.2, to find a root of the following equation:
y = 5x2 – 12x + 3
within the range 0 ≤ x ≤ 1. Continue to bisect the interval until the root is
found to within 0.001. Repeat for the range 1 ≤ x ≤ 3 to find the other
root. Check your answers by hand, using the quadratic formula (Equation
6.16).
6.8 Repeat Problem 6.7 with Newton’s Method within an Excel spreadsheet.
Note that the derivative of the function is as follows:
y′ = 10x – 12
Consider the test case where L1 = 6 in, L2 = 4 in, L3 = 7 in, and L4 = 5.2
in. For this case:
a. Using MATLAB, find the input angle θ2 required to produce an out-
put angle of θ4 = 80°.
b. Check your answer to part a using Excel.
c. Check your answer to parts a and b by drawing the mechanism to
scale, either using a CAD program or by hand.
Figure P6.9
6.14 Consider the hoist described in Problem 5.16, where a 500-N weight is
being lifted by a rope wound around the cylinder, with an unknown fric-
tion coefficient, μ. An engineer has measured the tension T2 required to
support the 500-N load to be 950 N at a contact angle of θ = 85°. Deter-
mine the friction coefficient μ by:
a. Putting the equation for rope tension in standard form.
b. Plotting the equation using MATLAB.
c. Using the MATLAB fzero command to find the appropriate solution
for contact angle θ.
d. Checking your answer by re-solving it using the Excel Goal Seek
tool.
6.15 We learned in Chapter 2 that ball bearings are hardened through a process
of heating and then rapid cooling, or “quenching,” by submersion in an
oil or water. The temperature of the ball as a function of time, T(t) in the
bath may be estimated by Equation 2.3, repeated here:
T(t) = (Ti – T∞)e–t/τ + T ∞
where t is the time in seconds in the bath; Ti is the initial ball temperature;
T∞ is the oil temperature; and τ is the time constant in seconds that
depends upon the material of the ball, the geometry of the ball, and oil
properties. Assume that the initial ball temperature = 800°C, the oil tem-
perature = 40°C, and the time constant = 50 seconds. Using any method
you prefer, find the time at which the temperature of the ball bearing
equals 600°C, 300°C, and 50°C.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 221
C H A P T E R 7
Matrix Mathematics
Introduction
A matrix is a one- or two-dimensional array of numerical or algbraic elements
that represent some mathematical quantity. The ability to define, manipulate,
and perform mathematical operations on matrices is an important skill in solv-
ing engineering problems. In engineering, matrix mathematics is often used to
solve problems in control systems, structural analysis, thermal analysis, and
fluid dynamics. Examples of using matrices to solve these types of problems are
presented in Chapter 8.
221
ch07_mus80164.qxd 8/27/08 2:51 PM Page 222
Each row and column of a matrix is assigned an index number. The first row of
matrix A is referred to as “row 1” and the second row is referred to as “row 2.”
Similarly, the first and second column are referred to as “column 1” and “column
2,” respectively. Each number in the matrix is called an
element. Elements are referred to based on the column and
row in which they reside in the matrix. Elements are often
referred to using the format “aij” where “i” is the row num-
ber of the element and “j” is the column number of the ele-
ment. Using this format, we can display a matrix in a
general format, as shown in Figure 7.2. Figure 7.2
You have probably noticed that matrix A has two rows and two columns, whereas
matrix B has three rows and two columns. The number of rows and number of
columns is called the dimension of the matrix. Matrix A is referred to as a 2 × 2
(pronounced two by two) matrix and matrix B is referred to as a 3 × 2 matrix
(number of rows × number of columns). Matrix A is also called a square matrix
because the number of rows and the number of columns are equal. Understand-
ing the dimension of a matrix is important because the results of many matrix
operations depend upon the dimension of the matrices involved.
matrix C is given by the number of rows of the first matrix and the
number of columns of the second matrix. Figure 7.3 illustrates the
dimension requirements and product matrix dimension when multi-
plying a matrix of dimension (m × n) by a matrix of dimension (n × p).
Figure 7.3
Matrix multiplication is completed by multiplying each element in the
first row of the first matrix by the corresponding element of the first
column of the second matrix and then summing these products to result in the first
element of the resultant, c11. This is repeated for the first row and second column
to determine c12, and so on, until each row has been multiplied by each column.
This is most easily understood by looking at an example, as illustrated by Equa-
tions 7.2a–7.2e, showing the general solution for multiplying a 2 × 3 matrix by a
3 × 2 matrix, resulting in a 2 × 2 matrix:
⎡b b ⎤
⎡ a11 a12 a13 ⎤ ⎢ 11 12 ⎥ ⎡ c11 c12 ⎤
⎢⎣ a21 a22 a23 ⎥⎦ ⎢ 21 b22 ⎥ = ⎢⎣c21 c22 ⎥⎦
b (7.2a)
⎣ b31 b32 ⎦
where:
c11 = a11b11 + a12b21 + a13b31 (7.2b)
(first row by first column, resulting in index 11)
Figure 7.5
Label this matrix A by typing in “A=” into cell A3. Next, add vertical brackets
to visually indicate that this is a matrix. Use the Bold Line tool in the Draw Bor-
ders portion of the Borders drop-down tool located in the Font group on the
Ribbon, as illustrated in Figure 7.7. Upon selecting the tool, draw the vertical
lines by dragging the tool vertically, as shown in Figure 7.8. Press the Esc key
to turn off the Borders tool. Note that adding the vertical brackets is for appear-
ance only and is not required to designate a matrix in Excel.
Figure 7.6
Next, type in the matrix illustrated in Figure 7.9 into cells G2:I4 and align the
cells to the center. Add the straight brackets around the matrix and then label
this matrix B by typing “B=” into cell F3.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 227
Let’s add matrix A to matrix B to create a sum matrix C. Select cells L2:N4, click
in the Formula Window, and type “=B2:D4+G2:I4”. Note that it is far easier to
select the cells that represent matrices A and B than it is to type in the cell num-
bers. To indicate to Excel that this is a matrix oper-
ation, you must press Ctrl+Shift+Enter. Excel will
now treat the formula as a matrix and complete the
operation, filling in the sum into cells L2:N4. Excel
denotes an array or matrix operation in a formula by
automatically inserting curly brackets at the begin- Figure 7.10
ning and end of the formula, as shown in Figure 7.10.
Complete the spreadsheet by typing “A+B=” into cell K3. Add straight brack-
ets around the sum matrix and then align all cells to the center. Your spread-
sheet should look similar to Figure 7.11. Note that you can now type in any 3 ×
3 matrices for A and B and Excel will calculate the resulting matrix of the addi-
tion operation in cells L2:N4.
Figure 7.11
we see our inner dimensions agree so matrix multiplication is possible and our
outer dimensions are 3 × 2, which gives us the dimension of the product matrix.
Next, let’s transpose this new matrix. Again, we must identify the dimension of
the product matrix of the operation C = (AB)T. Matrix AB is a 3 × 2, so our prod-
uct matrix will be a 2 × 3. Select cells G6:I7 and then select the Formula Win-
dow. Type “=TRANSPOSE(B6:C8)” and then press Ctrl+Shift+Enter to
complete the operation.
Type “kB=” into cell F11 and then properly format the new matrix. Your com-
pleted spreadsheet should look similar to Figure 7.15.
Figure 7.15
ch07_mus80164.qxd 8/27/08 2:51 PM Page 229
Figure 7.17
Remember, only square matrices can be inverted. Like the other matrix opera-
tions, we must know the dimension of the resulting matrix. In this case C = A–1
and the resulting matrix will have the same dimension as matrix A. Select cells
B6:D8 and then select the Formula Window. Type “=MINVERSE(B2:D4)”
and then press Ctrl+Shift+Enter to complete the operation.
Label this matrix A–1 by typing “A–1=” in cell A7. Add straight
brackets, align to center, and set the number of decimals to two.
Your inverse matrix should look similar to Figure 7.18.
If we type in a new 3 × 3 matrix into cells B2:D4, its inverse will be Figure 7.18
returned into cells B6:D8. Let’s just change one element in matrix A.
Change element a32 from 3 to 1. Your spread-
sheet should now look like Figure 7.19.
determine that a matrix has an inverse. Use the Undo tool to revert back to the
original matrix A.
Now, let’s check that A–1A = I. Select cells B10:D12 and then select
the Formula Window. Type “=MMULT(B6:D8,B2:D4)” and then
press Ctrl+Shift+Enter to complete the operation. Label the matrix
A–1A and add the straight brackets. Your resultant matrix should
Figure 7.20 look similar to Figure 7.20.
The resultant matrix does not quite look like the identity matrix. There are some
non-zero terms in the off-diagonal elements. However, these values are very
small and result from the numerical error generated as Excel computes the
inverse. These values are certainly outside the precision of our calculation, so we
can ignore them. To clean up the matrix, set the number of decimal places to
two and set the alignment to the center. Your completed spreadsheet should look
similar to Figure 7.21.
Figure 7.21
>> A=[1 0 2; 2 1 2; 0 2 1]
A =
1 0 2
2 1 2
0 2 1
>> B=[1 0 1; 1 1 2; 3 3 1]
B =
1 0 1
1 1 2
3 3 1
>> C=A+B
C =
2 0 3
3 2 4
3 5 2
>> C=A*B
C =
7 6 3
9 7 6
5 5 5
ch07_mus80164.qxd 8/27/08 2:51 PM Page 232
>> C=2*C
C =
2 0 4
4 2 8
0 12 2
>> A=[0 1 1; 2 3 1; 1 2 1]
A =
0 1 1
2 3 1
1 2 1
>> B=[1 2 2; 1 0 1]
B =
1 2 2
1 0 1
>> C=A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.
Remember, the number of columns of the first matrix and the number of rows of
the second matrix must match. MATLAB has returned an error, letting us know
that our matrices cannot be multiplied because the inner dimensions do not agree.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 233
Sometimes matrices may get incorrectly entered and it is quicker to transpose the
matrix than retype the matrix, especially if the matrix is large. Other times, matri-
ces generated in one calculation need to be transposed for use in a subsequent cal-
culation. Let’s transpose matrix B and complete the operation C = AB, as shown
here:
>> B=B’
B =
1 1
2 0
2 1
>> C=A*B
C =
4 1
10 3
7 2
>> A=[1 2 1; 0 2 0; 2 1 1]
A =
1 2 1
0 2 0
2 1 1
>> B=[1 2 3; 4 5 6; 7 8 9]
B =
1 2 3
4 5 6
7 8 9
ch07_mus80164.qxd 8/27/08 2:51 PM Page 234
>> C=inv(A)
C =
-1.0000 0.5000 1.0000
0 0.5000 0
2.0000 -1.5000 -1.0000
>> D=inv(B)
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND =
1.541976e-018.
D =
1.0e+016 *
-0.4504 0.9007 -0.4504
0.9007 -1.8014 0.9007
-0.4504 0.9007 -0.4504
Recall from previous Excel exercises, the determinant also gives us an indication
if a matrix is invertible. If the determinant is zero (the definition of a singular
matrix), the matrix has no inverse and conversely, if the determinant is non-zero,
the matrix has an inverse.
Calculate the determinant of matrix A and B to verify this rule, as shown here:
>> detA=det(A)
detA =
-2
>> detB=det(B)
detB =
0
ch07_mus80164.qxd 8/27/08 2:51 PM Page 235
Matrix operations do not have to be done one step at a time, but can be combined
into a single line of code. Let’s define two new matrices A and B and then com-
plete the operation C = (ABT)–1 using one single line of code, as shown here:
>> A=[1 2 1; 0 1 2]
A =
1 2 1
0 1 2
>> B=[1 2 0; 1 1 2]
B =
1 2 0
1 1 2
>> C=inv(A*B’)
C =
0.3333 -0.3333
-0.1333 0.3333
Problems
Use matrices A and B below for Problems 7.1–7.8.
⎡1 3 0⎤ ⎡0 1 1⎤
A = ⎢2 1 2⎥ B = ⎢ 1 3 3⎥
⎢ ⎥ ⎢ ⎥
⎣ 4 1 3⎦ ⎣ 2 0 3⎦
⎡ 12 −6 27 ⎤
D = ⎢ 5 18 −2 ⎥
⎢ ⎥
⎣ −4 2 −9 ⎦
7.9 Use Excel to calculate the determinant and inverse of matrix D above.
7.10 Use MATLAB to calculate the determinant and inverse of matrix D
above.
⎡1 1 0 ⎤
G = ⎢0 1 2 ⎥ H = [1 3 4 ]
⎢ ⎥
⎣ 2 2 3⎦
7.11 Use Excel to show that (GT)T = G for each of the matrices G and H
above.
7.12 Use Excel to calculate the resultant matrix C = GHT for matrices G and
H above.
7.13 Use MATLAB to show that (GT)T = G for each of the matrices G and H
above.
7.14 Use MATLAB to calculate the resultant matrix C = GHT for matrices G
and H above.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 237
⎡1 3 3 6 4⎤ ⎡ 20 ⎤
⎢2 1 4 2 4⎥ ⎢6⎥
⎢ ⎥ ⎢ ⎥
M = ⎢6 4 1 3 8⎥ N = ⎢14 ⎥
⎢0 4 6 2 1⎥ ⎢9⎥
⎢4 1 ⎥⎦ ⎢5⎥
⎣ 2 0 4 ⎣ ⎦
7.15 Use Excel to calculate the resultant matrix X = M–1N for matrices M and
N above.
7.16 Use MATLAB to calculate the resultant matrix X = M–1N for matrices M
and N above.
⎡1 3 3 6 4⎤
⎢2 1 4 2 4⎥
⎢ ⎥
P = ⎢6 4 1 3 8⎥ Q = [10 12 14 7 3]
⎢0 4 6 2 1⎥
⎢4 1 ⎥⎦
⎣ 2 0 4
7.17 Use Excel to calculate the resultant matrix X = P–1QT for matrices P and
Q above.
7.18 Use MATLAB to calculate the resultant matrix X = P–1QT for matrices P
and Q above.
⎡1 0 0 4 1 ⎤ ⎡ 11 ⎤
⎢ 2 −2 0 1 −1⎥ ⎢ −7 ⎥
⎢ ⎥ ⎢ ⎥
R = ⎢ 0 4 1 −3 0 ⎥ S=⎢ 3 ⎥
⎢ 1 −1 2 2 1 ⎥ ⎢ −17 ⎥
⎢3 2 5 0 1 ⎥ ⎢ 5 ⎥
⎣ ⎦ ⎣ ⎦
7.19 Use Excel to calculate the resultant matrix Z = R–1S for matrices R and S
above.
7.20 Use MATLAB to calculate the resultant matrix Z = R–1S for matrices R
and S above.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 238
ch08_mus80164.qxd 8/27/08 2:52 PM Page 239
C H A P T E R 8
Solving Simultaneous
Equations
Introduction
In many engineering applications it is necessary to solve several equations simul-
taneously; that is, the solution must fit all of the equations. Sometimes we only
need to solve two or three equations in order to solve an engineering problem,
while in advanced engineering analysis we may need to solve hundreds of thou-
sands of equations. (Good thing we have computers to help out with that!)
239
ch08_mus80164.qxd 8/27/08 2:52 PM Page 240
appear in engineering applications can contain many variables, but to begin, let’s
consider the following two equations:
2x + 3y = 14 (8.1a)
–4x + y = 28 (8.1b)
Recall, to solve a system of equations, there must be the same number of equa-
tions as there are unknowns or variables. For there to be a unique solution (an x
and y) that fits both Equations 8.1a and 8.1b, the equations must be: (1) inde-
pendent, meaning that one equation cannot be a constant multiple of another
equation; and (2) consistent, meaning that the two equations cannot differ only
by the constant term. For example, Equations 8.2a and 8.2b are not independent,
as they are simply a multiple of each other and actually represent the same equa-
tion.
2x + 3y = 14 (8.2a)
4x + 6y = 28 (8.2b)
Equations 8.3a and 8.3b are not consistent, as there is no unique x and y that when
multiplied by 2 and 3, respectively, can add up to both 14 and 28. These two equa-
tions represent two parallel lines and, therefore, there is no intercept or unique
point that represents a solution.
2x + 3y = 14 (8.3a)
2x + 3y = 28 (8.3b)
We will begin by solving a set of linear equations graphically using Excel, then
by using the Goal Seek tool in Excel, and finally through the use of matrix oper-
ations using Excel and MATLAB. Nonlinear simultaneous equations will be
solved using the Solver tool in Excel.
■ Solution
These are equations of lines and in order to graphically determine the solution,
we must first rewrite the equations in slope-intercept form, or y = mx + b. Start
by rearranging both equations with the variable y on the left side of the equal sign.
Equation 8.1a is rearranged, yielding Equation 8.4a and then Equation 8.4b.
Equation 8.1b is rearranged, yielding Equation 8.4c.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 241
3y = –2x + 14 (8.4a)
2 14
y=− x+ (8.4b)
3 3
y = 4x + 28 (8.4c)
Open a new spreadsheet in Excel. Label cells for the x values and then label
cells for the y values, given by Equations 8.4b and 8.4c, as “y_eq1” and
“y_eq2”, respectively. Type in “0” and “10” for the x values. We can insert any
two values for x since both equations form lines and we need just two points to
graph each equation. Format your spreadsheet, as shown in Figure 8.1.
In cell B2, type the formula for the y value of Equation 8.4b as
“=-2/3*A2+14/3” and then copy down to cell B3.
In cell C2, type the formula for the y value of Equation 8.4c as “=4*A2+28”
and then copy down to cell C3. Your spreadsheet should look similar to Figure
8.2.
Now let’s graph the two lines using an XY (scatter) chart by selecting Scatter
with Straight Lines. Add vertical major gridlines and move your chart to a sep-
arate sheet. Your properly formatted chart should look similar to Figure 8.3.
Figure 8.3
ch08_mus80164.qxd 8/27/08 2:52 PM Page 242
Let’s again “zoom in” on the solution. Type the values for x of “-4” and “–6”
into cells A2 and A3, respectively. Your updated chart should look similar to
Figure 8.5 where we can now see the solution of the system of equations is
(–5, 8). This graphical method can be an effective solution technique; however,
in the event that the solution contains non-integers, it can be difficult to obtain a
precise solution and the techniques presented next are more suitable.
EXAMPLE 8.2 Use Excel Goal Seek to solve the equations given in Example 8.1.
■ Solution
Let’s use the spreadsheet from the previous exercise. We need to drive a single
variable to a known value by changing a second variable. In this case, we can take
the difference between the y values of each equation and drive it to zero by chang-
ing x. When the difference between the y values is zero, they must be equal, and
so the solution has been found.
Type “y_eq1 – y_eq2” into cell D1. Next, type the formula “=B2–C2” into cell
D2. Your properly formatted spreadsheet should look similar to Figure 8.6.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 243
Figure 8.6
Figure 8.8
Figure 8.7
Now we will use the Goal Seek tool to obtain the solution. Select
cell D2 and then select the Data tab from the Ribbon followed by Goal
Seek... from the What-If Analysis drop-down menu, as shown in
Figure 8.7.
Next, in the Goal Seek dialog box, set the “Set cell:” to D2, the “To value:” to
0, the “By changing cell:” to A2, and then select OK, as shown in Figure 8.8.
Then select OK to close the Goal Seek Status dialog box.
Use matrix mathematics in Excel to solve the circuit analysis problem described EXAMPLE 8.3
below.
In this exercise we will use Excel to solve a simple system of equations. In the
following exercise we will take advantage of the programming capabilities of
MATLAB to solve a larger system of equations.
Assuming we had a 12-V battery supplying current to a 2-Ω resistor, the current
through the resistor would be 12 V/2 Ω, or 6 amps.
Now let’s look at the slightly more complex circuit shown in Figure 8.10. In this
circuit, the voltage source supplies two parallel resistive networks. The current at
a junction in the network must algebraically sum to zero. In other words, the cur-
rent flowing into a junction must equal the current flowing out of a junction. This
is known as Kirchhoff’s current law, and when applied to this network at the junc-
tion between R1, R2, and R3, yields Equation 8.6:
I1 – I2 – I3 = 0 (8.6)
As we travel around any loop in the resistive network and return to our starting
point, the sum of the voltages across each component must equal zero using the
following convention: The voltage drops across a resistor in the direction of
current flow and the voltage rises across a voltage source or battery in the direc-
tion of the current flow. This is known as Kirchhoff ’s voltage law. The voltage
drop across each resistor can be calculated by applying Ohm’s law. Applying
Kirchhoff’s voltage law and Ohm’s law to the left loop in Figure 8.10 yields
Equation 8.7:
VB – R1I1 – R2I2 = 0 (8.7)
Applying Kirchhoff’s voltage law and Ohm’s law to the right loop in Figure 8.10
yields Equation 8.8:
–R3I3 – R4I3 + R2I2 = 0 (8.8)
Note that the sign convention results in a positive value of the voltage across R2
since we followed the loop in the clockwise direction, or against the direction of
the current, I2.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 245
⎡1 −1 −1 ⎤ ⎡ I1 ⎤ ⎡ 0 ⎤
⎢R R2 0 ⎥ ⎢ I ⎥ = ⎢V ⎥ (8.10)
⎢ 1 ⎥⎢ 2⎥ ⎢ B⎥
⎣0 R2 − ( R3 + R4 ) ⎦ ⎣ I 3 ⎦ ⎣ 0 ⎦
■ Solution
Open Excel and enter and label the values for the resistors, as shown in
Figure 8.11.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 246
Next, create the coefficient matrix A in cells E3:G5. Map the values of each
resistor into the coefficient matrix, as shown in Figure 8.12. This will allow you
to easily change the values of the resistors in your input table.
Your properly formatted coefficient matrix should look similar to Figure 8.13.
Enter, label, and format the constant matrix into cells B7:B9, as shown in Fig-
Figure 8.11 ure 8.14. Note that we are assuming a 12-V battery in our circuit.
Next, calculate the inverse of the coefficient matrix in cells E7:G9 and then
label and format the matrix, as shown in Figure 8.15.
Now, calculate the product of the inverse matrix and the constant matrix
Figure 8.14 in cells B11:B13. Properly format and label the X matrix, as shown in
Figure 8.16.
amps. This is because the current will flow to take the path of least resistance and
so the majority of the current bypasses R2 and flows through the right side of the
circuit.
As you work through the next two exercises, keep in mind that a program is most
useful if it can be easily modified to solve a new problem. Parameters that may
not be variables (in other words, they are defined constants) in the problem of
interest may become variables in a future problem. Defining these parameters at
the beginning of a program and then carrying them symbolically through the pro-
gram makes them easy to change in the future. This approach ensures a great flex-
ibility for future use.
In the following exercises, we will analyze the current flow through electrical
circuits.In Example 8.4, we will solve for the current flow in a resistive network.
In Example 8.5, we will change one of the resistors to a variable resistor and use
a for loop to calculate the current flow over a range of resistances. Finally, we
will create a plot of the output. If you did not complete Exercise 8.3, you should
at least read through the introduction so that you will understand how the simul-
taneous equations in the examples are generated.
Use MATLAB to calculate the current in each leg of the circuit shown in EXAMPLE 8.4
Figure 8.18.
Figure 8.18
ch08_mus80164.qxd 8/27/08 2:52 PM Page 248
■ Solution
Applying Kirchhoff’s and Ohm’s laws, we can formulate Equations 8.15–8.19:
I1 = I2 + I3 (8.15)
I3 = I4 + I5 (8.16)
VB1 – R1I1 – R2I2 = 0 (8.17)
–R3I3 – R4I4 + R2I2 = 0 (8.18)
R4I4 – R5I5 – VB2 = 0 (8.19)
In matrix form, these equations can be written as follows:
⎡1 −1 −1 0 0 ⎤ ⎡ I1 ⎤ ⎡ 0 ⎤
⎢0 0 1 −1 −1 ⎥ ⎢ I 2 ⎥ ⎢ 0 ⎥
⎢ ⎥⎢ ⎥ ⎢ ⎥
⎢ R1 R2 0 0 0 ⎥ ⎢ I 3 ⎥ = ⎢ VB1 ⎥ (8.20)
⎢0 R2 − R3 − R4 0 ⎥ ⎢I4 ⎥ ⎢ 0 ⎥
⎢0 − R5 ⎥⎦ ⎢⎣ I 5 ⎥⎦ ⎢⎣VB 2 ⎥⎦
⎣ 0 0 R4
Now, let’s create a MATLAB script file that solves these simultaneous equations.
We will define the value of the resistors as input variables. Open a new m-file
and enter the following script:
Save the m-file as “resistors” and execute the script. Note that the value of I5 is
–1.042 amps. This is not an error, but indicates that our assumed direction of the
current shown in Figure 8.18 is incorrect. The current is actually flowing in the
reverse direction to that shown in Figure 8.18.
Now, let’s modify our circuit and place a variable resistor in place of R3. Variable EXAMPLE 8.5
resistors are commonly used in electrical circuits to control current flow, such as
a volume control on a radio, or change other characteristics of the circuit. Use
MATLAB to calculate the current in each leg of the circuit shown in Figure 8.18
as the resistor R3 is varied from 0.1 to 100 Ω.
■ Solution
Our variable R3 can change from 0.1 to 100 Ω. Using a for loop will allow us to
increment the value of R3 and calculate the currents for each value of R3. We will
then plot all currents as functions of R3.
12 for i = 1:1000;
13 R3(i)=i/10;
14
15 %Define the coefficient matrix A, Row by Row;
16 A1 = [1 -1 -1 0 0];
17 A2 = [0 0 1 -1 -1];
18 A3 = [R1 R2 0 0 0];
19 A4 = [0 R2 -R3(i) -R4 0];
20 A5 = [0 0 0 R4 -R5];
21 A = [A1;A2;A3;A4;A5];
22
23 %Define the constants matrix C;
24 C = [0; 0; V1; 0; V2];
25
26 %Calculate the currents (X matrix);
27 X = inv(A)*C;
28
29 %Extract the currents from the X matrix;
30 I1(i)=X(1);
31 I2(i)=X(2);
32 I3(i)=X(3);
33 I4(i)=X(4);
34 I5(i)=X(5);
35 end;
36
37 %Make plot of the currents as functions of R3;
38 plot(R3,I1,R3,I2,R3,I3,R3,I4,R3,I5)
Save the m-file as “resistors_var” and execute the script. Notice how the
response of the system does not change significantly with respect to R3 after
about 30 Ω. From an engineering standpoint this may be important, because spec-
ifying a variable resistor with a resistance range of 0.1–30 Ω will allow a much
greater range of control of the currents than a 70–100 Ω variable resistor.
■ Solution
To begin, let’s rewrite the equations with zeros on the right of the equal signs
(similar to solving for roots in Chapter 6) and set each equation equal to dummy
variables y1 and y2:
y1 = 3x13 + 4x2 – 109 = 0 (8.23)
y2 = 2x1 + 7x2 – 55 = 0 (8.24)
Recall that a solution for the equations will be an x1 and x2 that results in both
equations equaling zero.
Open an Excel spreadsheet and type the labels x1 and x2 , and y1 and y2 into
cells A1:A2 and A4:A5, respectively. Then type in a guess of 2 and 3 for x1
and x2 and the formulas for equations y1 and y2 , checking you work as
shown in Figure 8.19.
The values of x1 and x2 above are guesses. For the equations to be satisfied, the
values of both equations y1 and y2 must be equal to zero per Equations 8.23
and 8.24. The equations may also be satisfied if the sum of y1 and y2 is zero Figure 8.19
(0 + 0 = 0). However, there are cases where the sum of y1 and y2 is zero, but y1
and y2 are not zero (such as –2 + 2 = 0). The equations are also satisfied if the
sum of y1 squared and y2 squared is equal to zero. The reason for squaring the
values is to ensure that the summed values are positive—the only way to get a
sum of zero is to have both y1 and y2 equal to zero.
Next, square each y1 and y2 value and then calculate the sum, checking your
work as shown in Figure 8.20.
and select the Excel Options button located at the bottom of the menu, as shown
in Figure 8.22.
Next, select Manage: Excel Add-Ins from the drop-down box located at the bot-
tom of the dialog box, and then select Go . . . , as shown in Figure 8.24.
Figure 8.22
Keep in mind that there may be more than one solution. Solver converges on a
solution based upon the initial guesses. To find other solutions you must change
your initial guess (although this example has only one solution). Often, an esti-
mate of the solution can be obtained graphically or by bracketing the solution by
applying some knowledge regarding an upper or lower limit. More engineering
applications using Solver, including using constraints, are demonstrated in
Chapter 10.
Figure 8.26
Problems
8.1 Use Excel to find the graphical solution to the following equations:
a. 3x + 2y = 11 b. 2x – 5y = 0
5x – 4y = 33 3x + 4y = 2
8.2 Use Goal Seek to find the solutions to the equations listed in Problem 8.1.
8.3 Use Excel to find the graphical solutions to the following equations:
sinx + 2y = 4
3x2 + 3y = 6
8.4 Use Solver to find the solutions to the equations listed in Problem 8.3.
8.5 The equations below are intersecting circles. Use Solver to find the two
solutions to these nonlinear simultaneous equations:
(x1 – 2)2 + (x2 – 2)2 = 16
(x1 – 5)2 + (x2 –6)2 = 2
Hint: Sketch the two circles on graph paper to establish your trial guesses
for the solution.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 254
8.6 A test projectile is fired down range at an initial velocity of 1467 ft/s
(1000 mph) and at a launch angle of 45° from horizontal. A second pro-
jectile is located 26,400 ft (5 miles) down range from and at the same ele-
vation as the first projectile. The second projectile is fired at a time Δt
after the first projectile is launched. The second projectile is fired down
range at an initial velocity of 2200 ft/s (1500 mph) and at a launch angle
of 60° from horizontal. The launch geometry is shown in Figure P8.6.
Both projectiles follow the equations of motion described in Chapter 1 by
Equations 1.1 and 1.2 and repeated here:
1 2
h ( t ) = vt sin − gt
2
x ( t ) = vt cos
where h(t) is the altitude in ft, x(t) is the down range distance in ft, ν is the
initial velocity in ft/s, θ is the launch angle, g is the gravitational accelera-
tion (32.2 ft/s2), and t is the time after launch in seconds.
The launch time of the second projectile must be calculated so that the
second projectile intercepts the first projectile. Use Solver to determine
the launch time, Δt, of the second projectile, the intercept time measured
from the launch of the first projectile, and the intercept altitude and inter-
cept down range distance as measured from the first projectile’s launch
point. Plot the trajectories (altitude versus down range distance) of both
projectiles on a single graph.
Figure P8.6
ch08_mus80164.qxd 8/27/08 2:52 PM Page 255
Figure P8.7
Figure P8.8
8.9 Use Excel to find the solution to the following system of linear equations:
3x – 2y + 4z – 10 = 0
x+z=2
x + 5y – 4z + 4 = 0
8.10 Use Excel to find the solution to the following system of linear equations:
3x1 + x2 + 4x3 – x4 – 23 = 0
3x1 + x3 + x4 – 2 = 0
–2x2 + x3 + x4 = 0
x1 + 5x2 – 2x4 + 4 = 0
8.11 Apply Kirchhoff’s laws to the resistive circuit shown in Figure P8.11 to
generate two sets of simultaneous linear equations. Show that the set of
equations generated from applying Kirchhoff’s Voltage law to the left and
right loops and the set of equations generated from applying Kirchhoff’s
Voltage law to the left and outer loops yields the same solution for the
value of the currents I1, I2, and I3.
a. To generate the first set of equations, write three equations correspon-
ding to:
1. current law at a junction,
2. voltage law around the left loop, and
3. voltage law around the right loop.
b. To generate the second set of equations, write three equations corre-
sponding to:
1. current law at a junction,
2. voltage law around the left loop, and
3. voltage law around the outer loop.
c. Use Excel to solve both sets of equations.
Figure P8.11
ch08_mus80164.qxd 8/27/08 2:52 PM Page 257
Figure P8.12
Figure P8.15
8.16 Suppose that the breaking load of the cables used to support the weight in
Problem 8.15 is 1500 lb. The factor of safety is defined as 1500 lb divided
by the maximum tensile force in any of the three cables. Write a MAT-
LAB program to vary d from 0 to 15 feet, in 0.1-foot intervals. For each
value of d, calculate the factor of safety. Plot the factor of safety versus d.
What value of d produces the highest factor of safety?
ch09_mus80164.qxd 8/27/08 2:52 PM Page 259
C H A P T E R 9
Numerical Integration
Introduction
Engineering and technology students need to study a considerable amount of
math during their academic careers, and practicing engineers use math every day.
Calculus is the basis of most engineering theories. This chapter will show you
how to perform integration numerically. Whether you are currently studying cal-
culus or not, you can follow the steps of the tutorials in this chapter, and develop
a skill that will help you better understand calculus and solve some real-world
problems.
259
ch09_mus80164.qxd 8/27/08 2:52 PM Page 260
have to know a boundary (or initial) condition, such as the initial velocity. Math-
ematically, we write these relations as follows:
dv
a= (9.1)
dt
and
∫
v = a dt (9.2)
∫ ( 3x 2
− 6 x )dx = x 3 − 3 x 2 + C (9.4)
Note that the two operations are closely related. However, when we found the
integral, we did not get exactly the same expression that we differentiated.
Instead of the 5 of the original expression, we got C, a constant of integration, in
Equation 9.4. This is because when we took the derivative, any constant in the
expression would have resulted in the same answer. Therefore, there are an infi-
nite number of polynomials with the same derivative. When we find an integral,
we are finding a function to fit a derivative. The answer is not unique; we must
know a boundary condition or initial condition to find the complete answer.
Further insight into differentiation and integration can be obtained from examin-
ing graphs of the functions. In Figure 9.1, the function y = x3 – 3x2 + 5 is plotted
against x, for values of x of –2 to 4.
Figure 9.1
Figure 9.2
Note that if the constant 5 in the function is changed to a different value, the effect
on the graph is simply to translate the curve higher or lower. However, the slope
at any point is unchanged; hence the derivative of the function remains the same
regardless of the value of the constant.
Of particular interest are the points where the slope is equal to zero. By setting
the derivative 3x2 – 6x equal to zero, we find that the slope is equal to zero at x =
0 and at x = 2. These values are important because they represent local maxima
or minima of the function y. Graphically, we see that there is a local maximum at
ch09_mus80164.qxd 8/27/08 2:52 PM Page 262
Analytically, we can evaluate this definite integral by substituting the upper limit
(4) into the indefinite solution shown in Equation 9.4, and subtracting the value
obtained by substitution of the lower limit (0):
( ) ( )
4
∫ 0
( 3 x 2 − 6 x )dx = ( x 3 − 3 x 2 ) 4
0 = 4 3 − 3( 4 )2 − ( 0 )3 − 3( 0 )2 = 16 − 0 = 16 (9.6)
Of course, the units of this answer depend on the units of x and y. Note that the
constant C from Equation 9.4 was omitted; the same C applies at both the upper
and lower limits and therefore is cancelled in a definite integral by the subtrac-
tion operation.
■ Solution
The trapezoid rule simply states that the area under a curve can be approximated
by the summation of a series of trapezoids. Consider the curve shown in
Figure 9.4. At two values of the independent variable x, x1, and x2, the values of
the function y are found and are labeled y1 and y2, respectively. A straight line
drawn from point (x1, y1) to point (x2, y2) forms a trapezoid with a base of x2 – x1
and an average height of (y1 + y2)/2, as shown in Figure 9.5. Therefore, the area
of the trapezoid is as shown in Figure 9.5.
disappeared for most applications. Using the trapezoid rule with a larger number
of intervals almost always produces adequate accuracy without significantly
increasing processing time.
Open a new Excel spreadsheet. Label cells A1 and B1 “x” and “y”, respectively.
In cells A2:A6, enter values 0, 1, 2, 3, and 4, as shown in Figure 9.7. For our
first approximation, we will use four intervals of x, each one unit wide.
In cell C3, enter the formula for the area of the first trapezoidal area, as shown
in Figure 9.10. Note that we have not entered a formula in cell C2. For four areas,
there are five points defining the area boundaries. Therefore, the first area is
between the first and second points.
Copy the formula to cells C4:C6. In cell C8, enter the formula
“=SUM(C3:C6)” to sum the areas of the trapezoids, as shown in Figure 9.11.
For this approximation, using four increments of x, we find a value of 18 for the
integral (as noted earlier, the units of this value depend on the units of x and y).
ch09_mus80164.qxd 8/27/08 2:52 PM Page 265
In the previous section, we found the value analytically to be 16, so our error is
12.5%. Figure 9.12 shows the trapezoids that we used in this approximation. We
can see that the areas of the trapezoids were greater than the actual areas for the
positive areas from x = 2 to x = 4, while the areas of the trapezoids were less than
the actual negative areas from x = 0 to x = 2.
Note that the formulas in columns B and C are still valid; they only need
to be copied to the cells below.
Repeat for cell C6, so that the area formula is copied to the appropri-
ate cells. Add a cell with a formula that sums the values of column C, as shown
in Figure 9.15.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 266
Figure 9.16
EXAMPLE 9.2 Use the trapezoid rule and MATLAB to approximate the value of the integral of
Equation 9.4, which is repeated here:
4
∫ 0
( 3 x 2 − 6 x )dx (9.4)
■ Solution
While the formulas for numerical integration are easy to enter into Excel, a dis-
advantage is that to use more intervals, we have to change our spreadsheet sig-
nificantly. In this example, we knew the exact answer, so we were able to
determine that eight intervals was sufficient to obtain an answer to a reasonable
accuracy. Of course, when we need to find an integral numerically, it is because
we do not know the answer. How do we know if our answer is accurate? One way
is to increase the number of intervals until our solution converges to the answer.
An advantage of using MATLAB is that we can set up a script file that allows us
to change the number of intervals quickly. For this example, we will create a
MATLAB function that determines the integral, with the number of intervals as
the argument of the function.
the second point’s coordinates, x(2) and y(2) are defined, and the area of the trape-
zoid defined by the first two points is calculated. This value is added to SUM, the
value of the integral, which was initialized before beginning the loop. These cal-
culations are then repeated until the last interval, defined by the next-to-last and
last points, is evaluated.
Save the function as “intexample”. From the command prompt, evaluate the
function for four intervals:
> intexample(4)
ans =
18
Note that the result, integral = 18, is the same as the Excel solution with the same
number of intervals. Before evaluating the function with more intervals, it is help-
ful to examine the flowchart and the MATLAB code thoroughly. In particular, note
ch09_mus80164.qxd 8/27/08 2:52 PM Page 268
the variables k and i. The value of k, the input variable, is set to 4 in this example.
The variable i defines the index number of the points that must be evaluated. For
this example, there are five points, as shown in Figure 9.18. For i = 1, the value of
x is the lower limit of the integral (0) and the value of y is calculated from the func-
tion for x = 0 (in this case, y(1) is also equal to zero). After defining and storing
the initial values of x and y, the code enters a for loop. The loop defines a set of
calculations for each interval, so the loop is passed through k times. However,
since the first point to be evaluated in the loop is the one for which i = 2, the loop
counter begins at 2 and runs until the value reaches k + 1, or 5, in this case. For
every pass through the loop, the area of the trapezoid is calculated and added to
the total (SUM), which was set to zero before entering the loop.
Figure 9.18
From the command prompt, evaluate the function for several values of the
number of intervals:
>> intexample(1)
ans =
48
>> intexample(2)
ans =
24
>> intexample(8)
ans =
16.5000
ch09_mus80164.qxd 8/27/08 2:52 PM Page 269
>> intexample(12)
ans =
16.2222
>> intexample(20)
ans =
16.0800
>> intexample(100)
ans =
16.0032
>> intexample(1000)
ans =
16.0000
Note that if k = 1, then the area is that of a triangle with a base of 4 units and a
height of 24 units. As we increase the number of intervals, the answer is clearly
converging to a value of 16, which we know is the exact answer.
If you want to evaluate even more intervals, you will need to display more digits
than the default. Enter the format long command, which displays all of the digits
stored by MATLAB, and evaluate the integral with 10,000 and 50,000 intervals:
>> intexample(10000)
ans =
16.000000319990953
>> intexample(50000)
ans =
16.000000012868973
Issue the format short command to return to the display of four digits after the
decimal point.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 270
EXAMPLE 9.3 Use the trapezoid rule to approximate the value of:
∫ 1 − z2 2
z
e dZ (9.7)
−∞ 2
where Z = the number of standard deviations from the mean of a normally dis-
tributed population.
If we use the symbols x̄ for the mean of the population and σ for the standard
deviation, the Z value for any data value x is shown in Equation 9.8:
x−x
Z= (9.8)
■ Solution
Before proceeding, some explanation of this integral is helpful. The integrand,
1 − z2 2
e
2
defines a normal distribution, also known as a bell curve, as shown in Figure
9.19.
Figure 9.19
ch09_mus80164.qxd 8/27/08 2:52 PM Page 271
The normal distribution is very important in statistics and has many engineering
applications, such as reliability and quality control. For example, consider a man-
ufacturing process in which a company makes 2-inch diameter steel tubes. No
manufacturing process is perfect, so the actual diameter of any given tube will be
slightly different from exactly 2 inches. After making and measuring a large num-
ber of tubes (a sample), the mean (average) diameter can be found. Also, the stan-
dard deviation, which is a measure of the variability of the diameter, can be
calculated (most scientific calculators, as well as Excel and MATLAB, have
built-in functions to calculate the standard deviation). If we then assume that the
sample is representative of all of the tubes made (the population), and that the
population fits a normal distribution, then we can use properties of the normal
distribution to make some important calculations. For example, suppose that the
tubes have a mean diameter of 1.998 inches, with a standard deviation of 0.006
inches. Further, let’s assume that the manufacturer guarantees that the diameter
of the tubes will be between 1.990 and 2.010 inches. What percentage of manu-
factured tubes is within this acceptable range of diameters?
To answer this question, we must consider the normal distribution shown in Fig-
ure 9.19. The area under the curve is equal to one (100% of the population), but
the curve extends to infinity in both directions. How do we evaluate an integral
with a limit of –∞? The answer is that we select a reasonable lower limit, so that
our answer is sufficiently accurate. We will assume that we want an answer that
is accurate to six significant digits. We will try different values for the limits (that
is, how many standard deviations below the mean that we need to include) and
for the number of intervals.
Save the function as “normdist” and execute it for different values of limit
and k:
>> normdist(3,100)
ans =
0.997292229481189
>> normdist(3,1000)
ans =
0.997300124163755
>> normdist(6,1000)
ans =
0.999999998025951
>> normdist(6,10000)
ans =
0.999999998026819
>> normdist(6,100)
ans =
0.999999997940018
>> normdist(5,100)
ans =
0.999999414352763
Note that changing the number of standard deviations included in the calculations
has a major impact on the accuracy, while the number of intervals has a much
smaller impact. Using ±6 standard deviations results in answers that are accurate
to 8 significant digits, even for as few as 100 intervals. Therefore, we will choose
a lower limit of –6 (6 standard deviations below the mean) and a number of inter-
vals of 1000, since the increase from 100 to 1000 intervals does not result in a
noticeable increase in computing time. We will now modify the function to cal-
culate the integral up to a given value of Z.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 273
Make the changes as indicated to the function normdist (note that lines 6–14
are unchanged):
Save the changes. Change the display format to short and execute the function
for values of Z = 0 and Z = 1:
>> normdist(0)
ans =
0.5000
>> normdist(1)
ans =
0.8412
The answer of 0.50 obtained for a Z-value of zero is logical, since 50% of all val-
ues will fall below the mean (zero standard deviations from the mean). The inter-
pretation of the answer for Z = 1 is shown graphically in Figure 9.20. The area
below the normal distribution curve up to one standard deviation greater than the
mean is 0.8412. Therefore, 84% of the population falls below this level.
Now that we have created a function to evaluate this integral, let’s return to a
problem posed earlier:
ch09_mus80164.qxd 8/27/08 2:52 PM Page 274
Figure 9.20
EXAMPLE 9.4 If a population of manufactured tubes have a mean diameter of 1.998 inches and
a standard deviation of 0.006 inches, what percentage are within the guaranteed
range of 1.990 to 2.010 inches?
■ Solution
Consider the lower limit first:
1.990 − 1.998
Z= = −1.333 (9.9)
0.006
That is, the lower limit is 1.333 standard deviations below the mean.
>> normdist(-1.333)
ans =
0.0913
The interpretation of this result is that 9.13% of all of the tubes will have diame-
ters below the lower limit.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 275
>> normdist(2)
ans =
0.9772
From this result, 97.72% of all of the tubes will have diameters below the upper
limit, while 2.28% have diameters above the upper limit. Therefore, the percent-
age of tubes within the guaranteed range is as follows:
97.72 – 9.13 = 88.59%
Note that we could also solve this problem in one step by calling the function
twice within a single line:
The slight difference is due to rounding off the intermediate results in the earlier
calculation. This result is shown graphically in Figure 9.21. In most manufactur-
ing environments, this result would be unacceptable, since more than 11% of all
tubes made do not meet the company’s guaranteed specifications. Measures
would be taken to improve the consistency of the manufacturing process, or the
company would need to modify its product specifications.
Figure 9.21
EXAMPLE 9.5 A small robot moves along a straight line. An accelerometer attached to the robot
records the acceleration in the direction of the motion (the x-axis) 10 times per
second. Data from a 4-second movement is shown in Table 9.1. The robot is at
rest (velocity and acceleration equal 0) at time t = 0. Find the maximum velocity,
the velocity at the end of the 4-second interval, and the total distance moved by
the robot.
■ Solution
Open a new Excel spreadsheet. Enter the time values in column A (beginning
with t = 0) and the acceleration in column B, as shown in Figure 9.22. Note:
To wrap text to a second line, as shown in row 1, either select the Wrap Text tool
from the Home group of the Ribbon, or press the Alt+Enter keys to manually
insert a line break in the text.
Examining the acceleration plot, we see that the robot’s speed will be increasing
over the first second of travel. During the next second, the acceleration is approx-
imately zero, so the velocity will be nearly constant. During the third and fourth
seconds of time, there is a period of deceleration, followed by about a half-
second of constant velocity and then a half-second of greater deceleration.
Recall from Equation 9.2, repeated here, that velocity is the integral of accelera-
tion:
∫
v = a dt (9.2)
ch09_mus80164.qxd 8/27/08 2:52 PM Page 278
Therefore, the area under the acceleration curve for each time interval is equal to
the change of velocity from the previous time. Since we are starting from a veloc-
ity of 0 (the initial condition), the final velocity will be the area under the entire
curve.
Copy this formula to the cells below in column C. In column D, enter the initial
velocity, 0, in the row corresponding to t = 0. In the next row, enter a formula
which adds the velocity change to the previous velocity, as shown in Figure 9.25.
Copy this cell down column D.
Figure 9.26
ch09_mus80164.qxd 8/27/08 2:52 PM Page 279
From the graph, we see that the maximum velocity is about 125 cm/s. If you need
a more exact value, you can scroll down the spreadsheet to look for the maxi-
mum, but an easier way is to enter a formula that finds the maximum value of the
entire column (especially if you have hundreds or thousands of rows of data).
Enter a formula to find the maximum value of row D, as shown in Figure 9.27. Figure 9.27
(Reserve columns E and F for position calculations.) To select the entire col-
umn, click on the column heading. The maximum velocity is displayed, as
shown in Figure 9.28.
The change in position x is equal to the integral of the velocity. We can define the Figure 9.28
initial position as x = 0.
In column E, enter a formula to find the integral of the velocity over the first
time increment (the position change), as shown in Figure 9.29. Copy this for-
mula to the cells below. Note that the units will be as follows:
⎛ cm ⎞
(second) ⎜
⎝ second ⎟⎠
= cm
Figure 9.29
In column F, enter the position as the sum of the previous position and the posi-
tion change from column E, beginning with the initial position of zero. Several
rows of the completed worksheet are shown in Figure 9.30.
The final position, 350 cm or 3.50 m, represents total distance traveled by the
robot over the 4-second time period.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 280
Figure 9.30
Figure 9.31
ch09_mus80164.qxd 8/27/08 2:52 PM Page 281
Problems
9.1 With Excel, print out a plot of this function:
y = x2 – 3x + 3
For 0 ≤ x ≤ 4.
By hand, label the values of y at integer values of x. Connect these points
with straight-line segments and calculate the area of each of the four
trapezoidal areas under the line segments. Sum these areas and compare
your result to the exact value of this integral:
4
4 ⎛ x 3 3x 2 ⎞
∫ 0
(x − 3 x + 3)dx = ⎜
2
⎝ 3
−
2
+ 3 x ⎟ = 9.33
⎠0
2
b. ∫ 0
e x dx
4
c. ∫ 0
( x 3 + 3 x 2 − 20 )dx
9.4 Modify the m-file created in Problem 9.3 to evaluate the integral for
upper limits of 4, 6, 8, and 10. Comment on your results.
9.5 Use the function normdist created in Example 9.3 to evaluate this prob-
lem. A population of steel bolts has an average breaking strength of
74,000 lb, with a standard deviation of 2,000 lb. What is the probability
that a given bolt will have a breaking strength of less than 67,000 lb?
9.6 Use the function normdist created in Example 9.3 to evaluate this prob-
lem. Suppose that the average height of an American adult male is 69 in
(5 ft, 9 in), and the standard deviation is 3.0 in. Assuming that heights are
distributed normally, find the percentage of adult males who are:
a. at least 6 ft tall
b. less than 5 ft tall
c. greater than 7 ft tall
d. between 5 ft, 6 in and 6 ft tall
ch09_mus80164.qxd 8/27/08 2:52 PM Page 282
9.7 A model rocket is launched straight up from level ground. The engine of
the rocket burns for about 3 seconds and is completely burned out after
4.5 seconds. Acceleration readings are made every 0.5 seconds, and are
shown in Table P9.7. Positive accelerations are upward. After the engine
burns out, the acceleration will be –g, the acceleration due to gravity, or
–9.8 m/s2. Using Excel, find:
a. the maximum upward velocity
b. the maximum height of the flight
c. the time at which the rocket hits the ground
d. the speed at which the rocket hits the ground
Also, plot the acceleration, velocity, and height of the rocket versus time
on three separate graphs. Note: Make sure to continue your calculations
until the rocket hits the ground (height = 0).
9.8 The robot in Example 9.5 is known to have a mass of 1.5 kg. Using
Excel, determine the work done by the robot’s motor during the first
1.4 seconds of motion as follows:
a. Use Newton’s Law (F = ma), the mass of the robot, and the accelera-
tions of Table 9.1 to determine the force generated by the motor for
each data point during the 1.4-second period.
b. Use the force data and the position data (generated in Example 9.5) to
plot force versus distance travelled during the first 1.4 seconds of
motion.
c. Work W can be defined as follows:
∫
W = Fdx
Figure P9.9
where:
k
= , the natural frequency
m
D = 1 − 2 , the damped natural frequency
Figure P9.11
9.12 Repeat Problem 9.10 with each of the following forcing functions, and a
damping ratio of zero:
a. F = 10 sin(5 t)
b. F = 10 sin(10t)
c. F = 10 sin(15t)
What do you notice about part b, in which the forcing frequency is equal
to the natural frequency of the system? (If you have ever driven a car with
a wheel badly out of balance, you might have noticed this condition of
resonance. At a certain speed, the vibrations will be much more notice-
able than at lesser or greater speeds. At this speed, the frequency of the
rotating tire is nearly equal to the natural frequency of the car.)
ch09_mus80164.qxd 8/27/08 2:52 PM Page 285
9.13 A 400-gallon cylindrical tank is filled with water. When a valve at the
bottom of the tank is opened, the flow rate q (in gallons per minute)
through the valve is:
q(t) = 80e–0.2t
where t is the time in minutes. Knowing that the total amount of water
through the valve at any time is the integral of this function, use MAT-
LAB to determine:
a. the amount of time required to empty half of the water from the tank
b. the amount of water left in the tank after 15 minutes
9.14 The cross section of an aircraft wing is a shape known as an airfoil. Air-
foil design requires a sophisticated knowledge of aerodynamics; however,
there are a large number of standard airfoils that can be used in aerody-
namic design. These standard airfoils are generally defined by x-y coordi-
nates, non-dimensionalized such that the tip of the airfoil is at the point
(0,0) and the tail of the airfoil is at the point (1,0).
Locate and download the coordinate points that define the Selig 1223 air-
foil. A good database for this is the UIUC Airfoil Coordinate Database
(available at http://www.ae.uiuc.edu/m-selig/ads/coord_database.html).
While the coordinates are non-dimensional, and can be scaled for any unit
system, assume that in this case the units of the coordinates are meters.
a. Using Excel, plot the airfoil coordinates to see the shape of the airfoil
(be sure to scale the plot such that the scales on the x- and
y-axes are identical, so the airfoil shape will appear correct).
b. Using Excel, perform numerical integration to determine the cross-
sectional area of the airfoil.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 286
ch10_mus80164.qxd 8/27/08 2:52 PM Page 287
C H A P T E R 10
Optimization
Introduction
One of the primary functions of engineers is the design of new devices, processes,
and systems. Engineering design can be defined as:
“the process of applying scientific and mathematical principles for the purpose of
defining a device, process or system that meets a given set of performance specifi-
cations and is optimal in some respect.”
This idea that the engineer is aiming for an optimal solution is important; the
engineer is seeking not only a solution to the design problem, but is seeking a
solution that is the best solution by some objective measure. The criterion that an
engineer uses to determine which solution to a design problem is “best” may vary
from problem to problem, and even from engineer to engineer. In different cases,
the “best” solution may be the one that is least expensive, or most reliable, or
lightest in weight, or smallest in size; it may be some other criterion, or even a
combination of many of these criteria. In the performance of their design activi-
ties engineers will be seeking solutions that maximize or minimize a specific
attribute; thus, mathematics of optimization are important tools for the design
engineer.
After examining the design task, the engineer makes some preliminary decisions
about the design solution:
■ The engineer will use a cylindrical bar; the circular cross section will be
equally stiff in all directions, and will eliminate the need to mount the
beam in a specific orientation.
■ In order to reduce weight, the bar will be hollow.
■ The bar will be made of steel, because it is strong, inexpensive, and readily
available.
After making these preliminary design decisions, the problem is reduced to the
selection of the inner and outer diameters of the cross section of the tube, as
shown in Figure 10.2.
where δ is the deflection of the tip of the beam (in inches), W is the weight of the
applied load (500 lb), l is the length of the beam (120 in), E is the modulus of
elasticity of the material (30,000,000 lb per square inch for steel), D is the outer
diameter of the cross section (in inches), and d is the inner diameter of the cross
section (in inches). Since the design problem states that a 1-in deflection is
acceptable, we can substitute this value to yield Equation 10.2:
64W l 3
≤ 1 in (10.2)
3E ( D 4 − d 4 )
Examining this equation shows us that we have one equation, but two unknowns
(D and d). This is called an underconstrained problem, which possibly has an
infinite number of mathematical solutions. In this case, we can think of this as
giving us some “free choice” in our solution; we could arbitrarily assign a value
to one of the unknown variables, and use Equation 10.2 to find the remaining
variable. For example, if we arbitrarily assigned d = 1 in, we could use Equation
10.2 to yield:
64 (500 lb)(120 in )3
D4 ≥ + d4 (10.3)
3(30 , 000 , 000 psi)(1 in)
or D ≥ 3.74 in. Given this mathematical information, the engineer would consult
a steel supplier and select an available standard size round steel bar with an out-
side dimension greater than 3.74 in (perhaps 3 – 3/4 in, or 3 – 7/8 in, to be safe).
This would certainly be an acceptable solution to the design problem.
In our example, perhaps the engineer determines that the best solution is the one
that uses the least steel possible. Therefore, the engineer writes the equation for
the volume of material in a hollow round bar:
l 2
V= (D − d 2 ) (10.4)
4
This is the criterion on which we will judge the quality of our design solution,
and we will select the solution that makes this value as small as possible (or min-
imizes it). In the terminology of optimization, we call this our objective function.
deflection of the tip of the beam must be less than 1 in, so Equation 10.2 must be
satisfied. We also have some other limits, such as:
■ The value of D and d must be positive non-zero values, since they are
physical dimensions.
■ In terms of manufacturing, it would be difficult to produce a hollow round
tube with a wall thickness that was very thin. Therefore, we will limit the
wall thickness of our tube to be at least 0.125 in.
These four restrictions on the values that our variables can take are called con-
straints in the terminology of optimization. In optimization, we write these equa-
tions in a standard form as equalities or inequalities, where all of the variables
appear on the left-hand side of the equation. Putting our objective function and
constraints into the standard language of optimization:
Minimize
l 2
V= (D − d 2 )
4
subject to:
64W l 3
≤ 1 in
3E ( D 4 − d 4 )
D−d
≥ 0.125 in
2
D≥0
d ≥0 (10.5)
The best design would be the combination of D and d that satisfies all of the con-
straints and minimizes the objective function.
Step 3 in this procedure requires particular attention. Note that all constraint
equations must be identified and written in equation form for the solution to be
valid; even if a constraint seems obvious or trivial, it must be considered. For
example, in our case study of Section 10.1, we included the constraints D ≥ 0 and
d ≥ 0. While these are obvious to the engineer, they must be considered and writ-
ten as equations for the mathematical optimization problem. If we overlook these
obvious constraints, we may end up with a mathematical solution that includes
negative values for our diameters. Also, be aware that in some problems, there
may be no restrictions at all on design variables. This is rare, however, in practi-
cal engineering problems.
While this classification is not strictly necessary, it will help us choose a solution
technique and help us understand the nature of our eventual solution.
To best understand the nature of the solution, we will consider an example involv-
ing just a single design variable, x, and a nonlinear algebraic objective function
f(x). For the solution of the optimization problem, we need to determine the value
of x that makes f(x) take on the extreme values (maximum or minimum). In the
general case, we can examine the values of f(x) over a wide range of values by
examining a plot of f(x) versus x. A typical example plot is shown in Figure 10.3.
Figure 10.3
ch10_mus80164.qxd 8/27/08 2:52 PM Page 293
While there is no restriction on our variable x, and it could take on any value
between –∞ and ∞, we can gain some insight by examining this plot over the
range shown. Note that in this general case:
■ there are a number of “peaks” and “valleys” in the plot of the function
■ at each “peak” and “valley,” the slope of the plot goes instantaneously to
zero.
This is shown in Figure 10.4.
Figure 10.4
In the solution of such an optimization problem, the solution method uses iden-
tification of the point or points where the slope of the plot becomes zero to iden-
tify these maximum and minimum points. A full description of how this is done
requires a course in differential calculus; for the purpose of our discussion, it is
sufficient to understand that principles of calculus can be used to find the points
where the slope of the plot is zero, and the corresponding values of x at these
points can be identified.
Take, for example, the case where we are attempting to minimize an objective
function that is a parabola:
Minimize y = 2x2 + 8x – 6 (10.11)
Using principles of calculus, we can write the equation for the slope of this curve
by taking the derivative of the function; in this case, the equation for slope is
given by Equation 10.12:
dy
slope = = 4x + 8 (10.12)
dx
This slope equation will be equal to zero at a single point: x = –2. This indicates
that the function y will take a minimum or maximum value at this point.
ch10_mus80164.qxd 8/27/08 2:52 PM Page 294
If we examine the plot of this function, as shown in Figure 10.5, we can confirm
that the function does indeed reach a minimum value at the point x = –2. We
should also note that the function has no unique maximum value; y can reach infi-
nite values as x goes to ±∞.
Note that in our case, once we determined that the function had a zero slope at
the point x = –2, we used a plot to determine whether the value was a maximum
Figure 10.5
There are indeed points of zero slope at the predicted values; the point x = 1⁄3
corresponds to a “peak” in the curve, and the point x = 1 corresponds to a
“valley.” However, as we examine the behavior of the function over the whole
range of values, we can see that the y has no distinct maximum value; it keeps
getting larger as x proceeds to ∞; similarly, the function has no unique minimum,
and keeps getting smaller as x proceeds to –∞.
ch10_mus80164.qxd 8/27/08 2:52 PM Page 295
Figure 10.7
ch10_mus80164.qxd 8/27/08 2:52 PM Page 296
The plot indicates that non-unique global maxima occur at x = π/2, 5π/2, 9π/2, ...,
while non-unique global minima occur at x = 3π/2, 7π/2, 11π/2,....
Looking at the three examples offered in this section, the following general con-
clusions can be drawn about unconstrained nonlinear optimization:
■ The points where the slope of the function are zero indicate points of
extreme (minimum and/or maximum) values.
■ The points indicated by a zero slope may be local, rather than global,
extremes. Caution should be taken in interpreting results, and results
should be checked to assure that global extrema have been located.
■ Global extrema may not be unique, especially if the objective function is
periodic.
While the examples in this section were limited to objective functions of a single
value, the results can be generalized to multivariable objective functions. While
the calculus involved in determination of slope becomes more difficult to use
with manual methods, the concepts we have examined in this section will help us
to determine and use the results of the algorithmic solutions we will employ.
Consider the linear optimization problem with two design variables and three
constraint equations, described as follows:
Maximize
y = 3x1 – 2x2
subject to:
x1 ≥ 3
x2 ≥ 1
2x1 + x2 ≤ 10 (10.18)
Recall that the constraint equations place restrictions on the allowable values
for our design variables x1 and x2. We can graphically view the set of allowable
values for our design variables by plotting the constraint equations, as shown in
Figure 10.8.
ch10_mus80164.qxd 8/27/08 2:52 PM Page 297
While the shape of the feasible region and the slope of the contour line would be
different for a different set of objective functions and constraints, the properties
of the solution seen in our example problem can be generalized. Because of the
nature of the linear objective function and linear constraint equations, the
extrema (maximum and minimum points) will always occur at a “corner point”
of the feasible region. Looking ahead to more complex problems, with numerous
design variables and constraint equations, an algorithmic solution that checks all
of the corner points of the feasible region could be developed. A standard algo-
ch10_mus80164.qxd 8/27/08 2:52 PM Page 298
rithm that is often employed to solve such problems is called the simplex algo-
rithm.
Maximize
y = 4x1 + 2x2
subject to:
x1 ≥ 3
x2 ≥ 1
2x1 + x2 ≤ 10
(10.19)
Graphically, the feasible
region and objective function
contours are shown in Figure
10.10.
As indicated earlier in this section, not all linear constrained optimization prob-
lems have closed feasible regions; in these cases, we must consider another
option for the solution to the problem. Consider, for example, a modified ver-
sion of our previous example problem, with one of our constraint equations
eliminated:
Maximize
y = 4x1 + 2x2
subject to:
x1 ≥ 3
x2 ≥ 1 (10.20)
The feasible region corresponding to this set of con-
straint equations is shown in Figure 10.11.
Minimize
y = 4x1 + 2x2
subject to:
x1 ≥ 3
x2 ≥ 1 (10.21)
ch10_mus80164.qxd 8/27/08 2:52 PM Page 300
■ Solution
We will begin by creating a MATLAB function to generate our objective
function values. Start MATLAB, open a new m-file, and enter the following
program:
1 function y=objfunc(x);
2 y=3*x^4+x^3*cos(pi*x);
ch10_mus80164.qxd 8/27/08 2:52 PM Page 302
We will now use the fminsearch function to locate the value of x that minimizes
this function. The algorithm requires an initial guess to use as a starting point for
the x value search. Since our objective function contains only one single variable,
we will use a plot to determine a value for our initial guess. In the MATLAB com-
mand window, issue the following command:
Figure 10.13
This plot shows that the function appears to take a minimum value in the range
of x = –0.2. Using this as a guess for our value, issue the following command:
>>xmin=fminsearch(‘objfunc’,-.2)
This instructs MATLAB to search for the variable that minimizes the function we
coded in objfunc.m in the neighborhood of the initial guess x = –0.2, and store the
result in the variable xmin. Executing the command yields the following result:
ch10_mus80164.qxd 8/27/08 2:52 PM Page 303
xmin =
-0.1834
If we would like to determine the value of the objective function at this point,
we can substitute this value of x into the objective function as follows:
>> ymin=objfunc(xmin)
ymin =
-0.0018
The results indicate that the objective function reaches a minimum value of
y = –0.0018 at a value of x = –0.1834.
>>xmin=fminsearch(‘objfunc’,100)
You should obtain a result very similar to our original result, regardless of the
initial guess that you try. This is not always the case, as we will see in the next
example.
■ Solution
We will begin by modifying our MATLAB function to generate our new objec-
tive function values. Open the objfunc file and modify line 2 as follows:
1 function y=objfunc(x);
2 y=3*x^4+x^3*cos(10*pi*x);
ch10_mus80164.qxd 8/27/08 2:52 PM Page 304
We will again generate a plot of the function, to determine the value of the ini-
tial guess:
Figure 10.14
The plot looks distinctly different than the plot shown in Figure 10.13, in that
many “local minima” appear in the plot. To begin, we will again search in the
range of x = –0.2. Execute fminsearch with a starting point of –0.2:
>>xmin=fminsearch(‘objfunc’,-.2)
xmin =
-0.2028
ch10_mus80164.qxd 8/27/08 2:52 PM Page 305
>> ymin=objfunc(xmin)
ymin =
-0.0032
The results indicate that the objective function reaches a minimum value of
y = –0.0032 at a value of x = –0.2028.
Now we will explore the result of using a different initial guess. For example,
execute fminsearch with an initial guess of x = –0.6:
>> xmin=fminsearch(‘objfunc’,-.6)
xmin =
-0.5928
Note that a significantly different result is obtained; looking back at Figure 10.14,
it can be seen that a local minimum exists in the range of x = –0.6. The solution
algorithm in this case has located the local minimum of the function, rather than
the global minimum. Since this is a function of one variable, and can be easily
plotted, we can quickly evaluate our result, and notice that we have obtained a
result that is less than truly “optimal.” For multivariable problems, a graphical
verification is usually not possible.
Determine the values of x1, x2, and x3 that minimize the function:
y = x12 − x1 + x 24 − x 2 + x 34 + x 32 − x 3 (10.24)
■ Solution
We will begin by modifying our MATLAB function to generate our new objec-
tive function values. Open the objfunc file and modify line 2 as follows:
1 function y=objfunc(x);
2 y=x(1)^2-x(1)+x(2)^4-x(2)+x(3)^4+x(3)^2-x(3);
ch10_mus80164.qxd 8/27/08 2:52 PM Page 306
Note that in this version of the function, the variable x is an array containing three
elements. Save the function.
Since this is a multivariable function, there is no good way to plot the function to
determine a reasonable initial guess. We will arbitrarily assign an initial guess; in
this case, we will try x1 = x2 = x3 = 0. Enter the initial guess as an array and exe-
cute the command:
xmin =
0.5000 0.6300 0.3855
>> ymin=objfunc(xmin)
ymin =
-0.9373
The results indicate that the objective function reaches a minimum value of
y = –0.94 at the point x1 = 0.50, x2 = 0.63, and x3 = 0.39.
xmin =
0.5000 0.6299 0.3854
ch10_mus80164.qxd 8/27/08 2:52 PM Page 307
xmin =
0.5000 0.6300 0.3855
It appears that our answer remains unchanged even as we try significantly dif-
ferent initial guesses. We may reasonably conclude at this point that we have
reached a global minimum.
■ Solution
Note that this objective function is identical to that used in Example 10.2. We will
begin by creating a MATLAB function to generate our objective function values.
Open the objfunc file and modify line 2 as follows:
1 function y=objfunc(x);
2 y=3*x^4+x^3*cos(10*pi*x);
The fminbnd function takes three arguments: the objective function name, the
lower bound on the design variable, and the upper bound on the design variable.
Enter the command as follows and execute it:
ch10_mus80164.qxd 8/27/08 2:52 PM Page 308
>> xmin=fminbnd(‘objfunc’,.8,1)
xmin =
0.8910
>> ymin=objfunc(xmin)
ymin =
1.2115
The results indicate that the objective function reaches a minimum value of
y = 1.21 at the point x = 0.89. Consulting the plot of this function in Figure 10.14
confirms that this minimum value is correct in the range specified.
Figure 10.15
If the Solver add-in has not been loaded on your computer, refer to Chapter 8,
section 8.4, for the installation procedure.
■ Solution
This is identical to Example 10.1, which was solved using the MATLAB fmin-
search. Open an Excel spreadsheet, and set up the spreadsheet as shown in
Figure 10.16.
In cell B1, we will enter the initial guess for our optimization. To be consistent
with our previous solution to this problem, we will use an initial guess of 0.2.
Enter the guess value, as shown in Figure 10.17.
Press the Enter key and the objective function will be com-
puted using a value of 0.2 for the design variable. Figure 10.18
The Solver add-in will now be employed. Under the Data tab, click Solver, as
shown in Figure 10.19.
Figure 10.19
Figure 10.21
Click the selection icon next to the “By Changing Cells:” box, as shown in Fig-
ure 10.23.
Click on cell B1 (the cell containing the value of the design variable) to select
it, as shown in Figure 10.24.
Since there are no constraints in this problem, we can proceed with the solution.
To do this, simply click Solve, as shown in Figure 10.25.
To compare our solution with the results obtained from MATLAB, format cells
B1 and B2 to four decimal places. The results are shown in Figure 10.27.
Determine the value of x1, x2, and x3 that minimizes the function:
y = x12 − x1 + x 24 − x 2 + x 34 + x 32 − x 3 (10.27)
■ Solution
Open a new Excel spreadsheet. We will use the same arbitrary initial guesses
for the three design variables that were used when we solved this problem using
MATLAB. Set up the spreadsheet as shown in Figure 10.28.
Press the Enter key, and the objective function will be evaluated using these ini-
tial guesses.
Initiate Solver under the Data tab. Set the target cell to be B6 and set the “Equal
To:” option as Min. Since this is a multivariable optimization problem, we must
select multiple cells in the “By Changing Cells:” box. To do this, click on the
selection icon, as shown in Figure 10.29.
Figure 10.28
Figure 10.29
ch10_mus80164.qxd 8/27/08 2:53 PM Page 312
Click and hold the left mouse button over cell B2 and drag down to cell B4, as
shown in Figure 10.30.
Figure 10.30
Minimize
y = x12 − x1 + x 24 − x 2 + x 34 + x 32 − x 3
subject to:
x1 + 2x2 ≥ 4
x1 – x3 ≤ 0.1 (10.28)
■ Solution
This problem uses the same objective function as
Example 10.6, but we have now introduced two
constraints. We will modify our previous spread-
sheet to include the constraint equations. Modify
the spreadsheet as shown in Figure 10.32, enter-
ing the formula for the left-hand side of the first
constraint equation in cell B8.
Figure 10.32
ch10_mus80164.qxd 8/27/08 2:53 PM Page 313
The Add Constraint dialog box will open. Click the cell containing the first
constraint equation, cell B8, to select it as the Cell Reference, as shown in
Figure 10.35.
Figure 10.35
Figure 10.37
ch10_mus80164.qxd 8/27/08 2:53 PM Page 314
The constraint equation will appear in the Solver Parameters dialog box, as
shown in Figure 10.38.
Click Add and repeat the procedure to add the second constraint equation. It
should appear as shown in Figure 10.39.
The problem is now fully defined. Note that we have left the design variables as
they were when we solved the unconstrained problem. This is arbitrary, but is as
good a point as any at which to start our algorithm. With the problem fully
defined, click Solve to execute the solution algorithm. After Solver executes,
click OK to accept the solution, which is shown in Figure 10.40.
Initiate Solver from the Data tab. The parameters set in the previous solution
will still be set. Simply click Solve to run the algorithm again and click OK to
accept the solution. The results are shown in Figure 10.42.
The same results are obtained. While this is no guarantee that we have reached a
global minimum, it does give us greater confidence in our result.
■ Solution
This problem uses the same constraints as Example 10.7, but we modified the
objective function such that this problem now meets the definition of a linear con-
strained optimization problem. Not only must we modify our spreadsheet, but we
will also slightly modify our solution method to accommodate the linearity of this
optimization problem.
Press the Enter key. Initiate Solver from the Data tab; all parameters
should remain as established in Example 10.7. Recall from Section 10.2
that a specific solution algorithm applies to constrained linear optimization
problem; this solution technique is called the simplex algorithm. This algo-
rithm assures that the solution reached will be at a corner point of the fea-
sible region, which is required for optimality. We need to set one additional Figure 10.43
option to indicate that this is a linear problem, and assure that the appro-
priate solution algorithm will be used. To do this, click the Options but-
ton, as shown in Figure 10.44.
Click OK; the variables will be changed to new values, but the “solution” has
no meaning.
Minimize
y = 3x1 + x2 + 5x3
subject to:
x1 + 2x2 ≥ 4
x1 – x3 ≤ 0.1
x1 ≥ 0
x2 ≥ 0
x3 ≥ 0 (10.30)
■ Solution
This problem is nearly identical to Example 10.8, but constraint equations have
been added to ensure that all of the design variables are non-negative.
To solve this problem, we need to add these additional constraint equations. The
restriction of non-negative design variables is quite common in engineering opti-
mization problems; since our design variables are generally physical dimensions
and parameters (such as size, weight, electrical resistance, strength, etc.), nega-
tive values often do not make physical sense. We could add them one at a time,
using our normal constraint equation procedure; however, since the restriction of
non-negative design variables is so common there is a shortcut method of apply-
ch10_mus80164.qxd 8/27/08 2:53 PM Page 317
ing this constraint to all design variables. Note that by using this
shortcut, we will also be restricting the objective function to non-
negative values; in our example, as well as in many physical
problems, the objective function will be non-negative if all of the
design variables are non-negative.
The Assume Linear Model box should also be checked; with this
Figure 10.47
option selected, the solution algorithm will be restricted to
searching the corner points of the feasible region, and therefore
will be guaranteed to find a globally optimal solution. If this option is not
selected, the algorithm may converge on a locally optimal solution in the
interior of the feasible region.
Click OK to set the options. Click Solve to execute the algorithm. Note
that this time, a solution is reached; the addition of the non-negative con-
straints in our problem has provided us with an appropriately bounded fea-
sible region. The results of the optimization are shown in Figure 10.48.
Figure 10.48
10.6 Tutorial: Engineering Application of Linear
Constrained Optimization
When engineers approach a problem, the goal is not only to generate a solution
to the problem, but to generate the best solution to the problem. As a result, opti-
mization is a focus of many engineering activities. In Section 10.1, we formulated
a typical mechanical/civil engineering design problem as a nonlinear constrained
optimization problem. In this section, we will approach a typical industrial/
manufacturing engineering design problem by formulating it as a linear con-
strained optimization problem, and solving it using Excel.
A chemical company that formulates industrial adhesives has processing/storage EXAMPLE 10.10
plants in four cities:
■ New Orleans, LA
■ Gary, IN
■ Buffalo, NY
ch10_mus80164.qxd 8/27/08 2:53 PM Page 318
■ Portland, OR
The weekly production capacity and production cost for their top-grade adhesive
at each plant is shown in Table 10.1.
Three major customers place regular weekly orders; their locations, standard
orders, and negotiated pricing are shown in Table 10.2.
Midwest Manufacturing, Inc. (MMI) Duluth, MN 26,000 gallons/wk $2.00 per gallon
West Coast Corp. (WCC) Stockton, CA 13,000 gallons/wk $2.75 per gallon
Texas Manufacturing Co. (TMC) Houston, TX 11,000 gallons/wk $3.00 per gallon
The shipping costs between the production plants and the customers have been
estimated, as shown in Table 10.3.
MMI $0.22 per gallon $0.12 per gallon $0.16 per gallon $0.17 per gallon
WCC $0.26 per gallon $0.20 per gallon $0.39 per gallon $0.11 per gallon
TMC $0.12 per gallon $0.18 per gallon $0.21 per gallon $0.20 per gallon
Determine the production plan for each of the four manufacturing plants in order
to maximize the chemical company’s profits.
ch10_mus80164.qxd 8/27/08 2:53 PM Page 319
■ Solution
(10.31)
or:
Maximize
P = 1.07x1 + 1.78x2 + 2.17x3 + 0.90x4 + 1.57x5 + 1.84x6
+ 0.72x7 + 1.24x8 + 1.67x9 + 0.54x10 + 1.35x11 + 1.51x12 (10.32)
ch10_mus80164.qxd 8/27/08 2:53 PM Page 320
Figure 10.49
Note that there are seven constraint equations that must be added, although Fig-
ure 10.50 shows only the first six.
ch10_mus80164.qxd 8/27/08 2:53 PM Page 321
Since this is a linear problem, and since design variables are constrained to be
non-negative, the options must be set as shown in Figure 10.51.
Figure 10.52
The model predicts a $67,350 weekly profit for this product line based on the
optimal production schedule. Note that no production is scheduled for the Port-
land plant, and there is 4,000 gallons of unused capacity at the Buffalo plant.
Problems
10.1 Minimize the function y = 3x4 – 2x2 + 4x + 1 using the fminsearch func-
tion. Plot the function to verify your result.
10.2 Solve Problem 10.1 using Excel.
10.3 Minimize the multivariable function y = 3x4 – 2x2 + 4x + 1 + z2 – z using
the fminsearch function.
10.4 Solve Problem 10.3 using Excel.
10.5 Minimize the function y = x2 cos(2πx) in the range 0 ≤ x ≤ 1 using the
fminbnd function. Plot the function to verify your result.
10.6 Solve Problem 10.5 using Excel.
10.7 Solve the beam design problem set in Section 10.1 using Excel.
10.8 An engineer proposes using aluminum for the beam design problem of
Section 10.1, rather than steel. Modify the example problem using the
appropriate value of E for aluminum, and re-solve the problem.
10.9 A team of students has entered a robot competition, in which their robot
must start from a base location, move to and grab objects, and return
them to the base to score points. The point values assigned to the objects
are 100, 50, and 25 points, depending on their distance from the base.
There is a 4-minute time limit for the competition; only objects returned
to the base will be counted in the scoring. The team has practiced
retrieving all 10 objects; times for completing the round trip to the
object and bringing it back to the base, along with the point values of
each, are shown in Table P10.9.
Table P10.9
Object Number Point Value Time to Retrieve, s
1 100 110
2 100 80
3 100 75
4 50 55
5 50 45
6 50 30
7 25 22
8 25 20
9 25 15
10 25 15
ch10_mus80164.qxd 8/27/08 2:53 PM Page 323
Figure P10.13
ch10_mus80164.qxd 8/27/08 2:53 PM Page 325
10.14 In his paper “Do Dogs Know Calculus?”,1 mathematics professor Timo-
thy Pennings made an interesting observation while playing catch with
his Welsh Corgi, Elvis. Standing on the shore of Lake Michigan (point A
in Figure P10.14), Pennings threw a tennis ball into the lake (point B).
Rather than swimming directly toward the ball (Path a) or running along
the beach and swimming the shortest distance to the ball (Path b), Elvis
seemed to be optimizing his path (Path c) so that he minimized the time
required to get to the ball, taking into account that he could run faster
than he could swim.
Figure P10.14
a. Use Excel Solver to determine how far Elvis should run down the
beach (distance d) in order to minimize the time required to get to
the ball if:
■ Elvis can run at 6.40 m/s,
■ Elvis can swim at 0.91 m/s,
■ x = 30 m, and
■ y = 10 m.
Also determine the angle θ that the path makes relative to the shore-
line.
b. Repeat the problem for x = 20 m and y = 15 m.
Notes: In Penning’s analytical solution, he noted that the angle θ is
dependent on the relative speeds only, and is therefore independent
of x and y. He also found that Elvis’s paths did indeed match the
optimal paths quite well.
1Pennings, T. J., “Do Dogs Know Calculus?” The College Mathematics Journal, v. 34, no. 3, May 2003.
ch10_mus80164.qxd 8/27/08 2:53 PM Page 326
ch11_mus80164.qxd 8/29/08 8:54 AM Page 327
CONTENTS
A Connectors, 108 E
Accelerometers, 25 Constrained optimization, using Element, 222
Accuracy, 17–19 Excel, 312–317 Engineering computation,
Active Cell Address, Excel, 23 Constraints, 290 approaches to, 11–13
Algorithmic solutions, 4–11 Contour plot, 297 Engineering design, 287
Analytic solutions, 4–11 Correlation coefficient, 172 Engineering optimization, 288–290
Approximate, 9–11 Cosine, Excel calculation example, Equation
Arrays, 14–16 39 classification, 199–201
multidimensional, 16 Cumulative density function, 275 linear or nonlinear, 199–200
one-dimensional, 16, 86–93 Current Directory Window, problems for, 216–220
two-dimensional, 93–97 MATLAB, 64 roots of, 199–208
Arrows, and flowcharts, 106 Curve-fitting, MATLAB, 177–178 smaller steps for, 161
Assignment operation, MATLAB, D solutions, 201–208
67 theory, 199–208
Assignment operator, MATLAB, 67 Data plotting, 143–194 Exact, 9–11
curve fitting, 177–178 Excel, 4, 21–61
B equations in Excel, 147–159 adding matrices, 226–227
Bar graph, 145–146 equations in MATLAB, 159–176 built-in functions, 38–43
Excel, 185–187 Excel graphs, 180–191 calculating the determinant,
Bell curve, 270 graph producing, 178–179 229–230
Bisection method, 203–208 graph types, 143–146 constrained optimization
Black box, 19 MATLAB plot command, solutions, 312–317
Bounded feasible region, 297 159–166 formatting data, 24–29
Bracketing method, 207–208 problems for, 192–194 formulas, 30–38
XY graphs, 147–178 goal seeker, 214–216, 242–243
C Data representation, 13–19 graphical solution problem, 253
Calculations, Excel example, 38 Data storage, MATLAB, 98–99 graphs, 180–191
Calculus, concepts from, 259–262 Decision point, and flowcharts, 106 HLOOKUP, 50–54
Charts; See Graphs Definite integral, 262 IF statement, 43–49
Closed feasible region, 297 Derivative, 260–262 interface, 21–24
Column array, 87 Design, interactive process, 107 interpolating, 54–56
Column matrices, 17 Design optimization, 289 inverting matrices, 229–230
Column vector, 17 Design review, 107 logical functions, 43–49
Command History Window, Determinant, of matrix, 224–225 lookup tables, 50–54
MATLAB, 64 Diamond, and flowcharts, 106 mathematical operations, 32
Command Window, MATLAB, Differentiation, 259–262 matrices formatting, 226–227
64–74 Dimension, of the matrix, 222 matrix mathematics, 243–247
Comments, and MATLAB Script Discrete values, 9–11 matrix operations, 225–230
lines, 79 Double-precision, 19 multiplying matrices, 227–228
327
ch11_mus80164.qxd 8/29/08 8:54 AM Page 328
328 Index
Index 329
330 Index
Script files, MATLAB, 74–82 Title Window, Excel, 22 Worksheet Tabs, Excel, 24
Significant digits, 18 Transpose, and matrix, 224 Workspace Window, MATLAB, 64
Simplex algorithm, 298 Trapezoid rule, 263
X
Simplifying assumptions, 5 Excel, 263–266
Simpson's rule, 263–264 MATLAB, 266–270 XY graph, 143–145, 147–178
Sine, Excel calculation example, 39 value approximation, 270–274 curve fitting, 177–178
Single-precision, 19 Trendline, 144, 171 equations in Excel, 147–159
Smooth curve, 144 exponential, 174–175 equations in MATLAB, 159–176
Solver
U Z
nonlinear simultaneous equations,
250–253 Unconstrained optimization, using Zoom Slider, Excel, 24
problems for, 254 Excel, 308–311
and unconstrained optimization, Unconstrained problem, 289
308–312
V
Spreadsheet, Excel creation
example, 54–56 Variables, 13–14
Spreadsheet tools, 11–13 dependent, 13–14
Square matrix, 222 independent, 13–14
Standard deviation, 271 Vector quantity, 17
Status Bar, Excel, 24 Vectors, 16–17
Sum matrix, 222 View Toolbar, 24
VLOOKUP, and Excel, 50–54
T
W
Tangent, Excel calculation example,
39 While loop, 114–117
Theory curve, 144 Workbook Window, Excel, 23