Вы находитесь на странице: 1из 337

ch00_mus80164.

qxd 9/2/08 3:42 PM Page i

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

ENGINEERING COMPUTATIONS: AN INTRODUCTION USING MATLAB® AND EXCEL®

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.

This book is printed on acid-free paper.

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

Global Publisher: Raghothaman Srinivasan


Sponsoring Editor: Debra B. Hash
Director of Development: Kristine Tibbetts
Developmental Editor: Lora Neyens
Senior Marketing Manager: Curt Reynolds
Project Coordinator: Melissa M. Leick
Senior Production Supervisor: Laura Fuller
Associate Design Coordinator: Brenda A. Rolwes
Cover Designer: Studio Montage, St. Louis, Missouri
(USE) Cover Image: William E. Howard
Compositor: Fleck’s Communications Inc
Typeface: 10/12 Times Roman
Printer: R. R. Donnelley Crawfordsville, IN

Library of Congress Cataloging-in-Publication Data

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

Preface v 3.3 Tutorial: Using MATLAB Script Files 74


3.4 Tutorial: Using MATLAB Function
Files 82
PART 1 3.5 Tutorial: Computing With One-
Dimensional Arrays 86
CHAPTER 1 3.6 Tutorial: Computing With Two-
Computing Tools 3 Dimensional Arrays 93
3.7 Tutorial: Saving a MATLAB Session 98
Introduction 3
1.1 Analytic and Algorithmic Solutions 4
1.2 Approaches to Engineering CHAPTER 4
Computation 11 MATLAB Programming 105
1.3 Data Representation 13 Introduction 105
4.1 Flowcharts 105
CHAPTER 2 4.2 Tutorial: Loop Commands 108
Excel Fundamentals 21 4.3 Tutorial: Logical Branching
Statements 117
Introduction 21
4.4 Tutorial: Combining Loops and Logic 127
2.1 The Excel Interface 21
4.5 Tutorial: Formatting MATLAB Output 132
2.2 Tutorial: Entering and Formatting
Data with Excel 24
2.3 Tutorial: Entering and Formatting CHAPTER 5
Formulas with Excel 30 Plotting Data 143
2.4 Tutorial: Using Built-in Functions 38 Introduction 143
2.5 Tutorial: Performing Logical Tests 5.1 Types of Graphs 143
Using the IF Statement 43
5.2 XY Graphs 147
2.6 Tutorial: Using Lookup Tables 50
5.3 Guidelines for Producing Good
2.7 Tutorial: Interpolating with Excel 54 Graphs 178
5.4 Tutorial: Creating Other Types of Graphs
CHAPTER 3 with Excel 180
MATLAB Fundamentals 63
Introduction 63
3.1 The MATLAB Interface 63
3.2 Tutorial: Using the Command Window
for Interactive Computation 64
ch00_mus80164.qxd 9/2/08 3:42 PM Page iv

iv Contents

PA RT 2 8.3 Tutorial: Solutions to Simultaneous Linear


Equations Using MATLAB 247
CHAPTER 6 8.4 Tutorial: Solving Nonlinear Simultaneous
Finding the Roots of Equations 197 Equations Using Excel 250

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.

MATLAB is a registered trademark of TheMathWorks, Inc.


Excel is a registered trademark of The Microsoft Corporation.
ch00_mus80164.qxd 9/2/08 3:42 PM Page vi

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

Chapter 2: Excel Fundamentals

Chapter 3: MATLAB Fundamentals

Chapter 4: MATLAB Programming

Chapter 5: Plotting Data

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

4 CHAPTER 1 Computing Tools

This text is devoted to an introduction to the application of computational tools


to the solution of engineering problems. These are the types of tools used for
mathematical analysis and data processing across a wide variety of engineering
disciplines. While no individual software product can truly be considered a “stan-
dard” for all engineers, two widely available and widely used software packages
are introduced in this text: MATLAB® and Excel®. Besides being two of the most
popular computational packages for engineers, they also provide the opportunity
to demonstrate two very different approaches to engineering computation: pro-
gramming tools and spreadsheet tools. While these two platforms offer very dif-
ferent ways to approach the solution of engineering problems, there are some
similarities between them, particularly in the way data is represented, stored, and
handled. These similarities are important to understand, in that they offer a com-
mon language for these, and other, computational tools.

In this chapter, you will:


■ learn the difference between an analytic and an algorithmic solution,
■ learn the essentials of algorithm development and pseudocode,
■ learn the basic difference between programming tools and spreadsheet
tools,
■ learn the basic terminology of data storage and handling, and
■ learn the difference between accuracy and precision, and the implications
of both in engineering computation.

1.1 Analytic and Algorithmic Solutions


The computational tools introduced in this text allow us to automate the mathe-
matical analysis required to solve an engineering problem. In order to understand
both the advantages and limitations of the application of computational tools to
engineering problems, we must first understand the essential difference between
the analytic solution and the algorithmic solution to an engineering problem.

Consider the classic projectile motion problem addressed in introductory physics


classes. A ball will be fired from a toy cannon, with an initial speed of 10.0 meters
per second at an angle of 35.0°, as shown in Figure 1.1. An engineer has been
asked to predict the peak height that the cannonball will reach, the location at
which the cannonball will hit the ground, and the total flight time of the projectile.

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

CHAPTER 1 Computing Tools 5

1.1.1 The Mathematical Model


The first step in the solution of this problem is the
development of the mathematical model that the
engineer will use to predict the behavior of the sys-
tem. In this case, it requires the application of the
principles of the physics of mechanics. The engi-
neer creates a sketch of the system, as shown in
Figure 1.2.
Figure 1.2
In developing the mathematical equations that will
be used to predict the behavior of the system, the
engineer must make some decisions as to what to include in the model. In doing
so, the engineer balances the accuracy of the model (the ability of the equations
to properly predict the behavior of the system) and the simplicity of the model.
In this case, the engineer makes the following decisions:
■ The ground will be considered flat and level.
■ The launch point will be considered to be at ground level.
■ Wind resistance will not be considered in the equations.
These decisions, called simplifying assumptions, require considerable engineer-
ing judgment. The engineer must decide that the complexity introduced by
including these effects into the equations will not lead to any significant increase
in the accuracy of the equations. In this case, with these assumptions made, prin-
ciples of physics can be used to write the following equations for height and hor-
izontal distance as functions of time:
1 2
h ( t ) = vt sin ␪ − gt (1.1)
2
x ( t ) = vt cos␪ (1.2)
where h is the height of the cannon ball, x is the horizontal distance travelled, ν
is the initial speed of the cannonball, θ is the launch angle, g is gravitational
acceleration, and t is the time after launch (in seconds). With this model in place,
the engineer must now select a solution technique to solve the equations. We will
now contrast the analytic solution to the algorithmic solution of this problem.

1.1.2 The Analytic Solution


An analytic solution is an exact solution, based on the application of the mathe-
matical principles of algebra, calculus, etc. In the model we have developed, an
analytic solution is possible. In order to find the peak height the ball will reach, the
engineer uses principles of calculus to take the first derivative of Equation 1.1:
dh ( t )
= v sin ␪ − gt (1.3)
dt
ch01_mus80164.qxd 8/27/08 2:49 PM Page 6

6 CHAPTER 1 Computing Tools

When this derivative is equal to zero, the height is at an extreme (maximum or


minimum) value. Setting the derivative equal to zero and solving for t yields:

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

h ( t = 0.585s) = ⎛⎜ 10.0 ⎟⎞ ( 0.585s)sin(35.0°) − ⎛⎜ 9.81 2 ⎞⎟ ( 0.585s)2


m 1 m
(1.6)
⎝ s ⎠ 2⎝ s ⎠

or the peak height is determined to be hmax = 1.68 meters.

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:

⎛ 10.0 m ⎞ t sin(35.0°) − 1 ⎛ 9.81 m ⎞ t 2 = 0


⎜ ⎟ ⎜ ⎟ (1.7)
⎝ s ⎠ 2⎝ s2 ⎠

The engineer uses algebra to factor out t, leading to two solutions:


t = 0 and
⎛ 10.0 m ⎞ sin(35.0°)
⎜ ⎟
t=⎝
s ⎠
⎛ 4.91 m ⎞
⎜ ⎟
⎝ s2 ⎠
= 1.17 s (1.8)
The engineer recognizes that t = 0 corresponds to the launch time, and t = 1.17
s corresponds to the time at which the ball hits the ground again. This value can
be substituted into Equation 1.2 to determine the horizontal distance travelled
during 1.17 seconds of flight:
ch01_mus80164.qxd 8/27/08 2:49 PM Page 7

CHAPTER 1 Computing Tools 7

x ( t = 1.17s) = ⎛⎜ 10.0 ⎞⎟ (1.17s) cos(35.0°)


m
(1.9)
⎝ s ⎠

yielding a horizontal distance travelled of 9.58 meters.

The engineer reports the results in Table 1.1, with appropriate units:

Table 1.1 Results of the Analytic Solution

Peak height reached 1.68 meters


Horizontal distance travelled 9.58 meters
Total flight time 1.17 seconds

1.1.3 The Algorithmic Solution


An algorithmic solution is an approximate solution, based on the application of
a computational procedure. In an algorithmic solution, the engineer will define a
series of steps or rules to be followed that will lead to the discovery of the solu-
tion of the problem. The algorithm will generally rely on principles of arithmetic
only to solve the problem; therefore, while the solution is approximate, it also
eliminates the need to apply more complicated mathematics to the problem. An
algorithmic approach will be demonstrated in our sample problem.

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

8 CHAPTER 1 Computing Tools

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:

Table 1.2 Step-by-Step Solution Algorithm for Finding hmax


t tnew h hnew
Loop (sec) (sec) (m) (m) Step 4 Decision
1 0 0.1 0 .52 h < hnew, loop back to Step 2
2 .1 .2 .52 .95 h < hnew, loop back to Step 2
3 .2 .3 .95 1.28 h < hnew, loop back to Step 2
4 .3 .4 1.28 1.51 h < hnew, loop back to Step 2
5 .4 .5 1.51 1.64 h < hnew, loop back to Step 2
6 .5 .6 1.64 1.68 h < hnew, loop back to Step 2
7 .6 .7 1.68 1.61 h > hnew, set hmax = h. End the algorithm.

The algorithm leads to a solution value of hmax = 1.68 meters.

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

CHAPTER 1 Computing Tools 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:

Table 1.4 Results of the Algorithmic Solution

Peak height reached 1.68 meters


Horizontal distance travelled 9.42 meters
Total flight time 1.15 seconds

1.1.4 Comparison of the Analytic and the Algorithmic Solutions


Examining both the process and results of the analytic and algorithmic solutions
can tell us much about the nature of each solution. The most important differen-
tiation between the two solutions is that the analytic solution is exact. As long as
the mathematical techniques of algebra and calculus were properly applied, and
the arithmetic computation was performed correctly, the result is valid to the
appropriate number of significant digits allowed by the given data. The algorith-
mic solution is approximate; the equations are not solved exactly, but are merely
evaluated at specified values of the independent time variable. These specified
values of time, known as discrete values, limit the accuracy of the final solution.
By the nature of the algorithm, the only possible solutions occur at time values
ch01_mus80164.qxd 8/27/08 2:49 PM Page 10

10 CHAPTER 1 Computing Tools

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

While algorithmic solutions are approximate by their nature, we can increase


their accuracy by decreasing the interval between discrete points and simply run-
ning through the algorithm more times. Approaching an algorithmic solution “by
hand” would prove impractical if increased accuracy was required. Within prac-
tical limits, however, it is no more difficult to run through the algorithm tens, hun-
dreds, or even thousands of times. This is because algorithmic solutions lend
themselves readily to implementation with computer tools. The algorithms devel-
oped in this chapter were presented as verbal descriptions of the step-by-step
problem-solving strategy; these verbal descriptions are known as pseudocode. A
computer programming language, such as the MATLAB software introduced in
this text, can be readily used to translate our software-independent pseudocode
into software-specific computer code, providing clear instructions that the com-
puter can follow. While computers can be applied to automate the arithmetic part
of an analytic solution, it is in the implementation of algorithmic solutions where
computational tools are best suited.

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

CHAPTER 1 Computing Tools 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.

1.2 Approaches to Engineering Computation


In this text, we will contrast two distinct approaches to the implementation of
engineering computation: programming tools and spreadsheet tools.

Programming tools allow the translation of pseudocoded algorithms into instruc-


tion sets that can be followed by the computer. These instruction sets are called
computer programs or computer code. There are many programming languages
used by practicing engineers; we will use the MATLAB platform to introduce the
concept of programming tools in this text. As an example, the MATLAB imple-
mentation of the pseudocoded algorithm for finding maximum height is shown
below. The details of developing your own MATLAB code will be covered in
Chapters 3 and 4 of this text.

1 %MATLAB code for finding maximum height


2 % Definition of input variables
3 t=0; %Initial time
4 h=0; %Initial height
5 t_new=0; %New time
6 h_new=0; %New height
7 delta_t=.1; %Time step
8 v=10; %Initial speed
9 theta=35; %Launch angle
10 g=9.81; %Gravity
11 %Check for decreasing height
12 while h_new>=h;
13 h=h_new
14 t=t_new;
15 %Take one time step
16 t_new=t+delta_t;
17 %Calculate height per Eq. 1.1
18 h_new=v*t_new*sind(theta)-0.5*g*t_new^2;
19 end;
20 %Compute and output maximum height
21 h_max=h

Programming tools allow us to specify the logic and decision-making structure


that the computer will follow in the implementation of an algorithm. From the
earliest days of computing, users communicated with the machines through
ch01_mus80164.qxd 8/27/08 2:49 PM Page 12

12 CHAPTER 1 Computing Tools

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.

A spreadsheet tool is a completely different paradigm for computation; a spread-


sheet resembles a large data table. The user of a spreadsheet tool fills some of the
cells of the table with data, and fills other cells with mathematical equations and
logical expressions that use the data cells as their input. This tabular structure pro-
vides an intuitive graphical approach to data manipulation and computation, but
it differs significantly from the step-by-step instruction sets used in programming
approaches. While the graphical approach to computation is appealing, the direct
link with pseudocoded algorithms is sometimes lost with spreadsheet implemen-
tations. Although other spreadsheet products do exist, we will use the Excel prod-
uct from Microsoft Corporation as the spreadsheet platform in this text. As an
example, a spreadsheet used to implement the maximum height algorithm and
generate the data shown in Table 1.1 is shown in Figures 1.3 (with numerical val-
ues shown) and 1.4 (with formulas relating the cells shown).

Figure 1.3

Figure 1.4
ch01_mus80164.qxd 8/27/08 2:49 PM Page 13

CHAPTER 1 Computing Tools 13

As we introduce the various problem-solving approaches in this text, we will high-


light the advantages and disadvantages of these two approaches to engineering
computation. Some problems are best suited to solution by programming, while
others are best suited to spreadsheet solutions. That said, the MATLAB and Excel
tools that we introduce in this text are very advanced and capable computational
tools, and have to some extent adapted the best features of each approach into their
functionality. Excel has implemented a programming interface, where more tradi-
tional computer code can be developed to operate on and fill cells in the spread-
sheet. MATLAB has developed an array editing interface that looks and acts
similar to a spreadsheet. Both have developed preprogrammed utilities for plot-
ting, root finding, optimization, and other common operations that allow the user
access to advanced algorithms for engineering problem solving. The goals of this
text involve both proficiency with the computational tools and the insight into
selection of an appropriate tool for a given engineering application.

1.3 Data Representation


Despite the differences between various computational platforms, there are some
similarities between packages in the way data is represented, stored, and manip-
ulated. In this section, the terminology of data representation will be introduced
and related back to the MATLAB and Excel tools used in this text.

1.3.1 Variables and Functions


A variable is the symbolic representation of a quantity that can take on more than
a single value. Consider the equation:
y = 3x2 + 6 (1.10)
In this equation, x and y are variables, since they can take on many values. We
often refer to variables as independent or dependent. A variable is dependent
when its value depends on the value of other variables. Usually we write equa-
tions so that the dependent variable is on the left side of the equal sign. For exam-
ple, in Equation 1.10, we would assume that y is the dependent variable, since its
value depends on the value of the independent variable x. Of course, we could
rearrange the equation so that x is on the left side:

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

14 CHAPTER 1 Computing Tools

Let’s go back to the example of the cannonball’s trajectory. We wrote an equation


for the height h of the cannonball as:

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

1.3.2 Scalars and Arrays


In the algorithmic solution presented in Section 1.1, we chose the values of the
independent variable t (time) to evaluate, and calculated the value of the height
ch01_mus80164.qxd 8/27/08 2:49 PM Page 15

CHAPTER 1 Computing Tools 15

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:

Table 1.5 Algorithmic Solution to Cannonball Problem


Loop t(sec) tnew (sec) h (m) hnew (m)
1 0 0.1 0 .52
2 .1 .2 .52 .95
3 .2 .3 .95 1.28
4 .3 .4 1.28 1.51
5 .4 .5 1.51 1.64
6 .5 .6 1.64 1.68
7 .6 .7 1.68 1.61

In a spreadsheet solution, the calculations would be performed in the cells of the


spreadsheet, with the results shown in a form similar to that of Table 1.5. In a
spreadsheet, the numerical value in a cell is a scalar—a single value that can be
represented on a numerical scale. However, in a computing language like MAT-
LAB, results of calculations are stored differently. It is possible that we could
have variables named t, tnew, h, and hnew. In each calculation loop, we could write
over the previous value of the variable. In doing so, we would also be treating
each variable as a scalar, with a single value. But what if we wanted to keep the
results for each loop? We may want to plot height versus time. To do so, we need
to have those values stored in memory. It would be difficult to give each value a
unique name (for example, t1, t2, t3,, etc. for time values), and doing so would
require making every calculation sequentially, rather than in a repeating loop.
Instead, we use arrays to store data. An array is a single variable that has multi-
ple values associated with it. In our example, time t would be an array with seven
values. The values within an array are referenced by an index. An index is an inte-
ger that refers to the position of the value within the array. You can think of an
index as being an address. Our variable t has seven addresses, labeled 1–7. Into
each address we place the value of time (as in Table 1.6):

Table 1.6 Structure of Array t


Index 1 2 3 4 5 6 7
Time, seconds 0 0.1 0.2 0.3 0.4 0.5 0.6

We refer to an individual value of the array by including the index number in


parentheses following the array name, or as a subscript to the variable name. For
example, t (5) = 0.4 seconds, or t3 = 0.2 seconds.

It is very important to remember that index numbers must be integers, beginning


with one and progressing by one for subsequent values. Some of the common
errors that are made by beginning programmers include:
ch01_mus80164.qxd 8/27/08 2:49 PM Page 16

16 CHAPTER 1 Computing Tools

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

>> T(10) = 100


T =
0 0 0 0 0 0 0 0 0 100

In all of these cases, the fundamental error is confusion between independent


variables and indices. Remember that indices are simply counting values repre-
senting addresses within an array, and are not variables themselves.

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.

1.3.3 Matrices and Vectors


One- and two-dimensional arrays are often referred to as matrices. In addition to
being an efficient method for storing data, many mathematical operations can be
performed directly with matrices. In fact, the name MATLAB stands for Matrix
Laboratory, and the program was originally created to perform matrix operations.
In Chapters 7 and 8, we will learn some simple matrix mathematics and use
matrix methods to solve a series of simultaneous equations.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 17

CHAPTER 1 Computing Tools 17

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 ⎦

One-dimensional arrays are called vectors in MATLAB. If the values are


arranged in a single row, then the array is called a row vector; if the values are
arranged in a single column, the array is called a column vector. One-dimensional
arrays can also be called column matrices and row matrices.

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.

1.3.4 Accuracy and Precision


The terms accuracy and precision are often used interchangeably, but have dif-
ferent meanings in computing applications. Accuracy refers to the closeness of
the calculated solution to the actual value, and is a function of the model itself.
For example, when finding the height reached by the cannonball, we noticed that
as we increased the number of time steps, our solution approached the “exact”
analytical solution. We also noted that there were several assumptions present in
our model. For example, the effects of wind resistance were neglected. This
assumption also affects the accuracy of the solution.
ch01_mus80164.qxd 8/27/08 2:49 PM Page 18

18 CHAPTER 1 Computing Tools

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:

1214.55 6 significant digits


1214.5513 8 significant digits
0.00012 2 significant digits
10.00012 7 significant digits

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:

6.778 + 3.5 = 10.3


10.0 – 0.0012 = 10.0

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:

(7.553) (5.52) = 41.7


1.0 / 4.5567 = 0.90

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

CHAPTER 1 Computing Tools 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

20 CHAPTER 1 Computing Tools

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.

In this chapter, you will:


■ learn the terminology associated with the Excel spreadsheet environment,
■ learn how to input data and formulas into an Excel spreadsheet,
■ learn how to use formatting to enhance the appearance and functionality of
an Excel spreadsheet,
■ learn how to use the logical IF-ELSE command,
■ learn how to use lookup tables, and
■ learn how to perform linear interpolation using Excel.

2.1 The Excel Interface


The Excel program can be initiated by clicking on the Excel icon, as shown in
Figure 2.1. When the program is initiated, a new workbook, a multiple-page Figure 2.1
spreadsheet, is opened, as shown in Figure 2.2.

21
ch02_mus80164.qxd 8/27/08 2:49 PM Page 22

22 CHAPTER 2 Excel Fundamentals

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

CHAPTER 2 Excel Fundamentals 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

24 CHAPTER 2 Excel Fundamentals

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

2.2 Tutorial: Entering and Formatting Data with Excel


We will now learn how to enter data (text and numerical) into an Excel spread-
sheet. We will also format the data so that it looks more presentable and is easier
to read. In this tutorial you will create a table that lists the flight speed records
and dates for various types of aircraft.1

1Data from www.aerospaceweb.org.


ch02_mus80164.qxd 8/27/08 2:49 PM Page 25

CHAPTER 2 Excel Fundamentals 25

First, enter the table header titles in cells A1


through D1 (also denoted as A1:D1) by clicking
on cell A1 and typing “Aircraft Class.” Repeat
this and type “Record Setter,” “Date,” and
“Speed (mph)” into cells B1:D1. Notice how the
cells are not wide enough to display their entire
contents. One way to fix this is to click on the line
Figure 2.5
between the column labels and drag each column
to an appropriate width, as shown in Figure 2.5.

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

At this point, your table should look similar to Fig-


ure 2.6. It is not very readable and certainly not
presentable with the present formatting. Let’s
dress it up.

First, we can make the columns wider, but we will


use a different technique than presented above.
Place your cursor in the column header area on
the line separating columns A and B, and double- Figure 2.6
click. Notice how Excel automatically changes
the column width to fit the contents of the col-
umn. Repeat this to adjust the widths of columns B:D.

Now we can change the appearance of the table headers.


Select cells A1:D1 by clicking cell A1 and dragging across to
cell D1. Then click the Bold tool in the Font group on the
Ribbon, as shown in Figure 2.7.

Figure 2.7
ch02_mus80164.qxd 8/27/08 2:49 PM Page 26

26 CHAPTER 2 Excel Fundamentals

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.

Figure 2.9 Figure 2.10


ch02_mus80164.qxd 8/27/08 2:49 PM Page 27

CHAPTER 2 Excel Fundamentals 27

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

28 CHAPTER 2 Excel Fundamentals

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.

There is an alternate method to format a table in Excel that is particu-


larly useful for large tables where the data will be sorted and analyzed.
Figure 2.15 Let’s take a look at this method. First, clear the format of your table.
Select cells A1:D8, select the Clear tool, and then select the Clear
Formats tool from the Editing group on the Ribbon, as shown in
Figure 2.16.

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

Figure 2.17 Figure 2.18

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

CHAPTER 2 Excel Fundamentals 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

Our new table contains a drop-down box in each header. Click on


the Date header drop-down box, and select Sort Oldest to Newest, as shown in
Figure 2.22. You can also choose not to display certain data by unchecking the
appropriate box. Notice that if you uncheck 1986, both records established in
1986 are no longer displayed in the table. To redisplay, use the drop-down box
and check 1986 or use the Undo tool.

Save your spreadsheet. Figure 2.22


ch02_mus80164.qxd 8/27/08 2:49 PM Page 30

30 CHAPTER 2 Excel Fundamentals

2.3 Tutorial: Entering and Formatting


Formulas with Excel
In this tutorial we will learn how to perform calculations using Excel by entering
and manipulating formulas while performing an analysis of a bicycle drive train.
Most modern road racing bikes have 20 “speeds” or gear ratio combinations that
can be obtained. Referring to Figure 2.23, there are normally two sprockets or
chainrings on the crank and 10 sprockets or cogs on the cassette. As the rider
rotates the crank using the pedals, a chain transmits the motion from the chain-
ring to the cassette which is directly attached to the rear wheel’s hub such that one
revolution of the cassette is also one revolution of the rear wheel. Using a
mechanical device called a derailleur (not shown), the rider can select any com-
bination of chainrings and cogs. For modern road racing bikes, the chainring is
always larger in diameter than any of the cogs, such that one revolution of the
crank always results in more than one revolution of the rear wheel. A rider will
normally select a combination of gears depending upon the situation, taking into
account factors such as the force required to pedal, the desired pedaling rotational
speed (called cadence), the desired bicycle speed, and elevation change of the
road. As an example, if a rider is riding on level ground and proceeds up an
incline, the pedaling force will increase significantly as additional work is
required to overcome the force of gravity. Assuming the rider is maintaining a
constant pedaling cadence, he or she may shift to a lower gear ratio to reduce the
pedaling force. However, as we will see, the lower gear ratio will also result in a
reduction in bicycle speed.

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

CHAPTER 2 Excel Fundamentals 31

Front cranks commonly come with 52-tooth and 39-tooth


chainrings. The diameter of a sprocket is proportional to the
number of teeth. Since we will be working with ratios, we can
use the number of teeth in our calculations and not worry about
the actual diameters of the sprockets.

Type “Small Chainring Teeth” into cell A1.

Type “Large Chainring Teeth” into cell A2.


Figure 2.24
Type “39” and “52” into cells B1 and B2, respectively.

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.

Type “Gear Number” into cell A5.

Type “1” and “2” into cells A6 and A7, respectively.

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.

Type “Cassette Teeth” into cell B5.

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

32 CHAPTER 2 Excel Fundamentals

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.

Most programming languages, including Excel, use a standard hierarchy for


interpreting the order in which mathematical operations are performed. The gen-
eral rule in which mathematical operations are performed 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 parentheses 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.

Type “Small Ring Gear Ratio” into cell C5.

Table 2.1 Mathematical Operators


Operation Symbol Excel Usage
Addition + =B2+2.2
Subtraction - =D2-C3
Multiplication * =5.0*A6
Division / =C3/D3
Exponentiation ^ =D1^2
ch02_mus80164.qxd 8/27/08 2:49 PM Page 33

CHAPTER 2 Excel Fundamentals 33

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

34 CHAPTER 2 Excel Fundamentals

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.

Notice that the number of digits displayed varies depending on the


result of the calculation. Excel initially displays the results of calcu-
lations using a default number format. This General Number format
will display up to 10 digits plus the decimal. For very large or very
small numbers requiring 12 digits or more, the display will switch to
scientific notation. In most cases, you will want to change the num-
ber format so that all of your calculations are displayed with consis-
tent significant digits. Changing the display does not change the
value of the number in the cell, so it does not affect subsequent cal-
Figure 2.30 culations. For our example, the gear ratio has little meaning or sig-
nificance past the second decimal place; thus, we will
display two decimal places.

Select cells C5:C15 and then click the Decrease Decimal


tool from the Number group located on the Ribbon, as
shown in Figure 2.31, until two decimal places are dis-
played.

Figure 2.31
ch02_mus80164.qxd 8/27/08 2:49 PM Page 35

CHAPTER 2 Excel Fundamentals 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

where 1 ft/304.8 mm is a conversion factor that converts the distance from mm


to feet.

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

36 CHAPTER 2 Excel Fundamentals

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

where 60 min/hr and 1 mile/5280 ft are conversion factors necessary to convert


the speed from ft/min to mph.

We would like to have cadence as an input variable located in row 4. However, it


is also good practice to maintain some spacing between the different functional
areas of your spreadsheet. In this case, the small table in the upper right-hand
corner has our input variables of chainring teeth and wheel diameter and the
larger table has our calculations. We could have just as easily typed in the value
of 700 mm for the wheel diameter into the formulas that appear in columns E and
F; however, if you wanted to analyze a wheel diameter of 650 mm, which is com-
mon for triathlon bicycles, you would have to edit the formulas in cells E6:F15.
By explicitly defining the wheel diameter as a variable in cell B3, this allows you
to easily change the value of the variable to analyze other wheel sizes.

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

CHAPTER 2 Excel Fundamentals 37

row 4 by clicking on the row number on the left-hand side of the


spreadsheet, as shown in Figure 2.34.

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

38 CHAPTER 2 Excel Fundamentals

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.

2.4 Tutorial: Using Built-in Functions


There are many built-in Excel functions that are useful for engineering analyses.
Some of these are standard mathematical functions such as ex and ln(x), trigono-
metric functions such as sine and cosine, statistical functions such as mean and
standard deviation, and logical functions such as IF-ELSE.

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:

FUN_NAME(arg1, arg2, ...)

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.

Type the numbers 0, 1, 2, and 3 into


cells A2:A5, respectively.

Select cell B2 and then select the For-


mulas tab on the Ribbon. Next, select
the Math and Trig icon from the
Function Library group and then
scroll down and click on the EXP
function, as shown in Figure 2.37.

Figure 2.37
ch02_mus80164.qxd 8/27/08 2:49 PM Page 39

CHAPTER 2 Excel Fundamentals 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.

Type “Sine”, “Cosine”, and “Tangent” into cells B1:D1, respectively.

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

40 CHAPTER 2 Excel Fundamentals

In the Series pop-up window, set Series in to Columns, Type to Lin-


ear, Step value to 5, Stop value to 360, and then select OK, as shown
in Figure 2.41.

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.

Notice when you first typed “=s”, a pop-up appeared, show-


ing all of the functions that begin with the letter “S”, as shown
in Figure 2.42. This can be very helpful if you cannot quite
remember the exact function. If you double-click on the func-
tion in the pop-up, it will be automatically typed into the cell.

Also notice that once a function is typed into a cell up to the


opening parentheses, a pop-up appears showing the function
syntax, as shown in Figure 2.43. This can be very helpful
Figure 2.42 when using functions requiring multiple arguments.

There is a function in Excel that will convert an angle in degrees to radians. We


will use this in our cosine formula instead of the pi/180° conversion used previ-
ously.

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

CHAPTER 2 Excel Fundamentals 41

To finish our spreadsheet we will improve the appearance


with good formatting. Align the entire table to center, adjust
the column widths so that the table headers appropriately
display, and set the number display format to four decimal
places.

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

42 CHAPTER 2 Excel Fundamentals

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.

Assuming an initial bearing temperature of 600°C and an oil temperature of


30°C, how long does it take for the ball to cool to a temperature of less than 60°C?

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

Type in the formula “=($B$1-$B$2)*EXP(-D2/$B$3)+$B$2” into cell E2 and


then fill down to cell E12. Properly format the table, as shown in Figure 2.50.

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

Figure 2.49 Figure 2.50


ch02_mus80164.qxd 8/27/08 2:49 PM Page 43

CHAPTER 2 Excel Fundamentals 43

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.

2.5 Tutorial: Performing Logical Tests Using the IF


Statement
In many engineering analyses, we need to check the value of a number or text
string and, based upon that value, proceed down a different path to continue the
calculation. Excel contains several built-in logical functions that can make a
comparison and return a value or label based upon the comparison. One of the
most useful logical functions in Excel is the IF statement. The IF statement has
the following syntax:
IF(logical_test, value_if_true, value_if_false)
where the argument logical_test is any value or expression that can be evaluated
to true or false using the comparison operators of = (equal to), < (less than),
> (greater than), <= (less than or equal to), >= (greater than or equal to), or
ch02_mus80164.qxd 8/27/08 2:49 PM Page 44

44 CHAPTER 2 Excel Fundamentals

<> (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 “5” into cell B1.

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

CHAPTER 2 Excel Fundamentals 45

The specification on the hole diameter in inches is 0.2500 + 0.0010, –0.0005.


This means any hole with a diameter of 0.2495 to 0.2510 inches is acceptable.
Use the IF statement to:
1. Accept if the hole is within specifications
2. Reject High if the hole is too large
3. Reject Low if the hole is too small.

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

Type the following 20 measured diameters into cells A6:A25: “0.2501”,


“0.2496”, “0.2498”, “0.2512”, “0.2502”, “0.2512”, “0.2495”, “0.2499”,
“0.2500”, “0.2493”, “0.2496”, “0.2506”, “0.2502”, “0.2499”, “0.2506”,
“0.2503”, “0.2496”, “0.2494”, “0.2497”, and “0.2508”.

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

Type the formula “=IF((A6-$B$1)>$B$2,”REJECT HIGH”,IF((A6-$B$1)


<$B$3,”REJECT LOW”,”ACCEPT”))” into cell B6. The quotation marks
inside the formula denote a text string and must be included in the formula. Use
the fill handle to copy this formula down into cells B7:B25.

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

46 CHAPTER 2 Excel Fundamentals

Next, we will use an Excel function to count the number of


accepted, rejected high, and rejected low hole diameter meas-
urements. Obviously, with a small data set, this would be easy
to do manually, but imagine how long it would take if there
were thousands of measurements to count. The Excel function
is the COUNTIF function. The COUNTIF function has the
following syntax:
COUNTIF(range, criteria)
where the range is the group of cells containing the data to
count and the criteria is in the form of a number, expression,
or text that defines the cells to be counted.

Make a small table that lists the three inspection criteria—the


number of accepted, rejected high, and rejected low parts—
and the percentage of each of these.

Type “Accepted”, “Rejected High”, and “Rejected Low”


into cells D2:D4, respectively.

Type “Number” and “Percent” into cells E1 and F1, respec-


tively.

Figure 2.52 Type the formula “=COUNTIF(B6:B25,“ACCEPT”)” into


cell E2. The quotation marks inside the formula denote a
text string and must be included in the formula.

To count the number of parts rejected high and low, type


the formulas “=COUNTIF(B6:B25,“REJECT HIGH”)”
and “=COUNTIF(B6:B25,“REJECT LOW”)” into cells E3
and E4, respectively.

Type the formula “=E2/SUM($E$2:$E$4)” into cell F2 and


then copy it down into cells F3:F4. To display this calcula-
tion as a percentage, select cells F2:F4 and then click on the
Figure 2.53 Percent Style tool from the Number group located on the
Ribbon, as shown in Figure 2.53.

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.

Excel allows us to visually enhance the display by automati-


cally changing the cell display format based upon the value of
Figure 2.54 the cell. In this example, we can highlight the rejections based
ch02_mus80164.qxd 8/27/08 2:49 PM Page 47

CHAPTER 2 Excel Fundamentals 47

upon the string placed in cells B6:B25 by using conditional


formatting.

Select cells B6:B25 and then select Conditional Formatting,


Highlighted Cells Rules, and Text that Contains... from the
Styles group located on the Ribbon, as shown in Figure
2.55.

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

Next, apply a second condition by repeating the


conditional formatting steps, typing “High” into
the Format cells that contain the text dialog box,
and then selecting “Light Red Fill with Dark Red
Text”.

Finally, apply a third condition by repeating the


conditional formatting steps and typing “Low” Figure 2.56
into the Format cells that contain the text dialog
box and then selecting with “Custom Format...”.
Next, in the Format Cells dialog box, select the Font Tab and then select a dark
blue color from the Color drop-down menu, as shown in Figure 2.57.

Next, select the Fill tab


and select light blue for
the Background Color, as
shown in Figure 2.58.
Close the Dialog box by
selecting OK.

Figure 2.57 Figure 2.58


ch02_mus80164.qxd 8/27/08 2:49 PM Page 48

48 CHAPTER 2 Excel Fundamentals

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

CHAPTER 2 Excel Fundamentals 49

Table 2.2 Part Inspection Results


Part Number Test 1 Test 2 Test 3
1 Pass Fail Fail
2 Pass Fail Pass
3 Pass Pass Pass
4 Fail Fail Fail
5 Fail Pass Pass

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

The OR function has a similar syntax and returns


a value of TRUE if any of the logical tests are true
and a value of FALSE if none of the logical tests
are true.

Enter and format the values in Table 2.2 into cells


A1:D6, as shown in Figure 2.60.

Now let’s enter the logical test for criterion 1. We Figure 2.60
can embed the AND function into the IF statement.

Type “Criterion 1” into cell E1.

Next, type the formula “=IF(AND(B2=“P”,C2=“P”,D2=“P”),“Accept”,“Reject”)”


into cell E2 and then fill down the formula into cells E3:E6.

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.

Type “Criterion 2” into cell F1.

Next, type the formula “=IF(OR(B2=“P”,C2=“P”,D2=“P”),“Accept”,“Reject”)”


into cell F2 and then fill down the formula into cells F3:F6.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 50

50 CHAPTER 2 Excel Fundamentals

Your well-formatted spreadsheet should look similar to Figure 2.61.

Figure 2.61

2.6 Tutorial: Using Lookup Tables


In many engineering analyses we use tabulated property data. For example, in
calculating the strength of a structure, such as a bridge truss, we need to know the
materials of construction and properties such as tensile strength and elastic mod-
ulus of the material. In fluid flow analyses, the density and viscosity of the fluid
are important. Many textbooks have the required properties in tables so that you
can look up what is needed to perform the calculation depending on the material
of interest. Excel gives us the capability to create tables and then “look up” the
appropriate value from that table to complete a calculation. The Excel functions
used to look up values from a table include the VLOOKUP function and the
HLOOKUP function.

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

CHAPTER 2 Excel Fundamentals 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.

The amount of energy required to change 1 kg of liquid water at a constant pres-


sure completely to vapor is called the enthalpy of vaporization, or hv. The amount
of heat, Q, required to change a given mass, m, of water from liquid to vapor at a
constant pressure is given by Equation 2.4:
Q = mhv (2.4)
where Q is in kJ, m is in kg, and hv is in kJ/kg.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 52

52 CHAPTER 2 Excel Fundamentals

The value of hv is dependent upon temperature and is often tabulated similar to


Table 2.3, which lists vaporization temperature and pressure and the enthalpy of
vaporization at that temperature and pressure.

Table 2.3 Enthalpy of Vaporization of Water


Temperature, °C Pressure, kPa Enthalpy of Vaporization, kJ/kg
0 0.6613 2501
25 3.169 2442
50 12.35 2383
75 38.58 2321
100 101.4 2257
125 232.1 2189
150 475.8 2114
175 892.0 2032
200 1554 1941
225 2548 1837
250 3973 1716
275 5942 1575
300 8581 1405
325 12060 1190
350 16510 893
374 22090 0

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.

Right-click on the tab labeled “Sheet1” at the bot-


tom of the Worksheet window and select “Rename”,
as shown in Figure 2.62. Then type “Table” into the
highlighted tab.

Select the tab labeled Sheet2. This opens a second


worksheet where we can perform our calculations
with the table somewhat hidden in the background.
Remember, some tables could be very large and it is
generally more convenient to perform the analysis
on a clean sheet.

Rename Sheet2 “Calculations”. Figure 2.62


ch02_mus80164.qxd 8/27/08 2:49 PM Page 53

CHAPTER 2 Excel Fundamentals 53

Type “Temperature (°C)” into cell A1. To insert the


degrees symbol, select the Insert tab on the Ribbon and
then select the Symbol tool in the Text group, as shown
in Figure 2.63.

Next, select the degrees symbol from the Symbol dialog


box, as shown in Figure 2.64, and then select Insert.

Type “Mass (kg)”, “Pressure (kPa)”, and “Heat


Required (kJ)” into cells A2:A4, respectively. Figure 2.63

Type “25” and “3” into cells B1 and B2, respectively.

Type the partial formula “=VLOOKUP(B1,” into cell


B3. The next parameter that needs to be inserted into this
formula is table_array or the range of cells that contains
our table. It is easiest to use the point-and-click method
to insert this range. With the formula still active in the
Formula Window and the cursor located in the position
of table_array, as shown in Figure 2.65, select the
worksheet tab labeled “Table” to navigate to the prop-
erty table. Select cells A2:C17 and then finish the for-
mula by typing “,2,TRUE)”. Close the formula by
Figure 2.64
selecting the checkmark in the Formula Window or hit-
ting the Enter key on your keyboard.

Your correctly entered formula should read


“=VLOOKUP(B1,Table!A2:C17,2,TRUE)”. The
parameter “Table!” is the syntax for referencing
cells on a different worksheet within the workbook,
where “Table” is the name of the worksheet. Again, Figure 2.65 Figure 2.66
using the point-and-click method to specify the
data range is much easier than typing in the correct
format.

In cell B4, type the formula “=VLOOKUP(B1,Table!A2:C17,3,TRUE)*B2”


using the point-and-click method described previously. Your competed calcula-
tions should look similar to Figure 2.66.

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

54 CHAPTER 2 Excel Fundamentals

Let’s insert a note or comment to this spreadsheet to alert


or remind a user that the calculation may be using an
approximation.

Right-click on cell B1 and then select Add Comment from


the pop-up menu, as shown in Figure 2.68.

Next, in the pop-up comment box, type “Exact for tabu-


lated temperatures (every 25 C), else rounds down to next
tabulated value.”, as shown in
Figure 2.69. Click outside to
close the comment box. Notice
that a red triangle now appears
in the upper right-hand corner
of cell B1, indicating a com-
Figure 2.68 Figure 2.69 ment. When you place your
cursor on top of cell B1, the
comment is displayed. To edit or delete the comment, right-click on the cell and
select the appropriate choice.

2.7 Tutorial: Interpolating with Excel


A limitation of lookup tables is that for input values other than those tabulated,
the values are rounded to the next lowest tabulated value. More accurate results
can be obtained by interpolating, or estimating the data values between two
known input values. Linear interpolation is the simplest form of interpolation.

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.

Linear interpolation assumes a linear relationship between two sets of data


points. Referring to Figure 2.71, x1 and x2 represent the tabulated independent
variable or year in our example. The tabulated dependent variable is represented
by y1 and y2, or population, in our example. The value x represents a non-
tabulated year between the two tabulated years and the value y represents the pop-
ulation for the non-tabulated year, assuming a linear relationship between the
population and years.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 55

CHAPTER 2 Excel Fundamentals 55

Figure 2.70 Figure 2.71

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:

( 4086 − 3012 ) 1956 − 1950 = 36556


y = 3012 + ( )
(1960 − 1950 )
Next, we will use a logical check to determine the correct set of data on which to
interpolate based upon the year entered in cell A2.

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

56 CHAPTER 2 Excel Fundamentals

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.

Type “=MAX(C7:C16)” into cell B2 and then check your spread-


Figure 2.73
sheet for other years. Your completed spreadsheet should look
similar to Figure 2.73.

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

CHAPTER 2 Excel Fundamentals 57

2.2 Table P2.2a shows some basic activities, durations, and the dependence of
activities required to build a house.

Table P2.2a House-Building Activities


Preceding Duration
Activity Description Activity (weeks)
A Pour Foundation none 1
B Install Wall Framing A 2
C Install Roof B 3
D Install Electrical and Plumbing B 2
E Install Sheetrock C, D 2
F Install Windows and Doors C 1
G Install Flooring E, F 2
H Paint G 1

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

58 CHAPTER 2 Excel Fundamentals

Use Excel to create a Gantt chart of the following activities shown in


Table P2.2b. Make sure you show duration and slack time. What are the
critical path activities?

Table P2.2b Engineering Project Activities


Preceding Duration
Activity Description Activity (days)
A Determine Probe Velocity 1
B Calculate Drag Force A 1
C Determine Motor HP and Speed B 1
D Determine Drum Diameter 1
E Determine Speed Reducer C, D 1
F Design Drum D 2
G Integrate Retrieval System E, F 2
H Determine Control Scheme C 1
I Select Control Components H 2
J Integrate Control Components I 3
K Program PLC H 4
L Test System G, J, K 2
M Complete Documentation L 1

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

CHAPTER 2 Excel Fundamentals 59

2.10 Create a single spreadsheet to perform the following unit conversions,


taking a value in SI units as the input and returning the value converted 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 cells to cite the reference used to determine the
unit conversion values.
2.11 Create a single spreadsheet to perform the following unit conversions,
taking a value in U.S. Customary units as the input and returning the
value converted to SI units:
a. Feet to meters
b. Pounds per square inch (psi) to newtons per square meter (pascals)
c. Horsepower to watts
d. U.S. gallons to cubic meters
Use comments in your cells to cite the reference used to determine the
unit conversion values.
2.12 Consider the analytic solution of the projectile problem described in
Section 1.1.2. Create a spreadsheet that will allow 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. Calculate
the peak height, flight time, and horizontal distanced travelled for a
launch speed of 150 m/s and an angle of 60°.
2.13 A typical thickness for a sheet of paper is 0.004 inches. If you fold a sheet
of paper once, the thickness of the folded paper will double to a value of
0.008 inches. A second fold will result in a folded thickness of 0.016
inches. Create a spreadsheet that shows the number of folds from 0 to 50
and the resulting thickness of each fold. Calculate the resulting thickness
in units of inches, feet, and miles.
2.14 We learned in Example 2.3 that ball bearings 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 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 and
depends upon the material of the ball, the geometry of the ball, and oil
properties. Create a spreadsheet that utilizes Ti, T∞, and τ as input vari-
ables and calculates the ball temperature for times from 0 to 180 seconds
at 1-second intervals. Assume the time constant τ = 50 s.
ch02_mus80164.qxd 8/27/08 2:49 PM Page 60

60 CHAPTER 2 Excel Fundamentals

Assuming an initial bearing temperature of 800°C and an oil temperature


of 40°C, how long does it take for the ball to cool to a temperature of less
than 100°C?
2.15 Numerical grades for 5 students and 7 assignments are shown in
Table P2.15. Create a spreadsheet that determines the average numerical
grade for each of the students and then assigns a letter grade (A, B, C, D,
F) based on a 10-point scale (greater than or equal to 90 equals an A,
greater than or equal to 80 and less than 90 equals a B, etc.).

Table P2.15 Student Grades


Assignment Grade
Student 1 2 3 4 5 6 7
A 95 60 89 90 92 80 87
B 92 100 93 87 90 85 90
C 88 60 76 89 70 40 60
D 90 87 70 89 92 85 85
E 78 90 94 89 98 95 97

2.16 The time constant in Problem 2.14 is given by:


␳ DcP
␶=
6h
where p is the material density of the ball in g/cm3, D is the diameter of
the ball in cm, cp is the specific heat capacity of the material in J/(g°C),
and h is the heat transfer coefficient between the ball and the oil in
W/(cm2°C). Table P2.16 lists the material properties for aluminum, cop-
per, gold, nickel, and steel.

Table P2.16 Thermal Properties of Selected Metals


Aluminum Copper Gold Nickel Steel
Density (g/cm3) 2.77 2.77 19.30 8.90 7.83
Specific Heat
Capacity (J/(g°C)) 0.875 0.875 0.129 0.444 0.434

Assume a convective heat transfer coefficient of 0.3 W/(cm2°C). Create a


spreadsheet that utilizes the material, the ball diameter D, the convective
heat transfer coefficient h, and the temperatures Ti and T∞, as input vari-
ables. Use a lookup table to look up the thermal properties based upon the
material and then calculate the temperature of the ball for times from 0 to
600 seconds in 1-second increments. Assume the initial ball temperature
is 400°C, the oil temperature is 100°C, and the ball diameter is 0.5 cm.
Which material cools the fastest?
ch02_mus80164.qxd 8/27/08 2:49 PM Page 61

CHAPTER 2 Excel Fundamentals 61

2.17 Create a spreadsheet to calculate the weight of a sphere in pounds. Inputs


will be the diameter of the sphere (in inches) and the material. Use a
lookup table to find the specific weight (weight/volume) of the material
chosen from the list in Figure P2.17. Use Figure P2.17 to check your for-
mula for the weight of the sphere.

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.

Table P2.19 Air Pressure as a Function of Altitude


Altitude, feet Air Pressure, psi
0 14.70
1,000 14.16
2,000 13.66
3,000 13.17
4,000 12.69
5,000 12.23
10,000 10.10
20,000 6.76
30,000 4.37
40,000 2.73
50,000 1.69
ch02_mus80164.qxd 8/27/08 2:49 PM Page 62
ch03_mus80164.qxd 8/27/08 2:49 PM Page 63

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

In this chapter, you will:


■ learn the terminology associated with the MATLAB environment,
■ learn how to perform computations using MATLAB in the interactive
mode,
■ learn how to automate computations using MATLAB scripts, and
■ learn the difference between MATLAB scripts and functions, and how to
develop and use function files.

3.1 The MATLAB Interface


The MATLAB software package can be initiated by clicking on the MATLAB
icon, shown in Figure 3.1.
Figure 3.1

63
ch03_mus80164.qxd 8/27/08 2:49 PM Page 64

64 CHAPTER 3 MATLAB Fundamentals

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.

3.2 Tutorial: Using the Command Window for Interac-


tive Computation
We will now introduce the use of the Command Window as an interactive com-
puting interface. In this mode, we can use MATLAB like a scientific calculator.
In this tutorial, we will use this interactive mode to solve some geometric and
trigonometric problems.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 65

CHAPTER 3 MATLAB Fundamentals 65

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

66 CHAPTER 3 MATLAB Fundamentals

The answer is displayed, and we


conclude that the area of our rec-
tangle is 24.75 square inches.
Click on the Workspace tab to
display the Workspace Window,
as shown in Figure 3.5.

Note that the Command Window


is showing the result using a vari-
able named ans. With the Work-
space Window displayed, we can
see that the Workspace has been
updated to include the variable
ans, and shows that the value
stored in the variable is 24.75.
Also note that the Command His-
tory Window has been updated, Figure 3.5
and now displays the command
that we entered in the Command
Window in the list.

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

A variable is an alphanumeric symbol that will be assigned a numerical value


(similar to an algebraic equation). In MATLAB, a variable name must start with
a letter, cannot contain spaces (or certain special characters), is case sensitive, and
cannot duplicate a preexisting MATLAB command name. In order to avoid prob-
lems associated with variable names, we will select very simple names in this
solution.

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

CHAPTER 3 MATLAB Fundamentals 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

68 CHAPTER 3 MATLAB Fundamentals

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

The Workspace is updated accordingly.

In this example, we have introduced two mathematical operators: the multiplica-


tion operator and the assignment operator. Similar to what was demonstrated in
Excel in Chapter 2, there are many other operators available for mathematical
operation in MATLAB; a subset of those used most often is shown in Table 3.1.

Table 3.1 Mathematical Operators


Operation Symbol MATLAB Usage
Addition + >>a=6.3+2.2
Subtraction – >>c=10.2-4.5
Multiplication * >>f=3.4*2.7
Division / >>k=3/7.3
Exponentiation ^ >>p=4.2^2

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

CHAPTER 3 MATLAB Fundamentals 69

variables in a perimeter computation. Enter the following expression in the


Command Window:

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

70 CHAPTER 3 MATLAB Fundamentals

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.

To find the value of x, type in the following expression:

> 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

CHAPTER 3 MATLAB Fundamentals 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:

>> help matlab\elfun

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:

>> help sin

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

72 CHAPTER 3 MATLAB Fundamentals

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:

>> help sind

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)

In either case, the solution is output as:

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:

>> format long


ch03_mus80164.qxd 8/27/08 2:49 PM Page 73

CHAPTER 3 MATLAB Fundamentals 73

Repeating the calculation with the long format yields:

>> y=hyp*cosd(30)
y =
5.196152422706632

Issuing the format short command will return the default format:

>> format short

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

74 CHAPTER 3 MATLAB Fundamentals

Table 3.2 Some Common Elementary Functions


MATLAB Mathematical
Function Usage Interpretation

Natural log log(x) ln(x)


Base 10 log log10(x) log(x)
Exponential exp(x) ex
Absolute Value abs(x) ⏐x⏐
Square Root sqrt(x) x
Rounding round(x)
Sine (radians) sin(x) sin(x)
Sine (degrees) sind(x)
Cosine (radians) cos(x) cos(x)
Cosine (degrees) cosd(x)
Tangent (radians) tan(x) tan(x)
Tangent (degrees) tand(x)
Arcsine (radians) asin(x) sin–1(x)
Arcsine (degrees) asind(x)
Arccosine (radians) acos(x) cos–1(x)
Arccosine (degrees) acosd(x)
Arctangent (radians) atan(x) tan–1(x)
Arctangent (degrees) atand(x)
Arctangent (radians, quadrant-corrected) atan2(y,x)

3.3 Tutorial: Using MATLAB Script Files


While MATLAB is powerful when used as an interactive calculating tool, the true
power of the program becomes evident when we begin to automate our compu-
tations. We will explore the use of script files in this section. Any operation we
can do in the Command Window can be automated with a script file; we will con-
struct the script off-line and then execute it from the Command Window. We can
then run the script file over and over again, allowing us to perform repetitive
computations without retyping each of our commands.

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

CHAPTER 3 MATLAB Fundamentals 75

Locate the drive/directory in which


you would like to store your work and
click the “Make New Folder” button,
as shown in Figure 3.9.

Type in a name for your new folder


and click “OK”. Your new drive/
directory/folder will now display as the
current directory. Any work we perform
during this MATLAB session will be
stored in this directory. If you would
like to make this the default working
directory for all of your MATLAB
activities, you must add this directory to Figure 3.9 Figure 3.10
the MATLAB “path” (the directory tree
associated with the MATLAB environ-
ment). To add the directory to your
path, select “File: Set Path...” from the
main menu, as shown in Figure 3.10.

From the Set Path dialog box, click the


“Add Folder” button, as shown in Fig-
ure 3.11.

Find your new working directory in


the list shown in the Browse For Figure 3.11
Folder dialog box and click “OK”, as
shown in Figure 3.12.

The directory is now added to the MATLAB path. This is important,


because when MATLAB searches for files, it can only find files in
directories that are included in the path. Click the “Save” button in
the Set Path dialog box to save the new path and close the dialog
box. You may wish to add more working directories to better orga-
nize your MATLAB files (for example, you may desire separate
directories for every class in which you use MATLAB). For each
directory you add, be sure to append the directory to the path.

Figure 3.12
ch03_mus80164.qxd 8/27/08 2:49 PM Page 76

76 CHAPTER 3 MATLAB Fundamentals

EXAMPLE 3.4 We want to find the area and perimeter of the three rectangles described in
Table 3.3:

Table 3.3 Rectangle Dimensions for Example 3.4


Base Height
Rectangle 1 6.5 in 2.1 in
Rectangle 2 7.2 in 3.0 in
Rectangle 3 7.5 in 3.3 in

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

The Editor Window will open. Type


the script shown in Figure 3.14 in
the Editor Window, using the Enter
key to skip to the next line.
Figure 3.13
Note that these formulas are
very similar to those used in
Example 3.1 (although dif-
ferent variable names were
chosen, for demonstration
purposes). Save the file by
choosing “File: Save” from
the Editor menu, as shown
in Figure 3.15. Figure 3.14

The save location should


default to the working
directory that you set. Give
the file the name “rect” (it
has the extension .m by
default) and save it, as
Figure 3.15 shown in Figure 3.16.

Figure 3.16
ch03_mus80164.qxd 8/27/08 2:49 PM Page 77

CHAPTER 3 MATLAB Fundamentals 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

78 CHAPTER 3 MATLAB Fundamentals

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

You may repeat this for the third rectangle as an exercise.

■ 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):

1 % Define dimensions of Rectangle 1


2 base1=6.5;
3 height1=2.1;
4 % Define dimensions of Rectangle 2
5 base2=7.2;
6 height2=3;
7 % Define dimensions of Rectangle 3
8 base3=7.5;
9 height3=3.3;
10 %Compute values for Rectangle 1
11 rect_area1=base1*height1
12 rect_perimeter1=2*base1+2*height1
13 %Compute values for Rectangle 2
14 rect_area2=base2*height2
15 rect_perimeter2=2*base2+2*height2
16 %Compute values for Rectangle 3
17 rect_area3=base3*height3
18 rect_perimeter3=2*base3+2*height3
ch03_mus80164.qxd 8/27/08 2:49 PM Page 79

CHAPTER 3 MATLAB Fundamentals 79

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.

In our previous solution, we exe-


cuted our script by saving it and
then typing the script name at the
command prompt in the Com-
mand Window. This time, we
will execute the script using an
alternate “shortcut” from the Figure 3.17
Editor. From the Editor Toolbar,
click on the “Save and run”
icon, as shown in Figure 3.17.

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

80 CHAPTER 3 MATLAB Fundamentals

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

Open a new m-file and enter the following script:

1 %Get user input


2 b1=input(‘Enter the base value (in inches)’);
3 h1=input(‘Enter the height value (in inches)’);
4 %Compute area
5 input(‘Hit the Enter key to compute area’);
6 area=b1*h1
7 %Compute perimeter
8 input(‘Hit the Enter key to compute perimeter’);
9 perim=(2*b1)+(2*h1)

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:

Enter the base value (in inches)


ch03_mus80164.qxd 8/27/08 2:49 PM Page 81

CHAPTER 3 MATLAB Fundamentals 81

Type in the value “6.5”, and hit the Enter key. The program will display the next
input message and pause again:

Enter the base value (in inches)6.5


Enter the height value (in inches)

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:

Enter the base value (in inches)6.5


Enter the height value (in inches)2.1
Hit the Enter key to compute area
area =
13.6500
Hit the Enter key to compute perimeter
perim =
17.2000

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

82 CHAPTER 3 MATLAB Fundamentals

operations. Note that a period should not be used in filenames; while


MATLAB will add the default “.m” extension to all filenames, no addi-
tional periods may appear in the filename.
■ Filenames must start with a letter. Numbers and other “special” characters
are not permitted as the first character in a filename.
■ Filenames corresponding to prewritten MATLAB functions should be
avoided. Duplicating the name of a preexisting MATLAB function can
cause run-time problems. If you are concerned that the filename you are
considering may duplicate an existing MATLAB function, use the online
help to see if the function name exists.
■ File names are case sensitive: If a file is named “Area”, typing “area” or
“AREA” in the Command Window will not execute the file.
The best advice for choosing your script names is to pick short, descriptive,
unique words, and avoid any characters except the “underscore” in the file name.
The same naming rules hold true for variable names, as well as for function files,
which will be described in the following section.

3.4 Tutorial: Using MATLAB Function Files


In Section 3.3, we investigated the use of a specific type of MATLAB program
called a script. In this section, we will investigate a second type of MATLAB pro-
gram called a function. We have already used some prewritten functions available
to us in MATLAB; the sin and cos functions used in Example 3.3, the functions
listed in Table 3.2, and the input function used in Example 3.5 are all examples
of prewritten functions. Functions are distinguished by:
■ An input argument, or a value that will be “sent into” the function for pro-
cessing. Input arguments are placed inside the parentheses following the
function name.
■ An output, or a value that is “returned” by the function. This value is gen-
erally based on the input argument, and can be assigned to a variable name
if desired.
■ Variables which are defined locally, not globally. Unlike scripts, our func-
tions will not have access to the global variables defined in the Workspace,
nor will the variables we create within our functions be available for use in
the Workspace. The variables defined within the function that are not avail-
able in the Workspace to other scripts and functions are called local vari-
ables. The function cannot communicate with the Workspace through
shared variables; it can only communicate through the input arguments and
the outputs.
We will now develop a function to demonstrate the difference between scripts
and functions.
ch03_mus80164.qxd 8/27/08 2:49 PM Page 83

CHAPTER 3 MATLAB Fundamentals 83

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

84 CHAPTER 3 MATLAB Fundamentals

■ 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

Look at the Workspace Window, as shown in Figure 3.18.


ch03_mus80164.qxd 8/27/08 2:49 PM Page 85

CHAPTER 3 MATLAB Fundamentals 85

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.

Functions can also be called with variables as input arguments. To demonstrate


this, define the following global variables in the Command Window:

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

86 CHAPTER 3 MATLAB Fundamentals

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:

>> help area_rect

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:

>> help area_rect


This function takes the user-defined base
and height of a rectangle, and computes area

By taking advantage of this, we can offer ourselves (or others) reminders of what
our function does and how we use it.

3.5 Tutorial: Computing with One-Dimensional Arrays


In the preceding sections of this chapter, we have performed computations where
single numbers have been assigned to variables. In many programming applica-
tions, we will want to work with arrays, as opposed to single numbers. The rea-
son for this will become clear in subsequent chapters; for now, we will simply
learn the mechanics of assigning and manipulating arrays of numbers.

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

CHAPTER 3 MATLAB Fundamentals 87

>> a=[1 3 6.2]

When we hit the Enter key, the result of this assignment is echoed to the screen:

>> a=[1 3 6.2]


a =
1.0000 3.0000 6.2000

Note that a list of three numbers has been assigned to variable a. This is con-
firmed by checking the Workspace Window.

Create a second array by typing in the following expression:

>> b=[0.7; -3; 0]

Again, when we hit the Enter key, the result is echoed to the screen:

>> b=[0.7; -3; 0]

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

88 CHAPTER 3 MATLAB Fundamentals

For example, suppose we wish to double all of the values currently stored in
array a.

Issue the following command:

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

When the Enter key is pressed, the results can be seen.

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

Again, press the Enter key to see the result:

>> a(2)=.5*a(2)
a =
2.0000 3.0000 12.4000
ch03_mus80164.qxd 8/27/08 2:49 PM Page 89

CHAPTER 3 MATLAB Fundamentals 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:

a(1) a(2) a(3)

2.000 3.000 12.400

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.

Now, consider and type in the following command:

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

a(1) a(2) a(3) a(4)

2.0000 3.0000 12.4000 1.4000

Try the next command:

>> b(7)=3
ch03_mus80164.qxd 8/27/08 2:49 PM Page 90

90 CHAPTER 3 MATLAB Fundamentals

Hit the Enter key to execute the command:

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

CHAPTER 3 MATLAB Fundamentals 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.”

Open a new m-file and create the function as shown:

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

92 CHAPTER 3 MATLAB Fundamentals

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:

>> dims=[6.5 2.1];


ch03_mus80164.qxd 8/27/08 2:49 PM Page 93

CHAPTER 3 MATLAB Fundamentals 93

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)

Hitting the Enter key yields the following output:

>> a_and_p=area_perim(dims)
a_and_p =
13.6500 17.2000

3.6 Tutorial: Computing with Two-Dimensional Arrays


In Section 3.5, we explored computation with one-dimensional arrays. We will
now explore computation using two-dimensional arrays. A two-dimensional
array, or matrix, has both rows and columns associated with it. Matrix mathe-
matics is used throughout engineering, especially in such areas as finite element
analysis, advanced stress analysis, and control systems engineering. Matrices
will be addressed in great detail in Chapter 7 of this text; in this section, we will
simply cover the representation of matrices in MATLAB.

Clear out your Workspace by issuing the clear command. Begin by defining
matrix A by issuing the following command:

>> A=[1 -1 3; 4 -2 -4; 2 3 1; 0 -3 0]

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:

>> A=[1 -1 3; 4 -2 -4; 2 3 1; 0 -3 0]


A =
1 -1 3
4 -2 -4
2 3 1
0 -3 0
ch03_mus80164.qxd 8/27/08 2:49 PM Page 94

94 CHAPTER 3 MATLAB Fundamentals

We call this a (4 × 3) matrix, indicating that it consists of four horizontal rows


and three vertical columns. Note the way in which variable A is listed in the
Workspace Window; in the value column, the size of the matrix is displayed
instead (as shown in Figure 3.19).

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

CHAPTER 3 MATLAB Fundamentals 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]

The designation A(2,:) is interpreted by MATLAB as “second row, all columns.”


Likewise, we could reassign the first column of the matrix to be, for example, the
sum of the second and third columns of the matrix:

>> A(:,1)=A(:,2)+A(:,3)

As in our previous command, the designation A(:,1) is interpreted as “all rows,


first column.”

In addition to viewing/modifying matrices from the command prompt, we can


also use the capabilities of the MATLAB Array Editor to view and change our
matrices. To view any variable in the Array Editor, double-click the array sym-
bol in the Name column on the Workspace Window, as shown in Figure 3.20.

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

96 CHAPTER 3 MATLAB Fundamentals

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

CHAPTER 3 MATLAB Fundamentals 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).

Table 3.4 Rectangle Dimensions for Example 3.8


Base Height
Rectangle 1 6.5 in 2.1 in
Rectangle 2 7.2 in 3.0 in
Rectangle 3 7.5 in 3.3 in

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

Open a new m-file and enter the script shown:

1 %Define the base/height array


2 Dims=[6.5 2.1; 7.2 3; 7.5 3.3];
3 % Compute area and perimeter of Rectangle 1,
4 % and store them in the first row of Props
5 Props(1,:)=area_perim(Dims(1,:));
6 %Repeat for Rectangle 2, and store in second row
7 Props(2,:)=area_perim(Dims(2,:));
8 % Repeat for Rectangle 3
9 Props(3,:)=area_perim(Dims(3,:));
10 %Output results
11 Props

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

98 CHAPTER 3 MATLAB Fundamentals

3.7 Tutorial: Saving a MATLAB Session


While working with MATLAB, all variables assigned during the session from the
command prompt or in script files are available for use until:
■ the clear command is issued, or
■ the MATLAB session is ended by closing the program.
There will be times when you will want to preserve some or all of your variables
for use in a future MATLAB session. In this section, we will demonstrate some
of the data storage capabilities of MATLAB by using the save and load com-
mands.

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:

>> clear ans

By following the clear command with a variable name, we selectively eliminate


only the named variable. Note that the variable ans is no longer available in the
Workspace.

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

CHAPTER 3 MATLAB Fundamentals 99

>> save rectangles

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:

>> load rectangles

The A, Dims, and Props variables are restored to the Workspace.

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:

>> save rectdata Dims Props

Issue the clear command to clear out the Workspace:

>> clear

To reload the saved variables, issue the load command (with the appropriate
filename):

>> load rectdata

The Dims and Props variables will be restored to the Workspace.


ch03_mus80164.qxd 8/27/08 2:49 PM Page 100

100 CHAPTER 3 MATLAB Fundamentals

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

CHAPTER 3 MATLAB Fundamentals 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

102 CHAPTER 3 MATLAB Fundamentals

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

CHAPTER 3 MATLAB Fundamentals 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

104 CHAPTER 3 MATLAB Fundamentals

then the output matrix should be:

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

In this chapter, you will:


■ learn to draw flowcharts to illustrate program steps,
■ learn to control the flow of program steps in MATLAB using for and while
loops,
■ learn to add logical branching steps to MATLAB programs, and
■ learn how to format MATLAB output.

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

106 CHAPTER 4 MATLAB Programming

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

CHAPTER 4 MATLAB Programming 107

The use of flowcharts is not limited to programming operations; for example,


the new product design process at a certain company is illustrated in Figure 4.3.
After the need for a new product has been established, engineers will document
the requirements for the design (the attributes of the new product) and the con-
straints (such as cost, safety codes to be met, manufacturing capabilities of the
company, etc.). Preliminary design activities will attempt to determine the fea-
sibility of producing a product that meets all of the requirements and constraints.
At the end of this phase, a design review meeting is held. At the design review,
a decision is made. If the preliminary design appears feasible, then work on the
detailed design will begin. If not, then another decision is made. One possible
alternative is to reexamine the requirements and constraints, and to do more pre-
liminary design work. Another alternative is to stop work on the project alto-
gether. If the project proceeds into the detailed design phase, then a second
design review is held after the design is finalized. At this review, engineers and
managers will determine whether the design meets all requirements and con-
straints. Another decision point is reached: Should the company begin manu-
facturing, or does the design need to be refined in some way? Although the
flowchart in Figure 4.3 is a very simple version of a design process, it illustrates
features that will be typical of more complex processes. Since design is an iter-
ative process, the flow of the steps often “loops back” to repeat previous steps.
Also, as we have noted, there are decision points at which the direction of the
process flow depends on a condition.

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

108 CHAPTER 4 MATLAB Programming

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

The program steps illustrated in this flowchart can be performed in MATLAB


using the logical if statement, which will be discussed later in the chapter. We per-
formed the same operation with Excel in Chapter 2. Like the pseudocode intro-
duced in Chapter 1, the logic illustrated in a flowchart is generic. This is one
advantage of using flowcharts to document and explain programs—they can be
understood by someone not familiar with the particular language used to write the
program.

4.2 Tutorial: Loop Commands


In Chapter 3, we wrote short MATLAB programs to perform sequences of cal-
culations. However, we have had to rely on coding each of the computations sep-
arately; each line in our script files contained a step in our computation, and the
steps were executed sequentially. Very repetitive calculations required very
repetitive typing in our scripts.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 109

CHAPTER 4 MATLAB Programming 109

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.

4.2.1 The for Loop


The for loop is perhaps the most widely used structure for performing repetitive
computations in any programming language (in some languages, this type of loop
is called a do loop). The logic of the for loop performing 10 repetitions of a set
of calculations is illustrated in Figure 4.5. A counter, m, is used to track the num-
ber of passes through the calculations. When the value of the counter reaches the
limit specified, the program flow progresses from the loop to the next set of
instructions.

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

110 CHAPTER 4 MATLAB Programming

Figure 4.6

To demonstrate a typical for loop, begin by initiating MATLAB and typing in


the following script file:

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.

Save the file with the name “fortest”.

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

CHAPTER 4 MATLAB Programming 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

112 CHAPTER 4 MATLAB Programming

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

Open a new m-file and enter the following script:

1 % Clear out the workspace


2 clear;
3
4 % Generate the data sets
5 for i = 1:11;
6 x(i) = (i-1)*(2*pi/10);
7 ysin(i) = sin(x(i));
8 end;
9
10 plot(x,ysin)

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

CHAPTER 4 MATLAB Programming 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):

1 % Clear out the workspace


2 clear;
3 hold off;
4
5 % Generate the data sets
6 for i = 1:1001;
7 x(i) = (i-1)*(2*pi/1000);
8 ysin(i) = sin(x(i));
9 end;
10
11 plot(x,ysin)

Save the new script.

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

114 CHAPTER 4 MATLAB Programming

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

There is no limit to the number or complexity of statements that can be included


between the for and end statements; whatever statements are included will be
executed as part of the loop. The for loop is a powerful tool for repetitively exe-
cuting computations when we know ahead of time how many times we will need
to repeat the steps. However, on some occasions we will want to execute the loop
until another condition is met; we may not know how many times we want to
repeat the computations beforehand. In such cases, we can employ a while loop.

4.2.2 The while Loop


The while loop is a looping structure that executes a set of statements repeatedly
until a specified variable hits a target value. The logic of the while loop is illus-
trated in Figure 4.10. Unlike a for loop, a counter variable is not required for a
ch04_mus80164.qxd 8/27/08 2:50 PM Page 115

CHAPTER 4 MATLAB Programming 115

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

A condensed form of the while loop flow is shown in Figure 4.11.

As an example, consider the algorithm illustrated in Figure 4.12.

Type the following in a new n-file:

Figure 4.10 Figure 4.11 Figure 4.12


ch04_mus80164.qxd 8/27/08 2:50 PM Page 116

116 CHAPTER 4 MATLAB Programming

Type the following in a new m-file:

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

CHAPTER 4 MATLAB Programming 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.

4.3 Tutorial: Logical Branching Statements


In this section, we will extend our work in MATLAB programming concepts to
include the implementation of logical branching statements. These programming
constructs will allow us to selectively execute portions of code, depending on the
logical conditions of certain program variables. All of the logical statements we
consider are forms of traditional “if-elseif-else” logic, which we will examine in
the following sections of the tutorial.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 118

118 CHAPTER 4 MATLAB Programming

4.3.1 The if Statement


The if statement is the basis for all of the logical branching statements that will
be used. An if statement is readily interpreted the same as any grammatical “if-
then” logical statement:

“If a variable takes on a specified value, then execute the following lines of code.”

The structure of the MATLAB if statement is as follows:

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:

1 % Get the user input


2 y = input(‘Enter a number less than or equal to
10: ‘);
3
4
5 % If the user entered a number bigger than 10,
change the value to 10
6 if y > 10
7 fprintf(‘The number you entered is greater
than 10. It will be changed to 10\n’)
8 y = 10;
9 end;
10
11 % Display the number
12 y

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

CHAPTER 4 MATLAB Programming 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.

Table 4.1 Commonly Used MATLAB Operators


Relational Operators
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
~= Not equal to
Logical Operators
& And
| Or
~ Not
ch04_mus80164.qxd 8/27/08 2:50 PM Page 120

120 CHAPTER 4 MATLAB Programming

Consider this example, in which we modify our iftest script to include addi-
tional logical checks:

1 % Get the user input


2 y = input(‘Enter a number between 1 and 10: ‘);
3
4
5 % If the user entered a number outside the
range, change it to 10
6 if y > 10 | y < 1
7 fprintf(‘The number you entered is outside
the range. It will be changed to 10\n’)
8 y = 10;
9 end;
10
11 % Display the number
12 y

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:

1 % Get the user input


2 y = input(‘Enter a number between 1 and 10: ‘);
3
4
5 % If the user entered a number outside the
range, change it appropriately
6 if y > 10 | y < 1
7 fprintf(‘The number you entered is outside
the range. It will be changed.\n’)
8 if y > 10
9 y = 10;
10 fprintf(‘The number has been changed
to 10.\n’);
11 end;
ch04_mus80164.qxd 8/27/08 2:50 PM Page 121

CHAPTER 4 MATLAB Programming 121

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

122 CHAPTER 4 MATLAB Programming

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.

4.3.2 Adding else and elseif Conditions


Sometimes, when performing logical branching, we would like to direct the pro-
gram to execute one branch of the code if one condition exists, and to another
branch of code if the condition does not exist. This type of logic, implemented
using two different if statements in the previous example, can also be compactly
implemented using an if-else block. The if-else block can be interpreted as fol-
lows:
“If a logical condition exists, then execute specific block of code. Otherwise (else),
execute a different block of code.”
Consider the previous example, as illustrated in Figure 4.14. Note that if the value
of y is between 1 and 10, the program skips directly to the end and displays the
value of y. Suppose that we want to display a message that the value entered is
within the range. This modification is illustrated in Figure 4.15. Notice that for

Figure 4.15
ch04_mus80164.qxd 8/27/08 2:50 PM Page 123

CHAPTER 4 MATLAB Programming 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):

1 % Get the user input


2 y = input(‘Enter a number between 1 and 10: ‘);
3
4
5 % If the user entered a number outside the
range, change it appropriately
6 if y > 10 | y < 1
7 fprintf(‘The number you entered is outside
the range. It will be changed.\n’)
8 if y > 10
9 y = 10;
10 fprintf(‘The number has been changed
to 10.\n’);
11 end;
12 if y < 1
13 y = 1;
14 fprintf(‘The number has been changed
to 1.\n’);
15 end;
16 else
17 fprintf(‘The number is in the range\n’)
18 end;
19
20 % Display the number
21 y

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

124 CHAPTER 4 MATLAB Programming

For example, we will rewrite our complex logic in this preceding script using
an if-elseif-else block:

1 % Get the user input


2 y = input(‘Enter a number between 1 and 10: ‘);
3
4
5 % If the user entered a number outside the
range, change it appropriately
6 if y > 10
7 fprintf(‘The number is too high. It will be
changed to 10\n’)
8 y = 10;
9 elseif y < 1
10 fprintf(‘The number is too low. It will be
changed to 1\n’)
11 y = 1;
12 else
13 fprintf(‘The number is in the range\n’)
14 end
15
16 % Display the number
17 y

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.

For example, we will augment our code as follows:

1 % Get the user input


2 y = input(‘Enter a number between 1 and 10: ‘);
3
4
5 % If the user entered a number outside the
range, change it appropriately and output the
number
ch04_mus80164.qxd 8/27/08 2:50 PM Page 125

CHAPTER 4 MATLAB Programming 125

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

126 CHAPTER 4 MATLAB Programming

Test this code for inputs of 0, 4, 10, 11, and 16.

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

CHAPTER 4 MATLAB Programming 127

4.4 Tutorial: Combining Loops and Logic


The programming constructs learned in the previous two sections (loops and log-
ical conditions) can be combined into very complex and powerful programs. In
this tutorial, we will consider two examples where a combination of loops and
logical conditions is required.

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

128 CHAPTER 4 MATLAB Programming

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.

Enter the commands below in a new m-file:

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

CHAPTER 4 MATLAB Programming 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

130 CHAPTER 4 MATLAB Programming

■ 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

CHAPTER 4 MATLAB Programming 131

Enter these commands in a new m-file:

1 % This program searches for right triangles for


2 % which all three sides are integers
3
4 % Initialize the counter m
5 m = 0;
6
7 % Loop to check all combinations of x and y up
to limits
8
9 for x = 1:25
10 for y = 1:25
11
12 % Calculate the hypotenuse h
13
14 h = sqrt(x^2 + y^2);
15
16 % Check to see if h is an integer
17 % If it is, write x, y, and h to the
screen
18 % and advance the value of the counter m
19
20 if h == floor(h)
21 m = m + 1;
22 x
23 y
24 h
25 end
26 end
27 end
28 m

Save the file as “Triangle” and run it.

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

132 CHAPTER 4 MATLAB Programming

How do we eliminate these duplicate answers? Consider the progressions of x


and y within the for loops. Initially, x is set to 1 and y progresses from 1 to 25:

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.

The third time through the outer loop, x is 3:

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.

4.5 Tutorial: Formatting MATLAB Output


In earlier sections of this chapter, we used the fprintf function to write text mes-
sages to the screen. In this section, we will use the fprintf function to also write
the values of variables to the screen or to an output file and learn how to format
those values and any accompanying text labels.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 133

CHAPTER 4 MATLAB Programming 133

The general format of the fprintf function is as follows:


fprintf(fid, ‘Text string including conversion specifications of variables’, list of vari-
ables)
When printing to the screen, the file identifier (fid) is omitted. Conversion spec-
ifications define the print format for each variable. A conversion specification
begins with % and is followed by the number of characters allowed for the vari-
able (optional), the number of decimal places (optional), and the type of format-
ting:

f = fixed decimal format


e or E = scientific notation
i = integer notation

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

134 CHAPTER 4 MATLAB Programming

Table 4.2 Examples of fprintf Commands


Command Printed to Screen/Comments
fprintf(‘The value of m is %i’,m) The value of m is 12>>
Integer format specified. Note that the prompt
for the next command is on same line if no new
line is specified.
fprintf(‘The value of m is %i\n’,m) The value of m is 12
>>
\n within text string causes printing to advance
to a new line.
fprintf(‘The value of d is %f\n’,d) The value of d is 7532.123400
>>
Fixed format without number of decimal places
set returns all digits that would normally be dis-
played with MATLAB’s “short” format.
fprintf(‘The value of d is %.1f\n’,d) The value of d is 7532.1
>>
Fixed format, one decimal place.
fprintf(‘The value of d is %10.1f\n’,d) The value of d is 7532.1
>>
Ten character widths are used for the display of
d. This type of formatting is useful for aligning
data into columns.
fprintf(‘The value of d is %.2e\n’,d) The value of d is 7.53e+003
>>
Scientific notation, two decimal places.
fprintf(‘The value of d is %.1f\n The value of d is 7532.1
The value of m is %i\n’,d,m) The value of m is 12
>>
If more than one variable is to be printed, they
are listed in the order of their conversion specifi-
cations.
>> fprintf(‘The value of d is %i\n’,d) The value of d is 7.532123e+003
>>
Since d is not an integer, the i format will not
work, and output defaults to scientific notation
and MATLAB’s “short” format.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 135

CHAPTER 4 MATLAB Programming 135

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.

Modify the file Triangle as shown.

1 %This program searches for right triangles for


2 % which all three sides are integers
3
4 % Initialize the counter m
5 m = 0;
6
7 % Loop to check all combinations of x and y up
to limits
8
9 fid = fopen(‘output.txt’,’wt’);
10 fprintf(fid,’ x y h\n’);
11 fprintf(fid,’ === === ===\n’);
12
ch04_mus80164.qxd 8/27/08 2:50 PM Page 136

136 CHAPTER 4 MATLAB Programming

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.

Save the file and run it.

The only output displayed to the screen is


the number of triangles found, as shown in
Figure 4.23. Figure 4.23
ch04_mus80164.qxd 8/27/08 2:50 PM Page 137

CHAPTER 4 MATLAB Programming 137

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.

The contents of the file are shown in Figure 4.25.

Figure 4.24 Figure 4.25

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

138 CHAPTER 4 MATLAB Programming

e. A = 12; g. for i = 1:3


if A < 10 for j = 1:3
A = A*2; if i == j
else A(i,j) = 1;
A = A/2; else
end A(I,j) = 0;
f. for m = 1:10 end
A(m) = 5*m; end
if A(m) <= 25 end
A(m) = 0;
end
end

4.2 Draw a flowchart for each of the scripts in Problem 4.1.


4.3 The following MATLAB scripts contain errors that will prevent them from
executing properly. Identify and explain the errors.
a. for m = 1:5 d. A = 4;
A = A+1; while A < 10
end A = A + 1;
b. for i = 0:3 if A > 5
A(i) = i+2; A = 5;
end end
end
c. for k = 1:10
A(i)= k; e. for m = 1:1000
End j = m/10
A(j) = m;
end
4.4 Suppose that $1000 is deposited into an account that pays 5% interest per
year. At the end of each year, the amount in the account is 1.05 times the
amount at the beginning of the year. Write a MATLAB program with a for
loop to calculate the amount in the account after 10, 20, and 30 years.
4.5 Repeat Problem 4.4, assuming that the interest is compounded quarterly;
that is, one-fourth of the annual interest (1.25%) is added to the account
every three months. Also, repeat the problem with monthly compounding.
4.6 For the account described in Problem 4.4, write a MATLAB program with
a while loop to determine the number of years required for the amount in
the account to reach $5,000.
ch04_mus80164.qxd 8/27/08 2:50 PM Page 139

CHAPTER 4 MATLAB Programming 139

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

140 CHAPTER 4 MATLAB Programming

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

CHAPTER 4 MATLAB Programming 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.

In this chapter, you will:


■ learn about the different types of graphs that are often used in engineering
reports,
■ create scatter graphs from functions and data with Excel and MATLAB,
■ learn how to curve-fit data,
■ learn how to design graphs that are easy to read, and
■ create pie, bar, and combined graphs with Excel.

5.1 Types of Graphs


Before examining various types of graphs, it is worth noting that the terms graph,
chart, and plot are used often used interchangeably. In Excel, all graphs are
referred to as charts. In MATLAB, plot commands are used to create graphs. The
graphs that are of most value in engineering applications are XY, or scatter,
graphs. In these graphs, data pairs are plotted on a grid. Typically, the indepen-
dent variable is plotted on the horizontal (x) axis and the dependent variable is
plotted on the vertical (y) axis. In some cases, however, it is not known if there
is a dependence of one variable on the other. In these cases, plotting the data can
help us determine if the two variables are related. Some XY graphs are used to

143
ch05_mus80164.qxd 8/27/08 2:50 PM Page 144

144 CHAPTER 5 Plotting Data

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.

Figure 5.1 Figure 5.2

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

CHAPTER 5 Plotting Data 145

Figure 5.3 Figure 5.4

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.

A bar graph displays each item as a rectangle with


height proportional to its value, as shown in Figure 5.6.
(Note that in Excel, this type of graph is referred to as
a column chart, while a similar graph with the bars hor-
izontal is referred to as a bar chart. In this text, we will
refer to this type of graph as a bar graph, regardless of
the orientation of the bars.)

One advantage of bar graphs is the ability to display


two or more data sets side by side. For example, the
grade distribution for a second exam is shown along-
side that of the first exam in Figure 5.7. This side-by-
side display of the data sets is an effective method for
allowing comparisons between the two. Figure 5.5
ch05_mus80164.qxd 8/27/08 2:50 PM Page 146

146 CHAPTER 5 Plotting Data

Figure 5.6 Figure 5.7

A special type of bar graph that is useful in statistical analysis is a histogram. In


a histogram, data values are placed into data ranges called “bins.” For example,
suppose that we asked a group of students how long they spent completing an
assignment, and the answers ranged from 45 minutes to 8.5 hours. A convenient
bin interval is 1 hour, so the first bin includes the times less than or equal to 1
hour, the second bin would include the times greater than 1 hour and less than or
equal to 2 hours, and so on up to a final bin including times greater than 8 hours.
A bar graph is created, showing the number of student times that fall within each
interval, as shown in Figure 5.8. Note that the bars are shown without gaps
between them. This is because the values on the horizontal axis are not discrete
values, as they are in Figures 5.6 and 5.7, but rather are data ranges that are con-
tinuous.

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

CHAPTER 5 Plotting Data 147

Figure 5.8 Figure 5.9

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.

5.2.1 Tutorial: Plotting Equations in Excel


In this tutorial, we will be plotting the value of a somewhat complex equation. It
is the equation for the response of a spring-mass-damper system. If you have a
mass hanging from a spring, pulling down on the mass and releasing it causes the
mass to oscillate up and down. Eventually, the oscillations will “decay” until we
no longer see them. How fast the oscillations decay is a function of the damping
of the system. In the simple case of the spring and mass, a small amount of damp-
ing is present in the system. In other systems, such as in the suspension of a car,
an actual damper (the shock absorber) is a part of the system. The spring-mass-
damper model is useful in many fields of engineering. The model applies to
mechanical systems such as suspension systems and the vibrations of structures,
and also to hydraulic systems. There is also an analogy to electric circuits.

The response of the system is determined by formulating and solving a differen-


tial equation. We will be looking at the solution to the underdamped condition, in
which the damping is low enough to allow the mass to oscillate. (If the damping
is very high, then the mass would not even come back to its original position. This
is the overdamped condition. If the damping is just enough so that the mass
returns to its original position without oscillating, this is the critically damped
condition). The solution for the underdamped condition is as follows:
⎡ y ␰␻ ⎤
y = ⎢ y0 cos ␻ D t + 0 sin ␻ D t ⎥ e − ␰␻t (5.1)
⎣ ␻D ⎦
ch05_mus80164.qxd 8/27/08 2:50 PM Page 148

148 CHAPTER 5 Plotting Data

where: y = the displacement of the mass relative to its original position


y0 = the initial displacement (the displacement at time t = 0)
ω = the natural frequency of the system; a measure of how fast the sys-
tem will oscillate freely
ξ = the damping coefficient; a value between zero and one
t = time

and ωD = the damped frequency, which is calculated here:

␻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

CHAPTER 5 Plotting Data 149

For subscripts, choose the Home tab


from the Ribbon and click the arrow
in the Font group to show the Format
Cells box, as shown in Figure 5.12.
Then, click the Subscript box.

Label the cell for the damped fre-


quency and enter the formula from
Equation 5.2, as shown in Figure
5.13.

If you enter ωD in the label cell, you


must change the font back to “Nor- Figure 5.11
mal” after entering the symbol ω.

Figure 5.12 Figure 5.13

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

Press the Enter key to complete the formula.

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

150 CHAPTER 5 Plotting Data

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

Highlight cells A8:B18. Under the


Insert tab of the Ribbon, select Scatter
plot and choose the option for Scatter
with Smooth Lines, as shown in Figure
5.18.

Figure 5.17
ch05_mus80164.qxd 8/27/08 2:50 PM Page 151

CHAPTER 5 Plotting Data 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.

Figure 5.19 Figure 5.20


ch05_mus80164.qxd 8/27/08 2:50 PM Page 152

152 CHAPTER 5 Plotting Data

The chart now appears on its own sheet, as indi-


cated by the tabs at the bottom of the workbook
(see Figure 5.21). If you would like to give the
sheet a unique name (a good idea if your work-
book contains a large number of graphs), right-
click on the tab and select Rename. You can also Figure 5.21
rearrange the tabs by clicking and dragging
them to new positions.

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.

Figure 5.22 Figure 5.23

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.

Recall that this technique copies a formula downward as


long as there are values in the adjacent input cells (time
values).

We will now add this new data to our graph.


Figure 5.24
Right-click within the graph area and choose Select
Data, as shown in Figure 5.25. Notice that the data
ch05_mus80164.qxd 8/27/08 2:50 PM Page 153

CHAPTER 5 Plotting Data 153

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.

Figure 5.25 Figure 5.26

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.

We will now change the appearance of the chart.

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.

Figure 5.27 Figure 5.28

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

154 CHAPTER 5 Plotting Data

Figure 5.29 Figure 5.30

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.

Choose Layout: Legend: None, as shown in Figure 5.31.

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.

Choose Layout: Gridlines: Primary Vertical Gridlines: Major Gridlines, as


shown in Figure 5.32.

Figure 5.31 Figure 5.32

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

CHAPTER 5 Plotting Data 155

Choose Layout: Axes: Primary Horizontal Axis: More Primary Horizontal


Axis Options, as shown in Figure 5.33. Check the Fixed option for the maxi-
mum value of the axis and enter 5 as the maximum value. Also, click on the
pull-down menu beside Axis labels, change the location of the labels to Low, as
shown in Figure 5.34, and then click OK.

Figure 5.33 Figure 5.34

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.

Right-click on the vertical (y) axis and choose Format


Axis. Change the maximum value for the axis to 3.

Right-click on one of the vertical gridlines. Choose For-


mat Major Gridlines and under Line Color, select Solid
line. Use the color menu to change the gridline color to
a shade of gray, as shown in Figure 5.35. Repeat these
steps for the horizontal gridlines.

Showing the gridlines in a light color allows the data curve


to stand out. Figure 5.35
ch05_mus80164.qxd 8/27/08 2:50 PM Page 156

156 CHAPTER 5 Plotting Data

Click on the title. From the Home tab on the Rib-


bon, change the font size as desired. Do the same
for each of the axis labels and for the numbers
along each axis.

The graph should now appear as shown in Figure


5.36.

If you would like to save the settings that you have


made for this graph in order to use them in a future
graph, select Design: Save As Template from the
Ribbon, as shown in Figure 5.37. Give your tem-
plate a name and save it to the default directory.
Figure 5.36 When creating a graph for which you desire to use
these settings, choose the Templates folder from
the list of available chart types, as shown in Figure 5.38. Holding the cursor over
each template icon shows the name of the template.

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.

Figure 5.37 Figure 5.38

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

CHAPTER 5 Plotting Data 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.

Switch to the page containing the graph. Click on the


chart to activate the chart tools on the Ribbon and select
Design: Select Data. In the Select Data Source box, select
Add to create a new data series, as shown in Figure 5.42. Figure 5.42
ch05_mus80164.qxd 8/27/08 2:50 PM Page 158

158 CHAPTER 5 Plotting Data

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.

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

The finished graph is shown in Figure 5.48.

Figure 5.45 Figure 5.46 Figure 5.47


ch05_mus80164.qxd 8/27/08 2:50 PM Page 159

CHAPTER 5 Plotting Data 159

Figure 5.48

5.2.2 Tutorial: Plotting Equations in MATLAB


To demonstrate plotting with MATLAB, we will repeat the spring-mass-damper
problem of Example 5.1.

Plot Equation 5.1 (repeated here): EXAMPLE 5.3

⎡ y ␰␻ ⎤
y = ⎢ y0 cos ␻ D t + 0 sin ␻ D t ⎥ e − ␰␻t (5.1)
⎣ ␻D ⎦
where

␻D = ␻ 1 − ␰ 2

for these values: y0 = 3 in, ω = 2π radians/second, and ξ = 0.10.

■ 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

160 CHAPTER 5 Plotting Data

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

1 % SMD.m: Plots displacement of under damped


2 % spring-mass-damper system
3 %
4 % y0 = initial displacement, inches
5 % dc = damping coefficient
6 % fr = natural frequency, radians/second
7 % fd = damped frequency, radians/second
8 % t = time, seconds
9 % y = displacement, inches
10 %
11 y0 = 3.0;
12 dc = 0.10;
13 fr = 2*pi;
14 fd = fr*sqrt(1-dc^2);
15 for i = 1:101
16 t(i) = (i-1)*0.05;
17 c = cos(fd*t(i));
18 s = sin(fd*t(i));
19 e = exp(-dc*fr*t(i));
20 y(i) = (y0*c + y0*dc*fr/fd*s)*e;
21 end
22 plot(t,y)
ch05_mus80164.qxd 8/27/08 2:50 PM Page 161

CHAPTER 5 Plotting Data 161

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.

From the MATLAB command prompt,


run SMD.

A new window containing the graph,


labeled Figure 1, will be opened, as
shown in Figure 5.49. The graph can be
edited within the window.

Figure 5.49
ch05_mus80164.qxd 8/27/08 2:50 PM Page 162

162 CHAPTER 5 Plotting Data

Click the arrow on the toolbar to allow editing


of the graph, as shown in Figure 5.50.

Right-click on the curve and select Line Width,


as shown on Figure 5.51, and choose a wider
line. Using a similar procedure, change the
color of the line, if desired. Right-click in a
blank area of the graph and click Grid to turn Figure 5.50
on the gridlines display, as shown in Figure
5.52.

Many editing functions can be accessed from the Property Editor.

Right-click in a blank area of the screen and choose Show Property Editor, as
shown in Figure 5.53.

Figure 5.51 Figure 5.52 Figure 5.53

The Property Editor is opened under the


graph, as shown in Figure 5.54. From the
Property Editor, you can add and format
the title and axis labels, change line types
and colors, turn the grid on and off, and
edit many other graph features. Note that
there are options for editing the z-axis;
MATLAB can create 3-D plots. In this
book we will concentrate on 2-D plots;
consult the MATLAB help files if you
would like to learn how to make 3-D
plots.

Enter a title for the plot and labels for


the axes. Click on each text item and
Figure 5.54 change the font and size as desired.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 163

CHAPTER 5 Plotting Data 163

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.

The finished graph is shown in Figure 5.56.

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.

Selecting Edit: Copy Options from the


main menu opens the box shown in Fig-
ure 5.57. Among the options is one to
copy the figure as a metafile or as a
bitmap. For most applications, a metafile Figure 5.56
will produce an image of good resolu-
tion, without increasing the file size as
much as a bitmap image.

With the options set, selecting Edit:


Copy Figure from the main menu places
the figure on the Windows Clipboard.
Select Paste from the other application to
place the figure in the document.

Several of the formatting options set pre-


viously interactively can be written into
the m-file.

Open the m-file SMD. Edit the plot


statement, as shown here, to specify the
line width and color. Add the lines Figure 5.57
ch05_mus80164.qxd 8/27/08 2:50 PM Page 164

164 CHAPTER 5 Plotting Data

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

CHAPTER 5 Plotting Data 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.

Note that the original data, for a damping coefficient of


0.1, is not shown. That is because when a plot com-
mand is encountered, the previously opened plot is
overwritten. Therefore, the first plot was created and
labeled Figure 1, but the subsequent plot command cre-
ated a new Figure 1. If multiple plots are desired, then
the figure command is used to open a new plot window. Figure 5.59
ch05_mus80164.qxd 8/27/08 2:50 PM Page 166

166 CHAPTER 5 Plotting Data

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’);

Save and run the m-file.

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

CHAPTER 5 Plotting Data 167

The finished graph is shown in Figure 5.60.

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:

>> fplot(‘sin’,[0 2*pi])

To plot the displacement of our spring-mass-damper system, we must first create


a function file.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 168

168 CHAPTER 5 Plotting Data

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:

>> fplot(‘displace’,[0 5])

The resulting plot is shown in Figure 5.61.

The function created works well for plotting displace-


ment as a function of time for fixed values of initial
displacement, damping coefficient, and natural fre-
quency. However, if we want to compare the displace-
ments for different values of damping coefficients,
then we would have to create a new function with that
value of the damping coefficient. A better approach is
to create a function with multiple arguments. That is, a
function that returns a value of displacement for
entered values of four variables—initial displacement,
damping coefficient, natural frequency, and time.

Figure 5.61
ch05_mus80164.qxd 8/27/08 2:50 PM Page 169

CHAPTER 5 Plotting Data 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.

Enter the following from the Command Line:

>> fplot(‘displace2(3,.1,2*pi,t)’,[0 5])


>> hold on
>> fplot(‘displace2(3,.2,2*pi,t)’,[0 5])

Note that in the list of argu-


ments for the function, a
variable name (in this case,
t) is inserted for the inde-
pendent variable to be plot-
ted. The function is then
followed by the limits of
the independent variable in
square brackets. As before,
the curves generated will
show a comparison of the
effects of two different
damping coefficients. The
resulting plot is shown in
Figure 5.62. This plot can
now be edited using the
interactive editing tools. Figure 5.62
ch05_mus80164.qxd 8/27/08 2:50 PM Page 170

170 CHAPTER 5 Plotting Data

5.2.3 Tutorial: Plotting Data and Curve Fitting with Excel


Consider a load test of a helical spring, as illustrated in Figure
5.63. The spring is placed between two flat plates and force is
slowly applied to the upper plate, causing the spring to com-
press. When the force reaches a preload value of 25 newtons,
the location of the upper plate is set as zero. As the upper plate
continues to move, the distance that the top plate moves, d,
and the force required to move the plate, F, are recorded. As
soon as the upper plate has moved 10 mm, the test is ended.
Table 5.1 shows the data that was collected in one of these
tests. If we plot the load versus the displacement, then the
slope of the line is called the spring constant. Figure 5.63

Table 5.1 Spring Test Data


d, mm F, N
1 102
2 156
3 230
4 317
5 400
6 452
7 530
8 611
9 670
10 739

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

CHAPTER 5 Plotting Data 171

The resulting graph is shown in Figure


5.65.

You could draw a straight line by hand


or a line connecting the first point and
the last, but we want to find the line that
represents the best fit to the data. There-
fore, we will use a least-squares fit. In a
least-squares fit, a line is found that min-
imizes the squares of the differences
between the y-values of the data points
and the values calculated from the line’s
equation. The differences are squared so
that positive and negative differences do
not cancel each other out. Equations for
the slope and y-intercept are derived
using calculus. Excel and MATLAB Figure 5.65
both have commands for computing
least-squares fits.

Right-click on one of the data points and select Add


Trendline, as shown in Figure 5.66. Accept Linear as the
fit type. Check the boxes to display the equation of the
line and the R-squared value, as shown in Figure 5.67,
and click Close.

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

172 CHAPTER 5 Plotting Data

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

The spring constant is equal to the slope, 72.3 N/mm.

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

CHAPTER 5 Plotting Data 173

Table 5.2 Cooling Experiment Data


Time, minutes Temperature, °F
0 200
1 192
2 185
3 179
4 174
5 169
10 151
15 138
20 126
25 117
30 106
60 84

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

Note that the data points are not equally


spaced. A common error made by many
students is to select a line graph as the
chart type instead of an XY graph. A line
graph places the data along the x-axis at
equal intervals, regardless of the values
of the data. If the x-data is categorical
(for example, months of a year), then a
line graph can be used. However, you
should not use a line graph if you have
numerical values of x.

Clearly, these data points do not fall


along a straight line. If you refer back to
Figure 5.67, you will see that Excel
allows several other types of trendlines
to be fit to the data. Two of these trend- Figure 5.69
line types will produce errors if we try to
apply them to our data. The logarithmic
curve will contain a term of ln(x), which
is undefined for x = 0. A power curve
takes the following form:
y = Axb,
and so will always pass through the origin, and therefore will obviously not fit
our data. The moving average is not technically a curve fit at all, but rather a data
ch05_mus80164.qxd 8/27/08 2:50 PM Page 174

174 CHAPTER 5 Plotting Data

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

Figure 5.70 Figure 5.71

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

CHAPTER 5 Plotting Data 175

damper system decayed exponentially (while oscillating). We will now apply an


exponential trendline to our data.

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.

Right-click on the trendline label box


(equation and R2 values) and select For-
mat Trendline Label. Change the font,
size, fill color, and line color of the box.
Also change the number format from
General to Number and the number of
decimal places to 5, as shown in Figure
5.73.

Figure 5.72 Figure 5.73

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 resulting trendline is shown in Figure 5.74.


Although the general form of an exponential curve
is appropriate, as discussed earlier, the curve does
not match the data particularly well. Again, we
need to think about the actual problem. As the water
cools, its temperature will eventually approach that
of the air around it (77°F in this example). How-
ever, our exponential equation predicts that as time
gets very large, the temperature will approach zero.
In other words, the water will freeze even though
the air temperature is 77°F! Our model should pre-
dict that the difference in the water and air temper-
atures will approach zero. Figure 5.74
ch05_mus80164.qxd 8/27/08 2:50 PM Page 176

176 CHAPTER 5 Plotting Data

Add a new column to the data table in Excel. Enter a


formula that subtracts 77° from the water temperature.
Figure 5.75 shows the values of the temperature differ-
ences. Right-click in the graph area and choose Select
Data, as shown in Figure 5.76.

With Series 1 selected, choose Edit, as shown in


Figure 5.77. Click the icon to the right of the Series Y
Values box, as shown in Figure 5.78. Select the cells
containing the temperature difference data, as shown in
Figure 5.79.

Change the y-axis label to “Temperature Difference,


Figure 5.75 degrees F”.

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.

Figure 5.76 Figure 5.77 Figure 5.78

Figure 5.79 Figure 5.80


ch05_mus80164.qxd 8/27/08 2:50 PM Page 177

CHAPTER 5 Plotting Data 177

5.2.4 Tutorial: Plotting Data and Curve Fitting with MATLAB


As with Excel, there are many curve-fitting options available in MATLAB. The
following example, in which we plot and curve-fit the spring test data from the
previous Excel tutorial, will demonstrate the general procedure for curve fitting
in MATLAB.

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)

The plot is shown in Figure


5.81.

Click the Arrow on the tool-


bar to allow editing of the
graph. Right-click on the
line and choose Marker:
square, as shown in Figure
5.82. Right-click again and
choose Line Style: none.
Figure 5.82
From the main menu, select
Tools: Basic Fitting, as
shown in Figure 5.83. Figure 5.81
Select linear as the type of
fit. Check the Show equa-
tions box, and set the number of Significant digits to 4, as shown in Figure 5.84.
Click Close.

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

178 CHAPTER 5 Plotting Data

Figure 5.83

Figure 5.84 Figure 5.85

Edit the graph to add gridlines, axis labels, and a title.

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.

5.3 Guidelines for Producing Good Graphs


When creating a graph to be used in a paper, report, presentation, or assignment,
there are several guidelines that should be followed in order to make the graph
easy to read and interpret:
■ Give the graph a descriptive title. The title can be either at the top of the
graph or below the graph following the figure number, if figure numbers
are used.
■ Always label both axes, including the units of numerical values.
■ Choose font sizes that are large enough to be read easily, especially if the
graph is to be reduced in size.
■ Gridlines are often useful, but should be of a lighter color and/or narrower
line width than the data curves, so that the data curves stand out.
■ When multiple data curves are shown, they should be clearly identified
with a legend or with text labels next to the curves. Colors are an excellent
way to differentiate the curves, but if your document is going to be printed
or reproduced in black and white, a color legend may be of little value. If
you have more than two or three curves, consider adding text labels beside
the curves, as the legend will become difficult to interpret.
ch05_mus80164.qxd 8/27/08 2:50 PM Page 179

CHAPTER 5 Plotting Data 179

■ 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.86 Figure 5.87


ch05_mus80164.qxd 8/27/08 2:50 PM Page 180

180 CHAPTER 5 Plotting Data

Figure 5.88

5.4 Tutorial: Creating Other Types of Graphs with Excel


We noted earlier that scatter (XY) graphs are by far the most widely used type of
graph in engineering applications. However, other types of graphs can often be
useful, and this tutorial will cover the creation of pie graphs, bar graphs, and
Pareto graphs with Excel. These types of graphs can also be produced with MAT-
LAB. However, Excel is usually the tool of choice because of the ease of data
entry and the flexibility of the plot editing tools.

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.

Table 5.3 Cost Components of Product ABC


Previous Year Current Year
Direct Labor $16.00 $16.80
Benefits $6.40 $9.25
Materials $3.75 $3.80
Equipment $2.20 $2.20
Energy $1.25 $1.45
Overhead $14.00 $16.00

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

CHAPTER 5 Plotting Data 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.

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

Figure 5.91 Figure 5.92

Move the location of the graph to a


separate sheet.

The resulting graph is shown in Figure


5.93.

If there are more than a few slices in


the pie, then even a color pie chart can
be difficult to interpret with only the
legend to identify the slices. A better
way is to add labels adjacent to each
slice. Figure 5.93
ch05_mus80164.qxd 8/27/08 2:50 PM Page 182

182 CHAPTER 5 Plotting Data

First, we will make the pie smaller to allow more room for the labels.

Click immediately outside of the perimeter of the pie, so that it is


selected and surrounded by a sizing box. Click and drag a corner of
the box, as shown in Figure 5.94, to make the pie smaller. You can
also click and drag in the area outside of the pie to center it on the
graph. (Clicking and dragging on the pie itself results in “exploding”
the pie slices. If you inadvertently do this, click the Undo button.)

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

Figure 5.95 Figure 5.96

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.

Figure 5.97 Figure 5.98


ch05_mus80164.qxd 8/27/08 2:50 PM Page 183

CHAPTER 5 Plotting Data 183

Right-click on the pie and choose Select Data, as


shown in Figure 5.99.

Click Edit under the Horizontal (Category) Axis


Labels, as shown in Figure 5.100. Click and drag
over the cells containing the category names, as
shown in Figure 5.101, and click Close.

Click on one of the data labels. All of the labels will


be selected. Click again on one label to select it and
deselect the other labels. Click and drag the label to Figure 5.99
the desired position, as shown in Figure 5.102.
Repeat these steps for the other labels.

To add a border to the slices, right-click on one of the


slices and select Format Data Series. Choose Border
Color: Solid Line and choose black as the border
color, as shown in Figure 5.103. Next, add a title to
the graph. Then, click on the legend to select it and
press the delete key. Figure 5.100

The finished pie graph is shown in Figure 5.104.

There are several options for changing the appearance


of the chart. One is to “explode” the pie segments so
that they are separated.

Right-click on the pie and choose Format Data


Series. Move the Pie Explosion slider bar to the right
to separate the slices, as shown in Figure 5.105. After Figure 5.101 Figure 5.102
selecting a value of about 10%, click Close.

The exploded graph is shown in Figure 5.106. Note


that another way of exploding the slices is by clicking

Figure 5.103 Figure 5.104


ch05_mus80164.qxd 8/27/08 2:50 PM Page 184

184 CHAPTER 5 Plotting Data

Figure 5.105 Figure 5.106

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.

The graph can also be shown in 3-D.

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.107 Figure 5.108 Figure 5.109

The finished 3-D exploded pie graph is shown in Figure 5.110.


ch05_mus80164.qxd 8/27/08 2:50 PM Page 185

CHAPTER 5 Plotting Data 185

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.

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

186 CHAPTER 5 Plotting Data

The resulting graph is shown in Figure 5.113.

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.

Figure 5.114 Figure 5.115

Enter the series name as “Previous Year”, as shown in Figure 5.116.

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

CHAPTER 5 Plotting Data 187

Figure 5.116 Figure 5.117

If desired, you can change the width of the bars by


right-clicking on any of the bars and selecting For-
mat Data Series. Move the slider bars to adjust the
gap/overlap between bars, as shown in Figure
5.118. The top slider controls the gap or overlap
between bars in the same category. The bottom
slider controls the gaps between the categories.
Figure 5.118
The finished graph is shown in Figure 5.119.

Figure 5.119
ch05_mus80164.qxd 8/27/08 2:50 PM Page 188

188 CHAPTER 5 Plotting Data

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.

Figure 5.121 Figure 5.122

The sorted data is shown in Figure 5.123.

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

CHAPTER 5 Plotting Data 189

Figure 5.124 Figure 5.125

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.

Label this column Cumulative %, as shown in Figure 5.127. Figure 5.126

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.

Figure 5.127 Figure 5.128


ch05_mus80164.qxd 8/27/08 2:50 PM Page 190

190 CHAPTER 5 Plotting Data

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.

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

Select a line graph with data markers, as shown in Figure 5.131.

Figure 5.131
ch05_mus80164.qxd 8/27/08 2:50 PM Page 191

CHAPTER 5 Plotting Data 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.

Right-click on one of the data markers corresponding to a cumulative percent-


age and select Format Data Series, as shown in Figure 5.132. Click the Sec-
ondary Axis option, as shown in Figure 5.133.

Figure 5.132 Figure 5.133

The resulting graph is shown in Figure 5.134.

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.

The finished Pareto graph is shown in Figure 5.135.

Figure 5.134 Figure 5.135


ch05_mus80164.qxd 8/27/08 2:50 PM Page 192

192 CHAPTER 5 Plotting Data

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

CHAPTER 5 Plotting Data 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

194 CHAPTER 5 Plotting Data

Change the y-axis to logarithmic by right-clicking on the axis, selecting


Format Axis, and checking the box labeled “Logarithmic scale” (leave the
base as 10). What is the shape of the curve when plotted this way? This is
referred to as a “semi-log” plot, because only one of the axes uses a loga-
rithmic scale.
5.17 Consider the quarter-circles shown in Figure P5.17. For each, estimate the
area by counting the number of squares within the region. (For squares
that are partially within the region, you can count only the squares that are
50% or more within the region, or, for better accuracy, estimate the frac-
tion of the square within the region.) Using Excel, plot the area in square
units versus the radius and add a trendline to fit the data. How does the
equation of the trendline compare with the exact equation of the area of a
quarter-circle? What is the shape of the curve if plotted on logarithmic
scales for both the x and y axes?

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.

Table P5.18 Marble Diameters (inches)

0.476 0.471 0.484 0.477 0.486 0.488


0.481 0.462 0.484 0.489 0.451 0.478
0.469 0.479 0.452 0.484 0.488 0.485
0.482 0.474 0.461 0.478 0.473 0.475
0.469 0.467 0.484 0.463 0.475 0.489

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

Chapter 7: Matrix Mathematics

Chapter 8: Solving Simultaneous Equations

Chapter 9: Numerical Integration

Chapter 10: Optimization

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.

In this chapter, you will:


■ learn to identify linear, polynomial, and general nonlinear algebraic equa-
tions,
■ learn the Bisection Method and Newton’s Method for root finding,
■ learn the fundamental differences between bracketing methods and open
methods for root finding,
■ learn to use the polyval, roots, fplot, and fzero functions in MATLAB,
■ learn to use the Goal Seek tool in Excel, and
■ learn to identify an appropriate computational tool to apply to a specific
equation type.

197
ch06_mus80164.qxd 8/27/08 2:51 PM Page 198

198 CHAPTER 6 Finding the Roots of Equations

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.

In this example, we have used engineering analysis to reduce a design problem


to an algebraic equation that must be solved. However, there are often no simple,
known solutions to the complicated equations that arise from engineering analy-
sis of real physical systems. In this chapter, we will learn to use computational
methods to solve such complicated algebraic equations.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 199

CHAPTER 6 Finding the Roots of Equations 199

6.2 Roots of Equations: Theory


Consider an algebraic equation, such as Equation 6.3:
x 3 + 6 x = sin( 2 x ) (6.3)
The “solution” of this type of equation involves finding a value of x that makes
the expression true. In posing this problem as a classic “root finding” problem,
we first cast the equation in a standard form, by gathering all terms on one side:
f ( x ) = x 3 + 6 x − sin( 2 x ) (6.4)
The root finding problem now becomes finding the values of x that yield:
f (x) = 0 (6.5)
Any value of x that yields this result is called a root of the equation. Depending
on the specific equation, there may be no roots, one root, or any number of roots
(up to infinity).

6.2.1 Classification of Equations


For very simple algebraic equations, and in some other special cases, it is possi-
ble to find the root (or roots) analytically through a closed-form solution. How-
ever, it is often necessary to employ a numerical algorithm to solve an algebraic
equation. Both MATLAB and Excel have powerful tools for solving algebraic
equations. The specific tool we choose to employ, however, will largely depend
on the specific classification of algebraic equation that we are considering.
Therefore, we will first focus on the classification of algebraic equations.

Is the Equation Linear or Nonlinear?


Our algebraic equations can be classified generally into two main groups: linear
algebraic or nonlinear algebraic.

A linear algebraic equation is any equation in which the independent variable


appears in the equation raised to the first power only, either alone or multiplied
by a constant. For example:
7y − 6 = 0 (6.6)
z
= −8 (6.7)
3
8x − 3 = 5x + 4 (6.8)
are all examples of linear algebraic equations. They can each be put into a “stan-
dard form” f (x) = Ax + B = 0; in our examples:
f ( y) = 7 y − 6 = 0 (6.9)
ch06_mus80164.qxd 8/27/08 2:51 PM Page 200

200 CHAPTER 6 Finding the Roots of Equations

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.

Once an equation is classified as nonlinear, we can further refine the classifica-


tion.

Is the Nonlinear Equation a Polynomial Equation or a General Nonlin-


ear Equation?
A polynomial equation is one that can be rearranged such that it includes the inde-
pendent variable only raised to positive integer powers (either alone, or multi-
plied by a constant). For example:
f ( y ) = 3 y 7 + 5 y 3 − 6 y 2 − 12 (6.12)
is an example of a polynomial equation; the independent variable y appears only
raised to positive integer powers. The equation may need to be rearranged to yield
this form; for example, consider the algebraic equation:
3
6 y2 − = 11 y + 4 (6.13)
y
While it may not be obvious at first glance, this equation can be rearranged into
a polynomial equation:
f ( y ) = 6 y 3 − 11 y 2 − 4 y − 3 = 0 (6.14)
The order of a polynomial equation is defined as the highest power to which the
independent variable is raised when the equation is in standard form; our exam-
ple polynomials are seventh- and third-order polynomials, respectively. The
order is important in that an nth-order polynomial will have at most n real roots;
it may have fewer than n real roots, as some of the roots may be imaginary num-
bers. In some special cases, the roots to polynomial equations can be found
ch06_mus80164.qxd 8/27/08 2:51 PM Page 201

CHAPTER 6 Finding the Roots of Equations 201

exactly using analytic methods; for example, second-order polynomials of the


following form:
f ( x ) = Ax 2 + Bx + C = 0 (6.15)
can be solved exactly using the quadratic formula:

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

Any nonlinear algebraic equation that cannot be rearranged and classified as a


polynomial equation will be classified as a general nonlinear equation. This will
include equations that contain the independent variable raised to non-integer
powers (i.e., x 2/3) and/or nonlinear functions of the independent variable (i.e.,
sin(x) and log(x)). Equation 6.4 is an example of a general nonlinear equation.
There is no general way to categorize the number or type of roots of a general
nonlinear equation; there may be no roots, one root, or an infinite number of
roots.

The classification of equations is shown in Figure 6.2.

Figure 6.2

6.2.2 Solution of Equations


Once an equation is in standard form f(x), with all the terms gathered on one side
of the equation, the root finding problem is posed as finding the value of the inde-
pendent variable x such that:
f (x) = 0 (6.17)
Computationally, the specific technique we choose for solving the equation will
depend on the way we classify the equation. In this section, the basic theory of
ch06_mus80164.qxd 8/27/08 2:51 PM Page 202

202 CHAPTER 6 Finding the Roots of Equations

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.

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

CHAPTER 6 Finding the Roots of Equations 203

Figure 6.5 Figure 6.6

We could certainly keep refining our plot and


make our graphical solution more accurate, but
we will stop here. In fact, since this is a simple
linear algebraic equation, this entire graphical
solution is unnecessary; through simple alge-
braic manipulation, we know that the root is
located at y = 67 , or y = 0.8571 (to some arbitrary
precision). However, examination of the graph-
ical solution is an important step toward under-
standing the essence of algorithmic approaches
to root finding. In fact, the method illustrated in
our example graphical case is a well-known
algorithm for root finding known as the Bisec-
tion Method, in which the root is narrowed
down to be in between two possible values of
the independent variable, and the estimate of
the root is taken at the midpoint of the range.
This is repeated until the range is narrow
enough that the root is considered to be accurate
enough for the application at hand. Figure 6.7
illustrates a flowchart for the Bisection Method.
Note that in this flowchart, the product of f (rl )
and f (r) is used to determine where the root
exists in the interval. If the sign of the product
is negative, then f (rl ) and f (r) have different
signs, which is an indication that the root falls
in the lower half of the interval. Otherwise, if
f (rl ) and f(r) have the same sign, the root will
fall in the upper half of the interval.

Figure 6.7
ch06_mus80164.qxd 8/27/08 2:51 PM Page 204

204 CHAPTER 6 Finding the Roots of Equations

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)

0.0000 1.0000 0.5000 –6.0000 –2.5000


0.5000 1.0000 0.7500 –2.5000 –0.7500
0.7500 1.0000 0.8750 –0.7500 0.1250
0.7500 0.8750 0.8125 –0.7500 –0.3125
0.8125 0.8750 0.8438 –0.3125 –0.0938
0.8438 0.8750 0.8594 –0.0938 0.0156
0.8438 0.8594 0.8516 –0.0938 –0.0391
0.8516 0.8594 0.8555 –0.0391 –0.0117
0.8555 0.8594 0.8574 –0.0117 0.0020
0.8555 0.8574 0.8564 –0.0117 –0.0049
0.8564 0.8574 0.8569 –0.0049 –0.0015
0.8569 0.8574 0.8572 –0.0015 0.0002
0.8569 0.8572 0.8571 –0.0015 –0.0006
0.8571 0.8572 0.8571 –0.0006 –0.0002
0.8571 0.8572 0.8571 –0.0002 0.0000
ch06_mus80164.qxd 8/27/08 2:51 PM Page 205

CHAPTER 6 Finding the Roots of Equations 205

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.

Newton’s Method can be described as follows. Suppose we are trying to deter-


mine the root of the function y(x). We begin by guessing the location of the value
x that will make y(x) = 0. We will call this guess xi. To generate an improved esti-
mate of the root, we perform the following steps:
■ We evaluate the true value of the function at this point, y(xi).
■ We compute the slope of the function y(x) at the point xi. We call this slope
value y′(xi). Mathematically, this is done by using principles of calculus to
find the first derivative of the function y(x), and substituting the value of xi
into the new equation. The result is the equation of a line tangent to the
curve y(x); this is illustrated in Figure 6.8.
■ The point where this slope line intersects the x-axis is used as the improved
estimate of the root, which we will call xn. This point is located using
Equation 6.19:
y ( xi )
x n = xi − (6.19)
y ′ ( xi )
This is illustrated in Figure 6.9.

These steps are repeated over and over again, until an estimate that is close
enough to the true root is determined.

Figure 6.8 Figure 6.9


ch06_mus80164.qxd 8/27/08 2:51 PM Page 206

206 CHAPTER 6 Finding the Roots of Equations

As an example, consider the function:


y = 3 x 3 − 15 x 2 − 20 x + 50 (6.20)
It is known from principles of calculus that the slope of the equation is as follows:
y′ = 9 x 2 − 30 x − 20 (6.21)
We will use Newton’s Method to find the root of Equation 6.20.

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:

y(10 ) = 3(10 )3 − 15 (10 )2 − 20 (10 ) + 50 (6.22)


= 1350
■ Evaluate the slope of the curve at the point xi = 10. This is done by evaluat-
ing Equation 6.21 with xi = 10. In this example, the slope is as follows:
y′ = 9 (10 )2 − 30 (10 ) − 20 (6.23)
= 580
■ Using Equation 6.19, the improved root estimate can be obtained. In the
example, this yields:
1350
x n = 10 − (6.24)
580
= 7.6724
This is illustrated graphically in Figure 6.10.

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.

Table 6.2 Seven Iterations of Newton’s Method for Equation 6.20


xi y y′ xn
10.0000 1350.00 580.0000 7.6724
7.6724 368.4941 279.6210 6.3546
6.3546 87.0049 152.7887 5.7851
5.7851 13.1273 107.6559 5.6632
5.6632 0.5457 98.7502 5.6577
5.6577 0.0011 98.3529 5.6577
5.6577 0.0000 98.3521 5.6577
ch06_mus80164.qxd 8/27/08 2:51 PM Page 207

CHAPTER 6 Finding the Roots of Equations 207

Figure 6.10

A flowchart for this method is shown in Figure 6.11.

Comparison of the Bisection Method and Newton’s


Method yields a major difference:
■ The Bisection Method requires two initial
guesses, with one on each side of the root.
Such a method is known as a bracketing
method.
■ Newton’s Method requires a single initial
guess, with no restrictions placed on it (other
than that the slope must not be zero at the ini-
tial guess). Such a method is called an open
method.
Bracketing methods and open methods have other
fundamental differences that should be addressed: Figure 6.11

■ As long as there is one root between the two


initial guesses in a bracketing method, the algorithm is guaranteed to find
the root, to whatever final precision is specified. As such, we say that
bracketing methods have “guaranteed convergence.” Open methods are not
guaranteed to find a root; they sometimes “diverge,” or fail to ever reach a
stopping point at an appropriate root. Programmers who implement open
methods must take care to check for divergence, and stop their programs
when it is detected.
■ While convergence is not guaranteed in an open method, in most cases
convergence will occur much quicker in an open method than in a bracket-
ing method; the desired precision of the solution will be reached with fewer
iterations in an open method.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 208

208 CHAPTER 6 Finding the Roots of Equations

■ 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

CHAPTER 6 Finding the Roots of Equations 209

6.3 Tutorial: Solution of General Nonlinear Equations


Using MATLAB
In this section, the use of MATLAB in the solution of general nonlinear equations
will be explored. In actuality, the method described in this section can be applied
to any algebraic equation, regardless of classification. However, since there are
simpler and more powerful tools available for polynomial equations, the method
described in this section is best suited for the general nonlinear case.

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

x tan x = 0.4 (6.25)

■ 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

210 CHAPTER 6 Finding the Roots of Equations

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:

>> fplot(‘ex6_1’, [0 1.5])

The plot shown in Figure 6.12


appears.

Fortunately, there does appear


to be a root in the interval we
selected (if there was not, we
would widen or change the plot-
ting interval). From observing
the plot, we will estimate the
root location to be near the point
x = 0.5.

Step 4: Use the fzero command,


along with the estimate of the
root, to compute the root. The
Figure 6.12
fzero command is a prewritten
root finding function in MAT-
LAB. It has the following syntax:

fzero(‘function_name’, guess)
ch06_mus80164.qxd 8/27/08 2:51 PM Page 211

CHAPTER 6 Finding the Roots of Equations 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

Note that the function does approximately equal zero.

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.

6.4 Tutorial: Solution of Polynomial Equations Using


MATLAB
An equation that has been classified as a polynomial equation is best solved using
the method described in this section. This method, which uses the MATLAB
roots command, will provide all of the roots of a polynomial equation (both real
and imaginary) without the need for an initial guess.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 212

212 CHAPTER 6 Finding the Roots of Equations

The solution method is described by this procedure:


1. Write the equation in standard form f(x).
2. Define a MATLAB array containing the constant coefficients of the poly-
nomial equation.
3. Find the roots of the polynomial using the MATLAB roots command.
4. Check your answers, using the MATLAB polyval command.
Using an example case, we will now explore this solution method step by step.

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

CHAPTER 6 Finding the Roots of Equations 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

214 CHAPTER 6 Finding the Roots of Equations

>> polyval(p,r)
ans =
1.0e–012 *
–0.1990 – 0.0426i
–0.1990 + 0.0426i
0

The polynomial yields approximately zero at each of the root locations.

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.

6.5 Tutorial: Solution of General Nonlinear Equations


Using Excel
Excel can be used to find a solution to a general nonlinear equation. Excel has
two tools that can be used for this purpose: Goal Seek and Solver. The simpler of
these, Goal Seek, will be employed in this section. The more complex and pow-
erful tool, Solver, will be explored in Chapters 8 and 10.

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:

f ( x ) = x tan x − 0.4 = 0 (6.30)

■ Solution
Begin a new Excel worksheet. Enter the text shown in Figure 6.13 in cells A1
and A2.

In cell B1, we must enter an initial guess for the


solution. If we did not know anything about the
function, we would certainly need to plot the func-
tion at this point, and use the plot to determine an
initial guess. Since, however, we have already Figure 6.13
ch06_mus80164.qxd 8/27/08 2:51 PM Page 215

CHAPTER 6 Finding the Roots of Equations 215

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

The Goal Seek dialog box will appear, as


shown in Figure 6.16.

Since we preselected cell B2, it appears in


the “Set cell:” box as the cell that we will
drive to a specified value. Click in the
“To value:” box, and type the number 0,
as shown in Figure 6.17.
Figure 6.16 Figure 6.17
This is the “target value” for our equation
described in B2, which in our case is zero (since we began with the problem cast
in standard form f(x) = 0). Click in the “By changing cell:” box and click on cell
B1 to select it, as shown in Figure 6.18.

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

216 CHAPTER 6 Finding the Roots of Equations

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

Click OK to accept the solution.

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

CHAPTER 6 Finding the Roots of Equations 217

6.4 Consider the following function:


3x4 – 6x = 6
a. Put the function in standard form, and plot the function using MAT-
LAB.
b. Write a simple program using the Bisection Method to find any one
root of the equation to within 0.01.
c. Write a simple MATLAB script to find the solution to the polynomial
equation using the roots command.
d. Check your results using the Excel Goal Seek tool.
6.5 Write a MATLAB script (and required function) to find the first positive
and first negative solutions (i.e., the ones with the smallest absolute val-
ues) to the following nonlinear algebraic equation using the fzero com-
mand.
7x = 4.5 + x3 cos x

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

6.9 A mechanism known as a four-bar linkage is shown in Figure P6.9.


Mechanisms such as this are used in mechanical systems to generate a
specific output motion in response to an input motion. This four-bar link-
age is a one-degree-of-freedom mechanism; if the position of any one of
the links is known, the position of all of the other links can be found.
Assume that there is a motor driving Link 2; if the angle of Link 2 (θ2) is
known, the angle of Link 4 (θ4) can be found through the solution of the
following equation:

L1 = L4 cos␪4 − L2 cos␪2 + L23 − ( L4 sin ␪4 − L2 sin ␪2 )


2

where Li is the length of Link i. (Note that Link 1 is an “implied link,”


and simply specifies the distance between the two rotational pivot points.)
ch06_mus80164.qxd 8/27/08 2:51 PM Page 218

218 CHAPTER 6 Finding the Roots of Equations

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.10 When an amount of money P is invested at an annual interest rate of i


(expressed as a decimal value, not a percentage), the total value of the
investment A after n years can be computed as follows:
A = P(1 + i)n
a. Write a MATLAB program that:
■ Prompts the user to enter an initial investment amount (P), a tar-
get value for the investment (A), and an interest rate (i)
■ Computes and outputs the number of years (n) that it will take for
the initial investment to grow to a specific target value (using a
root finding technique)
Test the program for an initial investment of $10,000, a target value
of $100,000, and an interest rate of 0.10.
b. Check your answer to part a using the Excel Goal Seek tool.
c. Check your answers to parts a and b by developing a computer-
generated plot of A versus n for the test case values.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 219

CHAPTER 6 Finding the Roots of Equations 219

6.11 Revisit the interest problem described in Problem 6.10.


a. Write a MATLAB program that:
■ Prompts the user to enter an initial investment amount (P), a tar-
get value for the investment (A), and an investment period (n)
■ Computes and outputs the interest rate (i) that it will take for the
initial investment to grow to a specific target value in the speci-
fied investment period (using a root finding technique)
Test the program for an initial investment of $10,000, a target value
of $100,000, and an investment period of 20 years.
b. Check your answer to part a using the Excel Goal Seek tool.
c. Check your answers to parts a and b by developing a computer-
generated plot of A versus n for the test case values.
6.12 A mechanical system is vibrating according to the following model:
y(t) = 7e–0.09t(sin(1.15t) + cos(1.15t))
where y(t) is the position in inches and t is the time in seconds. The
period of the vibration is defined as the time it takes to complete one
cycle of the vibration. Using either MATLAB or Excel, determine the
period of the vibrating system as follows:
a. Plot the position of the system as a function of time.
b. Use a root finding method to determine the first time at which the
position of the vibrating system is zero.
c. Use a root finding method to determine the third time at which the
amplitude of the vibrating system is zero.
d. Estimate the time to complete one cycle of the vibration by determin-
ing the difference between the two times.
The period of the vibration relates to one of the numerical parameters in
the model. Using your own research, determine which parameter corre-
sponds to the period, and check your answer.
6.13 Consider the hoist described in Problem 5.16, where a 500-N weight is
being lifted by a rope wound around the cylinder, with a known friction
coefficient of μ = 0.3. An engineer has specified a rope to be used in this
application, which has a known load capacity of 750 N. Determine the
maximum contact angle θ that can be used with this rope, 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.
ch06_mus80164.qxd 8/27/08 2:51 PM Page 220

220 CHAPTER 6 Finding the Roots of Equations

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.

In this chapter, you will:


■ learn to properly represent matrices using MATLAB and Excel,
■ learn how to perform matrix addition using MATLAB and Excel,
■ learn how to perform matrix multiplication using MATLAB and Excel,
■ learn how to multiply a scalar by a matrix using MATLAB and Excel,
■ learn how to transpose a matrix using MATLAB and Excel,
■ learn how to calculate the determinant of a matrix using MATLAB and
Excel, and
■ learn how to calculate the inverse of a matrix using MATLAB and Excel.

7.1 Properties of Matrices


The intent of this section is to provide an overview of the properties of matrices
so that you can understand how to complete basic matrix operations using MAT-
LAB or Excel. Rigorous treatment of the subject is left to mathematics textbooks.

221
ch07_mus80164.qxd 8/27/08 2:51 PM Page 222

222 CHAPTER 7 Matrix Mathematics

A matrix can be thought of as an array of numbers displayed


in a tabular format, as shown in Figure 7.1. Matrices are often
assigned a name, and in this example we have named this
matrix A. Note that matrices are usually denoted with bold Figure 7.1
font.

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.

7.1.1 Matrix Addition


Two or more matrices of the same dimension may be added together using matrix
addition such that C = A + B, where matrix C is referred to as the sum matrix.
The operation of matrix addition is given by cij = aij + bij, as illustrated in Equa-
tion 7.1. Matrix addition is commutative, meaning A + B = B + A.
⎡ a11 a12 ⎤ ⎡ b11 b12 ⎤ ⎡ a 11 + b11 a12 + b12 ⎤
⎢a + = =C (7.1)
⎣ 21 a22 ⎥⎦ ⎢⎣ b21 b22 ⎥⎦ ⎢⎣ a21 + b21 a22 + b22 ⎥⎦

7.1.2 Matrix Multiplication


The ability to perform the operation of matrix multiplication between two matri-
ces depends upon both the dimension of each matrix and the order of the opera-
tion. Matrix multiplication is denoted by C = A × B or C = AB. Matrix
multiplication is only possible if the number of columns of the first matrix is
equal to the number of rows of the second matrix. The dimension of the product
ch07_mus80164.qxd 8/27/08 2:51 PM Page 223

CHAPTER 7 Matrix Mathematics 223

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)

c12 = a11b12 + a12b22 + a13b32 (7.2c)


(first row by second column, resulting in index 12)

c21 = a21b11 + a22b21 + a23b31 (7.2d)


(second row by first column, resulting in index 21)

c22 = a21b12 + a22b22 + a23b32 (7.2e)


(second row by second column, resulting in index 22)
Matrix multiplication is not commutative, meaning AB ≠ BA.

7.1.3 Multiplying a Matrix by a Scalar


When we multiply a matrix by a scalar, we are simply “scaling” each element of
the matrix, thus creating a new matrix. This is normally denoted by C = kA,
where k is any scalar. This is accomplished by multiplying each element by the
scalar, as illustrated in Equation 7.3:
⎡a a12 ⎤ ⎡ ka11 ka12 ⎤
k ⎢ 11 = (7.3)
⎣ a21 a22 ⎥⎦ ⎢⎣ ka21 ka22 ⎥⎦
ch07_mus80164.qxd 8/27/08 2:51 PM Page 224

224 CHAPTER 7 Matrix Mathematics

7.1.4 The Identity Matrix


The identity matrix, I, is a square matrix with a unique property: When I is mul-
tiplied by another matrix A (assuming that their dimensions are such that multi-
plication is possible), the product is equal to A. In this regard, multiplying a
matrix by I is analogous to multiplying a scalar by one. This operation can be
expressed, as shown in Equation 7.4:
IA = A (7.4)
When multiplying a matrix by the identity matrix, this matrix multiplication has
the unique property of being commutative, or IA = AI = A.

The identity matrix is a diagonal matrix, which is a square


matrix containing zeros at all elements except the diagonal run-
ning from the top left to the lower right. The identity matrix is
a special diagonal matrix that contains all 1’s on the diagonal.
A 3 × 3 identity matrix is illustrated in Figure 7.4. Figure 7.4

7.1.5 The Matrix Transpose


Sometimes it is necessary to transpose a matrix. A transpose is a rearrangement
of the rows and columns such that row 1 becomes column 1, row 2 becomes col-
umn 2, and so on. Any matrix can be transposed and the transpose operation may
change the dimension of the matrix. The transpose of matrix A is often denoted
as AT. Figure 7.5 illustrates the matrix transpose operation. Notice how the
dimension changes from a 2 × 3 to a 3 × 2 as matrix A is transposed.

Figure 7.5

7.1.6 The Determinant of a Matrix


The determinant of a matrix is a scalar quantity that has some uses in matrix alge-
bra. The determinant is only defined for square matrices. The determinant of
matrix A is denoted as ⏐A⏐, or det(A). Finding the determinant of 2 × 2 and
3 × 3 matrices can be done relatively easily.

The 2 × 2 matrix A is given in Equation 7.5:


⎡a a12 ⎤
A = ⎢ 11 (7.5)
⎣ a21 a22 ⎥⎦
ch07_mus80164.qxd 8/27/08 2:51 PM Page 225

CHAPTER 7 Matrix Mathematics 225

The determinant of A is given in Equation 7.6:


⏐A⏐ = a11a22 – a21a12 (7.6)
The 3 × 3 matrix B is given in Equation 7.7:

⎡ b11 b12 b13 ⎤


B = ⎢ b21 b22 b23 ⎥ (7.7)
⎢ ⎥
⎣ b31 b32 b33 ⎦

The determinant of B is given in Equation 7.8:


b22 b23 b b23 b b22
B = b11 − b12 21 + b13 21 (7.8)
b32 b33 b31 b33 b31 b32

The determinant of larger matrices can be calculated in a similar manner; how-


ever, it is much easier to use Excel or MATLAB than to calculate the determinant
by hand.

7.1.7 The Matrix Inverse


The inverse of a matrix has the property such that if you multiply the inverse of
a matrix by the original matrix, the resultant matrix is the identity matrix. This
property is illustrated in Equation 7.9.
AA–1 = I (7.9)
The inverse of matrix A is denoted as A–1. The multiplication of a matrix times
its inverse is commutative, or AA–1 = A–1A = I. Only square matrices have an
inverse, but not all square matrices can be inverted. The inverting of a matrix can
be tedious and the actual mechanics are left to courses in linear algebra. We will
use the power of Excel and MATLAB to invert matrices for us.

7.2 Tutorial: Matrix Operations Using Excel


Excel has many built-in functions for performing matrix operations. The tutori-
als of this section will teach you how to:
■ properly format a matrix in Excel,
■ perform matrix addition in Excel,
■ perform matrix multiplication in Excel,
■ multiply a matrix times a scalar in Excel,
■ transpose a matrix in Excel,
■ calculate the determinant of a matrix in Excel, and
■ invert a matrix in Excel.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 226

226 CHAPTER 7 Matrix Mathematics

7.2.1 Formatting Matrices and Adding Matrices Using Excel


Each element of a matrix must be typed into a separate cell. Type in the matrix
shown in Figure 7.6 into cells B2:D4. Align the cells to the center.

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

Figure 7.7 Figure 7.8

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

CHAPTER 7 Matrix Mathematics 227

When using Excel for matrix operations, it is impor-


tant that you know the rules regarding matrix dimen-
sions. This is because you must designate, in
advance, the dimension of the resulting matrix of the
operation. This is accomplished by selecting the cells
in which you would like the resulting matrix to be
displayed. If you are adding two 3 × 3 matrices, you Figure 7.9
would need to highlight a set of 3 × 3 cells for the
resulting matrix. After selecting the range of cells for the resulting matrix, you
will type the formula for the matrix operation into the Formula Window. Then
you must press the Enter key while holding down the Ctrl and Shift Keys to com-
plete the matrix operation.

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

7.2.2 Multiplying Matrices and Transposing Matrices Using Excel


Type, label, and format matrices A and B, as illus-
trated in Figure 7.12.

Next, we will perform the operation C=AB. We


need to use the matrix multiplication rule with
respect to dimensions to determine the dimension of Figure 7.12
the product matrix C. We are multiplying a 3 × 3
matrix times a 3 × 2 matrix. Referring to Figure 7.3,
ch07_mus80164.qxd 8/27/08 2:51 PM Page 228

228 CHAPTER 7 Matrix Mathematics

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.

Highlight cells B6:C8 as the location of the


product matrix. Select the Formula Window,
type the formula “=MMULT(B2:D4,G2:H4)”,
and then press Ctrl+Shift+Enter to complete the
operation. Label the product matrix as “AB=” in
cell A7 and then properly format the matrix, as Figure 7.13
shown in Figure 7.13.

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.

Merge cells F6:F7 and then type “(AB)T=”


into the merged cell. Properly format your
matrix so that it looks similar to Figure 7.14.

Finally, we can multiply a matrix by a scalar.


Figure 7.14
Type “k=” into cell A11 and then type “3”
into cell B11. For this exercise we will mul-
tiply matrix B by the scalar k. Scalar multiplication does not change the dimen-
sion of the matrix, so we need to select a 3 × 2 set of cells in which to place the
resulting matrix. Select cells G10:H12 and then select the Formula Window.
Type “=B11*G2:H4” and then press Ctrl+Shift+Enter to complete the opera-
tion.

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

CHAPTER 7 Matrix Mathematics 229

7.2.3 Calculating the Determinant and Inverting Matrices


Using Excel
Open a new spreadsheet. Type, label, and format matrix A, as illus-
trated in Figure 7.16.

Let’s calculate the determinant of matrix A. Type “det(A)=” into cell


F3 and then type the formula “=MDETERM(B2:D4)” into cell
Figure 7.16
G3. Your spreadsheet should look similar to Figure 7.17.

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.

The #NUM! that now appears in the inverse


matrix indicates that Excel is unable to calcu-
late the inverse of matrix A. Remember, not all
square matrices can be inverted and our new
matrix A is one of those cases. Our new matrix
has the same elements in rows 2 and 3. This
means that these two rows are not linearly inde- Figure 7.19
pendent. Independent rows are one requirement
for invertible matrices. In addition to non-
independent rows, matrices with all zeros in a given row cannot be inverted. Also
note that the determinant is now equal to zero. A matrix with a determinant of
zero is called singular and does not have an inverse. Calculating the determinant
of a matrix and checking that it does not equal zero is another useful method to
ch07_mus80164.qxd 8/27/08 2:51 PM Page 230

230 CHAPTER 7 Matrix Mathematics

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

7.3 Tutorial: Matrix Operations Using MATLAB


MATLAB has many built-in functions for performing matrix operations. The
tutorials of this section will teach you how to:
■ properly enter a matrix in MATLAB,
■ perform matrix addition in MATLAB,
■ perform matrix multiplication in MATLAB,
■ multiply a matrix times a scalar in MATLAB,
■ transpose a matrix in MATLAB,
■ calculate the determinant of a matrix in MATLAB, and
■ invert a matrix in MATLAB.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 231

CHAPTER 7 Matrix Mathematics 231

7.3.1 Formatting and Adding Matrices Using MATLAB


Matrix addition in MATLAB is accomplished by using the + operator. To add
matrix A to matrix B, we must first create the variables A and B and assign matri-
ces to each variable. Recall from Chapter 3, to create a matrix, we type square
brackets, followed by each element separated by a space or comma, and then use
a semicolon to indicate the next row. Create matrices A and B as follows:

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

Now find the matrix C = A + B as follows:

>> C=A+B
C =
2 0 3
3 2 4
3 5 2

7.3.2 Matrix Multiplication Using MATLAB


Matrix multiplication is accomplished using the * operator. Using matrices A
and B defined in Section 7.3.1, find C = AB:

>> C=A*B
C =
7 6 3
9 7 6
5 5 5
ch07_mus80164.qxd 8/27/08 2:51 PM Page 232

232 CHAPTER 7 Matrix Mathematics

Matrix-scalar multiplication is also accomplished using the * operator. Issue the


following command to scale up matrix C by a factor of two while reassigning
the scaled matrix the variable C:

>> C=2*C
C =
2 0 4
4 2 8
0 12 2

7.3.3 Transposing Matrices Using MATLAB


Matrices are transposed in MATLAB using the ’ (apostrophe symbol) operator.
To demonstrate this, let’s first redefine matrices A and B, as shown here:

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

Now, complete the operation C = AB, as shown here:

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

CHAPTER 7 Matrix Mathematics 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

7.3.4 Inverting Matrices Using MATLAB


To invert a matrix in MATLAB, we use the command inv(A) where the variable
A is a square matrix. Let’s redefine matrices A and B, as shown here:

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

234 CHAPTER 7 Matrix Mathematics

Now, complete the operations C = A–1 and D = B–1, as shown here:

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

MATLAB gives us a warning, indicating that matrix B is singular or very close


to singular. Although there is a matrix D reported to the screen, note the scalar
out in front of matrix D. Each of the elements is being multiplied by the scalar
1016. Therefore, the matrix D should not be used in subsequent calculations.

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

CHAPTER 7 Matrix Mathematics 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⎦

7.1 Use Excel to calculate the resultant matrix C = A + B for matrices


A and B above. Check your results by calculating the resultant matrix
C = A + B by hand.
7.2 Use Excel to show that AB ≠ BA for matrices A and B above.
7.3 Use Excel to calculate the determinant of matrices A and B above. Does
an inverse exist for each matrix? Check your results by calculating the
determinants of matrices A and B by hand.
7.4 Use Excel to show that AA–1 = A–1A for matrices A and B above.
7.5 Use MATAB to calculate the resultant matrix C = A + B for matrices A
and B above. Check your results by calculating the resultant matrix C =
A + B by hand.
ch07_mus80164.qxd 8/27/08 2:51 PM Page 236

236 CHAPTER 7 Matrix Mathematics

7.6 Use MATLAB to show that AB ≠ BA for matrices A and B above.


7.7 Use MATLAB to calculate the determinant of matrices A and B above.
Does an inverse exist for each matrix? Check your results by calculating
the determinants of matrices A and B by hand.
7.8 Use MATLAB to show that AA–1 = A–1A for matrices A and B above.

Use matrix D below for Problems 7.9 and 7.10.

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

Use matrices G and H below for Problems 7.11–7.14.

⎡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

CHAPTER 7 Matrix Mathematics 237

Use matrices M and N below for Problems 7.15 and 7.16.

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

Use matrices P and Q below for Problems 7.17 and 7.18.

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

Use matrices R and S below for Problems 7.19 and 7.20.

⎡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!)

In this chapter, you will:


■ learn how to use matrices to represent a system of linear equations,
■ learn how to perform matrix operations to solve a system of linear equa-
tions using MATLAB and Excel, and
■ learn how to use the Solver tool to solve a set of nonlinear equations using
Excel.

8.1 Systems of Linear Equations


Engineering analysis often results in a system of equations that must be solved
simultaneously. The solution technique depends upon the type of equations that
make up the system. Often, the equations will be linear, meaning the equations
contain only constants and products of constants and first-power variables, as
covered in Chapter 6. So if x is one of our variables, it will show up as x, 3x, –5x,
or any other constant times x, but not as x2, x , 5x, or other more advanced func-
tions (recall, equations containing these are nonlinear). Linear equations that

239
ch08_mus80164.qxd 8/27/08 2:52 PM Page 240

240 CHAPTER 8 Solving Simultaneous Equations

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.

8.2 Tutorial: Solutions of Linear Equations Using Excel


EXAMPLE 8.1 Use Excel to graphically determine the solution to the system of linear equations
given as Equations 8.1a and 8.1b, which are repeated here:
2x + 3y = 14 (8.1a)
–4x + y = 28 (8.1b)

■ 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

CHAPTER 8 Solving Simultaneous Equations 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.

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

The solution of these two equations is the unique


x and y pair that satisfies both equations. This is
the intercept of the two equations, which cur-
rently is not displayed on our chart. We can see
from Figure 8.3 that the lines should intersect at
an x value between –10 and 0. Let’s replot the
chart over this range of x values. Change the
value in cell A3 to “–10”. Look at your chart. It
should now look similar to Figure 8.4. The lines
now intersect and we can see that the solution is
near x = –5; however, we still do not have the res-
olution to be definite about the value.

Figure 8.3
ch08_mus80164.qxd 8/27/08 2:52 PM Page 242

242 CHAPTER 8 Solving Simultaneous Equations

Figure 8.4 Figure 8.5

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

A second method of solving simultaneous equations in Excel is utilizing an Excel


tool called Goal Seek. Recall from Chapter 6, Goal Seek allows you to automati-
cally set the value of one cell by changing the value of a second cell. Goal Seek can
be useful in solving simultaneous equations where only two variables exist.

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

CHAPTER 8 Solving Simultaneous Equations 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.

We now have a solution for the system of equations.

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.

In electrical engineering, systems of linear equations are often encountered in


resistive circuit analysis. Let’s use this as our example. First, look at the simple
circuit shown in Figure 8.9. Electrical current is a quantity measured by the units
of amperes, or amps. The circuit demands a given current from its voltage source
(battery). This current depends on the overall resistance or load connected to the
battery. For a single resistor connected to a voltage source, the current through
the circuit is given by Ohm’s law, as shown in Equation 8.5:
⌬V
I= (8.5)
R
where ΔV is the voltage drop across the resistor (which equals the battery voltage
in the circuit in Figure 8.9) in the units of volts (V), I is the current through the
resistor (which is also equal to the current in any part of the circuit in Figure 8.9)
in the units of amps (a), and R is the value of the resistor in the units of ohms (Ω).
ch08_mus80164.qxd 8/27/08 2:52 PM Page 244

244 CHAPTER 8 Solving Simultaneous Equations

Figure 8.9 Figure 8.10

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

CHAPTER 8 Solving Simultaneous Equations 245

Now, rearranging Equations 8.6–8.8 yields the following system of equations:


I1 –I2 –I3 = 0 (8.9a)

R1I1 + R2I2 = VB (8.9b)

R2I2 – (R3 + R4)I3 = 0 (8.9c)


This system of equations can be written in matrix form as Equation 8.10:

⎡1 −1 −1 ⎤ ⎡ I1 ⎤ ⎡ 0 ⎤
⎢R R2 0 ⎥ ⎢ I ⎥ = ⎢V ⎥ (8.10)
⎢ 1 ⎥⎢ 2⎥ ⎢ B⎥
⎣0 R2 − ( R3 + R4 ) ⎦ ⎣ I 3 ⎦ ⎣ 0 ⎦

Now we can express Equation 8.10 in the general form of:


AX = C (8.11)
where A is called the coefficient matrix, X is called the variable matrix, and C is
called the constant matrix. The unknowns in this system are the currents, I1, I2,
and I3, that make up the X matrix. We can now perform matrix operations to solve
for the values of the X matrix. First, multiply each side of the equation by A–1
(remember that the order of matrix operations is important), yielding Equation
8.12:
A–1AX = A–1C (8.12)
Next, recall that A–1A = I, the identity matrix. Substituting this into Equation 8.12
yields:
IX = A–1C (8.13)
Finally, recall that IX = X. Substituting into Equation 8.13 yields:
X = A–1C (8.14)
Thus, our solution approach is:
■ arrange our system of linear equations in the form of Equation 8.11;
■ calculate the inverse of the coefficient matrix, A;
■ and then find the product of the inverse matrix, A–1, and the constant
matrix, C.
Let’s use Excel and solve our system of equations (Equation 8.10) for the current
in each loop.

■ 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

246 CHAPTER 8 Solving Simultaneous Equations

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.

Figure 8.12 Figure 8.13

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.

Figure 8.15 Figure 8.16

Finally, let’s add some clarity to our


program by adding an output table.
Type the labels I1, I2 and I3 into cells
D12:D14. Then map the correspon-
ding value in the X matrix to cells
E12:E14. Title and format the table.
Your completed spreadsheet should
look similar to Figure 8.17.

Now take a look at what happens to


the current in the circuit if we raise the
resistance value of R2. Let’s make it
very large compared to the other
resistors. Change the value of R2 to
1000 Ω . What happens to the value of
Figure 8.17 I2? The value of I2 drops to 0.009
ch08_mus80164.qxd 8/27/08 2:52 PM Page 247

CHAPTER 8 Solving Simultaneous Equations 247

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.

8.3 Tutorial: Solutions to Simultaneous Linear


Equations Using MATLAB
MATLAB is a very powerful tool in solving systems of linear equations, espe-
cially very large systems. Similar to the previous Excel example, we will use
matrix operations to find our solutions. Since MATLAB is designed to handle
matrix operations very efficiently and work with loop structures, we can easily
solve problems requiring millions of calculations. The solution technique out-
lined below is fairly efficient for relatively small systems of equations. For very
large systems of equations there are more efficient solution methods, such as
Gaussian elimination, which are beyond the scope of this text.

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

248 CHAPTER 8 Solving Simultaneous Equations

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

1 % Define the values of the resistors R1 - R5 in


Ohms;
2 R1=5;
3 R2=25;
4 R3=12;
5 R4=6;
6 R5=15;
7
8 %Define the value of the voltage sources, V1 V2
in Volts;
9 V1=110;
10 V2=45;
11
12 %Define the coefficient matrix A, Row by Row;
13 A1 = [1 -1 -1 0 0];
14 A2 = [0 0 1 -1 -1];
15 A3 = [R1 R2 0 0 0];
16 A4 = [0 R2 -R3 -R4 0];
17 A5 = [0 0 0 R4 -R5];
18 A = [A1;A2;A3;A4;A5]
19
ch08_mus80164.qxd 8/27/08 2:52 PM Page 249

CHAPTER 8 Solving Simultaneous Equations 249

20 %Define the constants matrix C;


21
22 C = [0; 0; V1; 0; V2]
23
24 %Calculate the currents (X matrix);
25
26 X = inv(A)*C

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.

Modify the resistors script as shown:

1 %Define the values of the resistors R1, R2, R4,


and R5 in Ohms;
2 R1=5;
3 R2=25;
4 R4=6;
5 R5=15;
6
7 %Define the value of the voltage sources, V1 V2
in Volts;
8 V1=110;
9 V2=45;
10
11 %Vary the resistance of R3 from 0.1-100 ohms and
find I
ch08_mus80164.qxd 8/27/08 2:52 PM Page 250

250 CHAPTER 8 Solving Simultaneous Equations

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.

8.4 Tutorial: Solving Nonlinear Simultaneous Equations


Using Excel
While there are many engineering solutions that require solving systems of lin-
ear equations, there are also many that require solving nonlinear equations. Non-
linear equations cannot be solved using the matrix operations described
previously. However, Excel has a powerful tool, Solver, that can be useful for
solving nonlinear (as well as linear) simultaneous equations.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 251

CHAPTER 8 Solving Simultaneous Equations 251

Use Solver to solve Equations 8.21 and 8.22: EXAMPLE 8.6

3x31 + 4x2 = 109 (8.21)


2x1 + 7x2 = 55 (8.22)

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

Now select the Solver tool


from the Analysis group
located in the Data tab on
the Ribbon, as shown in
Figure 8.21.

If you cannot locate the


Solver tool, use the fol-
lowing steps to add in the
tool. Click on the Office
Button in the upper left- Figure 8.20 Figure 8.21
hand corner of the screen
ch08_mus80164.qxd 8/27/08 2:52 PM Page 252

252 CHAPTER 8 Solving Simultaneous Equations

and select the Excel Options button located at the bottom of the menu, as shown
in Figure 8.22.

Next, select the Add-Ins button, as shown in Figure 8.23.

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

Figure 8.23 Figure 8.24

Finally, in the Add-Ins dialog box, check the Solver Add-in


box and then select OK, as shown in Figure 8.25. It may
take a few minutes for the Solver installation.

Solver uses an optimization algorithm to drive the value of a


single cell, known as the target cell, to a desired user set value
based on changing other cells, called adjustable cells (Solver
can handle up to 200 adjustable cells). In our case, we want to
drive the cell containing the sum of the squares of y1 and y2 (tar-
Figure 8.25
get cells) to zero by changing x1 and x2 (adjustable cells).

After selecting the Solver tool, in the Solver Parameters dia-


log box, set “Set Target Cell:” to D7; set the “Equal To:” option to Value of:,
and enter 0; set “By Changing Cells:” to B1:B2; and then select Solve, as
shown in Figure 8.26.

Solver comes up with a possible solution. The exact solution is x1 = 3 and x2 = 7.


Select OK to accept the solution.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 253

CHAPTER 8 Solving Simultaneous Equations 253

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

254 CHAPTER 8 Solving Simultaneous Equations

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

CHAPTER 8 Solving Simultaneous Equations 255

8.7 A two-link robot is shown in Figure P8.7.

Figure P8.7

The location of the robot’s hand is given by the following nonlinear


simultaneous equations:
x = L1 cos (θ1) + L1 cos(θ1 + θ2)
y = L1 sin(θ1) + L2 sin(θ1 + θ2)
If the length of the first robot link is L1 = 18 in and the length of the sec-
ond link is L2 = 12 in, use Excel to determine:
a. The angles θ2 and θ2 required to reach the point x = 14 in, y = 12 in.
Verify your answer by drawing the robot to scale (using a CAD sys-
tem). Note that there may be multiple solutions.
b. The angles θ1 and θ2 required to reach the point x = –14 in, y = 12 in.
Verify your answer by drawing the robot to scale (using a CAD sys-
tem). Note that there may be multiple solutions.
c. The angles θ1 and θ2 required to reach the point x = 29 in, y = 18 in.
Comment on the result.
8.8 A third link of L3 = 6 in is added to the robot in Problem 8.7, as shown in
Figure P8.8.

Figure P8.8

a. Determine the nonlinear simultaneous equations which describe the


hand position of the three-link robot.
b. Find the angles required to reach the points specified in parts a–c in
Problem 8.7. Again, check your answers with to-scale drawings.
ch08_mus80164.qxd 8/27/08 2:52 PM Page 256

256 CHAPTER 8 Solving Simultaneous Equations

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

CHAPTER 8 Solving Simultaneous Equations 257

8.12 Use MATLAB to calculate the currents I1 – I5 in the resistive network


shown in Figure P8.12. Use the following values for R1–R6 : 10 Ω, 2 Ω,
5 Ω, 10 Ω, 10 Ω, and 20 Ω. Assume the battery voltage is 30 V.

Figure P8.12

8.13 A variable voltage source replaces VB in the circuit shown in Figure


P8.12. Calculate and plot the currents, I1– I5, in the circuit above as a
function of VB as the voltage VB is increased from 0–100 V. Assume that
the voltage can be varied continuously and perform the calculation every
0.1 V. Use the values of the resistances given in Problem 8.12.
8.14 A variable voltage source replaces VB in the circuit shown in Figure
P8.12. Calculate and plot the voltage drop across each of the six resistors
in the circuit above as a function of VB as the voltage VB is increased from
0–100 V. Assume that the voltage can be varied continuously and perform
the calculation every 0.1 V. Use the values of the resistances given in
Problem 8.12.
8.15 A 1000-lb weight is supported by three cables, as shown in Figure P8.15.
Note that cable 3 is attached along the y-axis, at a distance of d in feet
from the origin O. Using concepts of vector analysis and particle equilib-
rium (usually taught in statics classes), three simultaneous equations can
be formulated. The tensile forces in the three cables, T1, T2, and T3, (in
pounds) are the independent variables:
0.348 T1 − 0.557 T2 = 0
⎛d⎞
−0.348 T1 − 0.239 T2 + ⎜ ⎟ T3 = 0
⎝ L⎠
⎛ 10 ⎞
0.870 T1 + 0.796 T2 + ⎜ ⎟ T3 − 1000 = 0
⎝ L⎠

where L = 10 2 + d 2 , the length of cable 3 in feet.


ch08_mus80164.qxd 8/27/08 2:52 PM Page 258

258 CHAPTER 8 Solving Simultaneous Equations

Write a MATLAB program to solve for the three tensile forces if d is


equal to:
a. 0 feet
b. 5 feet
c. 10 feet

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.

In this chapter you will:


■ develop an understanding of the concepts of differentiation and integration,
■ learn how to evaluate integrals numerically with Excel and MATLAB,
■ learn how to obtain an accurate solution by increasing the number of inter-
vals and converging to the exact solution, and
■ apply numerical integration to an application from statistics.

9.1 Concepts from Calculus


At the heart of calculus are two operations: differentiation and integration. Dif-
ferentiation involves finding the rate of change of a function. For example, sup-
pose we know the velocity of a car as a function of time. If we take the derivative
of the velocity with respect to time, then we get the acceleration: the rate of
change of velocity. On the other hand, suppose that the acceleration is the known
quantity (since acceleration is proportional to force, inexpensive instruments
called accelerometers are commonly used in testing). If we integrate the acceler-
ation with respect to time, we get the change in velocity. To get the velocity, we

259
ch09_mus80164.qxd 8/27/08 2:52 PM Page 260

260 CHAPTER 9 Numerical Integration

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)

We read these expressions as “acceleration equals the derivative of velocity with


respect to time,” and “velocity equals the integral of acceleration with respect to
time,” respectively. During your courses in calculus, you will learn how to find
derivatives and integrals, using a combination of rules, tabulated values, and
numerical methods. For example, if you need to find the derivative of a polyno-
mial, you use a rule that for each term of the polynomial, you reduce the expo-
nent by one and multiply the term by the original exponent. This is illustrated in
Equation 9.3:
d 3
y′ = ( x − 3x 2 + 5 ) = 3x 2 − 6 x (9.3)
dx
Note that y′ is read “y prime,” and the prime indicates differentiation with respect
to the independent variable (in this case, x). When you integrate a polynomial,
you increase the exponent of each term by one and divide the term by the new
exponent. So for example,

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

A derivative is defined as the rate of change of a function with respect to an input


variable. Graphically, the rate of change of y with respect to x is simply the slope
of the graph. In Equation 9.3, the derivative y′ was found to be 3x2 – 6x. We can
find the slope of the graph at any point using this expression. For example, at x =
1, the slope is equal to 3(1)2 – 6(1) = –3. This is shown graphically in Figure 9.2.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 261

CHAPTER 9 Numerical Integration 261

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

262 CHAPTER 9 Numerical Integration

x = 0 and there is a local minimum at x = 2. Analytically, we would need to find


the second derivative to determine whether the extreme points are maxima or
minima. If the second derivative is positive, then the point is a local minimum; if
the second derivative is negative, then the point is a local maximum. In this case,
the second derivative is y″ = 6x – 6. For x = 0, y″ = –6 and so the point is a local
maximum. For x = 2, y″ = +6, and the point is a local minimum.

While a derivative applies at a specific value of x, an integral can apply over an


interval of values of x. The form of the integral shown in Equation 9.4 is called
an indefinite integral, because there is no definite interval specified. When an
interval is specified, then the integral is called a definite integral. For example,
consider the integral of the function y = 3x2 – 6x for a range of x from 0 to 4. We
write this integral as shown in Equation 9.5:
4
∫ 0
( 3 x 2 − 6 x )dx (9.5)

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.

The graphical interpretation of a definite


integral is the area under a function’s curve
over a given interval. The integral evaluated
in Equation 9.6 is shown in Figure 9.3.
Areas under the curve and above the x-axis
are positive values of area, while areas
above the curve and below the x-axis are
negative values of area.

Determining integrals for polynomials and


many simple functions is straightforward,
and calculus textbooks and many other ref-
erence books contain extensive tables of
integrals. Sometimes, however, integrals
Figure 9.3 are encountered for which there is no
known closed-form solution. In other cases,
the function to be integrated is not given by an equation, but rather by a series of
measured values. In these cases, the integral may be approximated with the
numerical techniques demonstrated in the following tutorials.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 263

CHAPTER 9 Numerical Integration 263

9.2 Tutorial: Numerical Integration of Functions


Use the trapezoid rule and Excel to approximate the value of the integral of Equa- EXAMPLE 9.1
tion 9.4, which is repeated here:
4
∫ 0
( 3 x 2 − 6 x )dx (9.4)

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

Figure 9.4 Figure 9.5

Of course, the area of the trapezoid will equal


the exact area under the curve only if the curve
is a straight line. But by approximating the
curve by a number of short line segments, we
can obtain a value that is reasonably close to the
exact area, as illustrated in Figure 9.6.

There are other methods for calculating inte-


grals numerically. For example, Simpson’s rule
uses second-order polynomials to approximate
the curve shape. While this method generally
results in better accuracy with fewer intervals,
the trapezoid rule is easier to implement. As
computers have become faster, the need for
more efficient integration schemes has largely Figure 9.6
ch09_mus80164.qxd 8/27/08 2:52 PM Page 264

264 CHAPTER 9 Numerical Integration

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 B2, enter the formula for y, as shown in Figure 9.8.

Figure 9.7 Figure 9.8

Copy the formula to cells B3:B6, as shown in Figure 9.9.

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.

Figure 9.9 Figure 9.10

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

CHAPTER 9 Numerical Integration 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.

Figure 9.11 Figure 9.12

We can improve the accuracy of our


solution by increasing the number of
trapezoids. Let’s modify our spread-
sheet to double the number of intervals
from four to eight.
Figure 9.14
Delete the contents of the cells con-
taining the label “TOTAL” and the
sum of the areas. In column A, change
the x values so that they range from 0
to 4 by 0.5 increments, as shown in Figure 9.13
Figure 9.13.

Note that the formulas in columns B and C are still valid; they only need
to be copied to the cells below.

Double-click on the fill handle of cell B6, as shown in Figure 9.14.


This will cause the formula in cell B6 to be copied into the cells below,
until an empty cell is encountered to the left (column A). Figure 9.15

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

266 CHAPTER 9 Numerical Integration

The value of the integral is estimated to be 16.5. By increasing the number of


intervals from four to eight, we have reduced the error of the solution from 12.5%
to about 3%. Figure 9.16 shows the trapezoids that were used in this approxima-
tion. It is clear when comparing this figure to Figure 9.12 that increasing the num-
ber of intervals has resulted in a better approximation of the area under the curve.

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.

A flowchart of the function is shown in Figure 9.17. We will begin by inputting


the number of intervals k. There will be k + 1 points. The first point’s coordinates,
x(1) and y(1), are defined before entering the loop. The first pass through the loop,
ch09_mus80164.qxd 8/27/08 2:52 PM Page 267

CHAPTER 9 Numerical Integration 267

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.

Create a new MATLAB function as follows:

1 function SUM = intexample(k)


2 % Computes the integral of y=3x^2-6x for
x = 0 to 4
3 % k = Number of intervals
4
5 % Initialize the SUM (value of the integral)
6 SUM = 0;
7 %Calculate the increment value Figure 9.17
8 increment = 4/k;
9 %Set the values for the first endpoint
10 x(1) = 0;
11 y(1) = 0;
12 % Calculate x and y values at the end of each
interval
13 % Calculate the area for the interval, add to
SUM
14 for i = 2:(k+1)
15 x(i) = x(i-1) + increment;
16 y(i) = 3*(x(i)^2)-6*x(i);
17 SUM = SUM + .5*(y(i) + y(i-1))*(x(i) -
(i-1));
18 end

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

268 CHAPTER 9 Numerical Integration

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

We can now evaluate our function for various values of k.

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

CHAPTER 9 Numerical Integration 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:

>> format long

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

270 CHAPTER 9 Numerical Integration

Notice how fast MATLAB performs these calculations—only a second or two on


a moderately fast PC for 10,000 passes through the loop. Remember that if you
put in a very large number and get tired of waiting for the results, you can cancel
the operation by pressing Ctrl+C.

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

CHAPTER 9 Numerical Integration 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.

Create a new MATLAB function as follows:

1 function SUM = normdist(limit, k)


2 lower = -limit;
3 upper = limit;
4 inc = (upper-lower)/k;
5 SUM = 0;
6 x(1) = lower;
7 y(1) = 1/sqrt(2*pi)*exp(-x(1)^2/2);
8 for i = 2:(k+1)
9 x(i) = x(i-1)+inc;
10 y(i) = 1/sqrt(2*pi)*exp(-x(i)^2/2);
11 SUM = SUM + .5*(y(i) + y(i-1))*(x(i) -
x(i-1));
12 end
ch09_mus80164.qxd 8/27/08 2:52 PM Page 272

272 CHAPTER 9 Numerical Integration

Save the function as “normdist” and execute it for different values of limit
and k:

>> format long

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

CHAPTER 9 Numerical Integration 273

Make the changes as indicated to the function normdist (note that lines 6–14
are unchanged):

1 function SUM = normdist(Z)


2 % Calculates the % of population with values
less than Z
3 lower = -6;
4 upper = Z;
5 k = 1000;
6 inc = (upper-lower)/k;
7 SUM = 0;
8 x(1) = lower;
9 y(1) = 1/sqrt(2*pi)*exp(-x(1)^2/2);
10 for i = 2:(k+1)
11 x(i) = x(i-1)+inc;
12 y(i) = 1/sqrt(2*pi)*exp(-x(i)^2/2);
13 SUM = SUM + .5*(y(i) + y(i-1))*(x(i) -
x(i-1));
14 end

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

274 CHAPTER 9 Numerical Integration

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.

Evaluate the Z-value of –1.333 using the function normdist:

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

CHAPTER 9 Numerical Integration 275

Now consider the upper limit:


2.010 − 1.998
Z= = 2.000 (9.10)
0.006
Therefore, the upper limit is 2.000 standard deviations above the mean.

Evaluate the Z-value of 2.000 using the function normdist:

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

>> normdist(2) - normdist(-1.333)


ans =
0.8860

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.

In this example, we have evaluated an integral for which there is no simple


closed-form solution. Because of the importance of this particular integral in sta-
tistics, which is called the cumulative density function for a normal distribution,
many reference books have tables of its values for values of Z. Excel has built-in
functions for many statistical calculations, including NORMSDIST, which eval-
uates the cumulative density function for a given value of Z.

Enter this formula in a cell in Excel to verify the MATLAB solution:


“=NORMSDIST(2) - NORMSDIST(-1.333)”.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 276

276 CHAPTER 9 Numerical Integration

Figure 9.21

9.3 Tutorial: Numerical Integration of Measured Data


In the previous section, we integrated functions for which an equation was given.
Often, we need to perform integration of a function for which an equation is not
known, but rather is defined by a series of measured data points. In the following
example, we will integrate measured acceleration data to obtain velocity and
position values.

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.

Plot acceleration versus time, as shown in Figure 9.23.


ch09_mus80164.qxd 8/27/08 2:52 PM Page 277

CHAPTER 9 Numerical Integration 277

Table 9.1 Acceleration of Robot


Time, Accel., Time, Accel., Time, Accel., Time, Accel.,
sec cm/s2 sec cm/s2 sec cm/s2 sec cm/s2

0.1 99 1.1 63 2.1 0 3.1 –2


0.2 109 1.2 11 2.2 –27 3.2 3
0.3 104 1.3 2 2.3 –48 3.3 –2
0.4 113 1.4 1 2.4 –51 3.4 4
0.5 110 1.5 –2 2.5 –58 3.5 0
0.6 138 1.6 3 2.6 –53 3.6 –122
0.7 123 1.7 1 2.7 –57 3.7 –218
0.8 119 1.8 0 2.8 –51 3.8 –211
0.9 125 1.9 1 2.9 –31 3.9 –220
1.0 127 2.0 –1 3.0 1 4.0 –203

Figure 9.22 Figure 9.23

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

278 CHAPTER 9 Numerical Integration

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.

In column C, enter a formula to calculate the area of the first trapezoidal


region, as shown in Figure 9.24. Note that this value is entered on the row cor-
responding to t = 0.1 seconds. The calculated area represents the change of veloc-
ity from t = 0 to t = 0.1 seconds. The units of the area will be the units of the base
of the trapezoid multiplied by the units of the height, or
⎛ cm ⎞ cm
(second) ⎜
⎝ second 2 ⎟⎠ second
=

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.

Plot the velocity versus time, as shown in Figure 9.26.

Figure 9.24 Figure 9.25

Figure 9.26
ch09_mus80164.qxd 8/27/08 2:52 PM Page 279

CHAPTER 9 Numerical Integration 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.

We also see that the final velocity is approximately zero.

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.

Plot the position, as shown in Figure 9.31.

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

280 CHAPTER 9 Numerical Integration

Figure 9.30

Figure 9.31
ch09_mus80164.qxd 8/27/08 2:52 PM Page 281

CHAPTER 9 Numerical Integration 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

9.2 Evaluate the following integrals numerically in Excel, using 2, 4, 8, and


16 intervals. Comment on your results.

a. ∫ 0
sin␪ d␪

2
b. ∫ 0
e x dx

4
c. ∫ 0
( x 3 + 3 x 2 − 20 )dx

9.3 Write a MATLAB m-file to evaluate the following integral:


2
∫ 0
4 − x 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

282 CHAPTER 9 Numerical Integration

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

Table P9.7 Acceleration of Rocket


Time, s Acceleration, m/s2
0 0
0.5 30.1
1 32.4
1.5 33.6
2 35.1
2.5 38.7
3 34.2
3.5 18.1
4 –2.4
4.5 –9.8
5 –9.8
a = –9.8 m/s2 for remainder of flight

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

where F is force and x is the distance travelled. Use numerical integration


of the curve developed in part b to determine the work done by the robot’s
motor. Report your answer in the appropriate units.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 283

CHAPTER 9 Numerical Integration 283

9.9 In Chapter 5, we plotted the free vibration of a spring-mass-damper sys-


tem. Often, we want to analyze the response of the system to forced vibra-
tions. This system is illustrated in Figure P9.9.

Figure P9.9

The displacement y at any time t1 is calculated from Duhamel’s integral:


1 t1
y( t1 ) = ∫
m␻ D 0
F ( t )e − ␰␻ ( t1 − t ) sin[␻ D ( t1 − t )]dt

where:
k
␻= , the natural frequency
m
␻ D = ␻ 1 − ␰ 2 , the damped natural frequency

␰ = the damping ratio, which varies from 0 (undamped) to 1


(criticcally damped)

F(t) = the forcing function (force as a function of time)


Write a MATLAB function to find the displacement at any value of time
t1 for the following parameters:

m = 1 kg, k = 100 N/m, and ξ = 0.1

and a forcing function of


F = 9.8 N
The forcing function here is simply the weight of the mass. The physical
interpretation of the problem is that initially, the mass is being held at
rest, at the position where the spring is at its free length. At time t = 0, the
mass is dropped, hence the force of the weight is applied instantaneously.
ch09_mus80164.qxd 8/27/08 2:52 PM Page 284

284 CHAPTER 9 Numerical Integration

Use 1,000 increments of time from 0 to t1. Consider writing a separate


MATLAB function for the force as a function of time, so that it can be
changed easily in later problems.
Check your function with these values:
y(t1 = 1 s) = 0.131 m
y(t1 = 5 s) = 0.097 m
Note that as time increases, the displacement approaches the equilibrium
position, which is calculated as the weight divided by the spring stiffness.
9.10 Write a MATLAB file which utilizes the function written in Problem 9.9
to calculate and plot the displacement for values of time from 0 to 5 sec-
onds. Use 1,000 intervals of time. Comment on the shape of the curve.
Repeat for values of the damping ratio of 0 (undamped) and 0.5.
9.11 Repeat Problem 9.10 with a forcing function that applies the weight lin-
early over a 2-second interval instead of instantaneously, as illustrated in
Figure P9.11. Comment on your results.

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

CHAPTER 9 Numerical Integration 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.

Optimization is the mathematical process of determining the maximum or mini-


mum value that a mathematical function can take, and the values of the inde-
pendent variables that yield these maximum or minimum values. In very simple
cases, where there are only a few independent variables, and there is no limit on
the values that the independent variables can take, principles of calculus can be
readily used to find exact solutions to optimization problems manually. When
there are large numbers of independent variables, or when there are significant
restrictions placed on the values that the independent variables can take, algo-
rithmic methods must be employed. In this chapter, we will examine both the for-
mulation of optimization problems and the application of prewritten tools in
MATLAB and Excel for the computational solution of optimization problems.
287
ch10_mus80164.qxd 8/27/08 2:52 PM Page 288

288 CHAPTER 10 Optimization

In this chapter, you will:


■ learn to develop an optimization problem in standard form,
■ learn the difference between linear and nonlinear optimization problems,
■ learn how to solve optimization problems in MATLAB using the
fminsearch and fminbnd functions, and
■ learn how to solve optimization problems in Excel using the Solver tool.

10.1 Engineering Optimization


In order to motivate the application of mathematical optimization in engineering
design, we will examine a typical engineering design problem. An engineer is
asked to design a beam to support a 500 lb load applied 10 feet from a fixed sup-
port, with less than 1 inch of deflection under the load. A schematic is shown in
Figure 10.1.

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.

Figure 10.1 Figure 10.2

Based on knowledge of mechanics of materials, the engineer determines that the


deflection of the tip of the bar under the 500-lb weight is as follows:
64Wl 3
␦= (10.1)
3␲E ( D 4 − d 4 )
ch10_mus80164.qxd 8/27/08 2:52 PM Page 289

CHAPTER 10 Optimization 289

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)
3␲E ( 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.

However, as engineers, we are not simply seeking an acceptable solution to the


design problem; we want to create a design solution that is the best solution,
given a criterion. When given free choice, as in our example, we do not want to
arbitrarily specify any of our design variables; we want to carefully choose all of
them to yield the best solution possible. This is called design optimization.

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.

Looking at Equation 10.4 from a mathematical standpoint, the volume V can


reach a minimum value of zero when D and d are set equal to each other. How-
ever, in our design case, we have a number of physical limits that must be placed
on the possible values that our variables can take. For instance, we know that the
ch10_mus80164.qxd 8/27/08 2:52 PM Page 290

290 CHAPTER 10 Optimization

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
3␲E ( 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.

10.2 Formulating an Optimization Problem


To summarize and formalize the procedure we used in our example, the follow-
ing steps should be used to formulate a problem in the standard form used in the
mathematics of optimization.
■ Step 1: Identify the independent variables that must be assigned values. In
engineering optimization, these are called design variables. There can be
any number n of them, and we will denote these variables x1, x2, x3, ..., xn.
■ Step 2: Identify the objective function, or the quantity that will be mini-
mized or maximized in the optimization. In engineering, this is the criterion
that will be used to judge the “best” solution:
y = f (x1, x2, x3, ..., xn ) (10.6)
ch10_mus80164.qxd 8/27/08 2:52 PM Page 291

CHAPTER 10 Optimization 291

■ Step 3: Identify any restrictions on the independent (design) variables and


write these as equality or inequality equations. These are called the con-
straints, and each will be in one of the forms shown:
gi(x1, x2, x3, ..., xn) = Ai (10.7)
or:
gi(x1, x2, x3, ..., xn) ≤ Ai (10.8)
or:
gi(x1, x2, x3, ..., xn) ≥ Ai (10.9)
where Ai is a constant.

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.

Once we have our optimization problem in a standard form, it is useful to clas-


sify the type of optimization problem we have. This will help guide us in our
selection of the best solution method for our problem.
■ Unconstrained or Constrained: An unconstrained optimization problem is
one in which there are no restrictions on design variables. Therefore, there
would be no constraint equations. If there are any restrictions on design
variables (even one single constraint equation), the problem is classified as
a constrained optimization problem.
■ Linear or Nonlinear: A linear algebraic equation is one in which the inde-
pendent variables appear either alone or multiplied by a constant; it would
take the form of Equation 10.10:
f (x1, x2, x3, ..., xn) = a2x1 + a2x1 ... + anxn (10.10)
where the values of ai are constants (including possibly 0 or 1). If the
objective function and all of the constraint equations take the form of linear
algebraic equations, we classify the problem as a linear optimization prob-
lem. If the objective function or any of the constraint equations contain
even a single nonlinear element (e.g., a design variable raised to a power,
like x 13, a trigonometric function of a design variable, like cos(πx2), etc.),
ch10_mus80164.qxd 8/27/08 2:52 PM Page 292

292 CHAPTER 10 Optimization

the problem is classified as a nonlinear optimization problem. Note that for


constraint equations, the equal sign (=) in Equation 10.10 could be replaced
with an inequality (≤, ≥), without affecting the classification.

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.

10.3 Solution of an Optimization Problem


In this section, we will examine the solution of the various classifications of opti-
mization problems. While we will consider only simple examples, these exam-
ples will help us select a solution technique and better understand the solutions
that we obtain when we proceed to more complex problems. We will consider
nonlinear unconstrained problems, linear constrained problems, and nonlinear
constrained problems.

10.3.1 Nonlinear Unconstrained Optimization


Recall from Section 10.2 that a nonlinear unconstrained optimization problem
consists of a nonlinear objective function to be maximized or minimized, and no
restrictions on the value that the design variables can take (i.e., no constraint
equations). The lack of constraint equations makes this the simplest type of opti-
mization problem to analyze.

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

CHAPTER 10 Optimization 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

294 CHAPTER 10 Optimization

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

or minimum. (While there is a mathematical technique from calculus that uses


second derivatives to determine whether a given point is a minimum or maxi-
mum, as mentioned in Chapter 9, we will concentrate on the graphical solution
here.)

To examine this technique further, consider the single-variable optimization


problem associated with the objective function:
Minimize y = x3 –2x2 + x + 1 (10.13)
Finding the equation for the slope of this function yields:
dy
slope = = 3x 2 − 4 x + 1 (10.14)
dx
Finding the roots of this equation yields points of zero slope at x = 1⁄3 and x = 1.
Are these points minima or maxima? To examine this, we will look at the plot of
the function, plotted over the convenient range –0.2 ≤ x ≤ 1.5, as shown in Fig-
ure 10.6.

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

CHAPTER 10 Optimization 295

These results introduce the concept of the local mini-


mum and local maximum. The point x = 1 corresponds to
a minimum value of sorts; it corresponds to the lowest
point in the small “local” region surrounding the point.
If the plot of Figure 10.6 represented actual terrain, and
we were hikers positioned at the point x = 1, we would
look at our surroundings and determine that we were
indeed at the lowest point of the hike. Without the abil-
ity to stand back and look at the “big picture,” we would
be ignorant of the fact that much lower points exist, at
distances far from our location. Using this analogy, the
point x = 1 is called a local minimum, while the true min- Figure 10.6
imum value is called the global minimum. The same
argument can be made for the point x = 1⁄3, which is
called a local maximum.

Yet another property of nonlinear unconstrained optimization can be examined


with one additional example:
Minimize y = sin(x) (10.15)
Looking at the slope equation:
dy
slope = = cos( x ) (10.16)
dx
yields an interesting result. The slope equation is equal to zero at an infinite num-
ber of points:
␲ 3␲ 5␲ 7␲ 9␲
x= , , , , ,… (10.17)
2 2 2 2 2
This is confirmed by examination of the plot of the function, as shown in Figure
10.7.

Figure 10.7
ch10_mus80164.qxd 8/27/08 2:52 PM Page 296

296 CHAPTER 10 Optimization

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.

10.3.2 Linear Constrained Optimization


In Section 10.2, we classified optimization problems consisting of a linear alge-
braic objective function and linear algebraic constraint equations as linear con-
strained optimization problems. The nature of the solution of these types of
problems will be examined through four example problems.

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

CHAPTER 10 Optimization 297

Examining Figure 10.8 shows that there is a


closed region, bounded on all sides by constraint
equations, that contains all of the allowable values
for our design variables. The region of allowable
values is known as the feasible region; in this
example, where the feasible region takes the form
of a closed polygon, bounded on all sides by con-
straint equations, we call this a closed feasible
region or a bounded feasible region. While not all
mathematical optimization problems will involve
closed feasible regions, many engineering prob-
lems will, since there are generally physical con-
straints that place limits on our possible values for
design variables. When the set of constraints
results in a closed feasible region, there is an inter-
Figure 10.8
esting general result for the solution.

To demonstrate the nature of the solution, we will


plot our objective function at various combina-
tions of allowable design variables. The linear
objective function takes the form of the “contour
plot,” as shown in Figure 10.9.

At each “contour,” the value of the objective func-


tion is the same everywhere along the line; the
minimum value of the objective function occurs at
the intersection with the upper-left boundary of
the feasible region (where x1 = 3, x2 = 4, and y = 1,
and the contours take the form of parallel lines that
increase in value as they proceed down and to the
right across the feasible region. The maximum
value occurs at the lower-right boundary of the
feasible region, where x1 = 4.5, x2 = 1, and y =
Figure 10.9
11.5, which is the solution to our maximization
problem.

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

298 CHAPTER 10 Optimization

rithm that is often employed to solve such problems is called the simplex algo-
rithm.

To examine another property of the solution of a linear constrained optimization


problem, we can consider the following problem, which duplicates the con-
straints of our previous example but has a different objective function.

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.

The minimum value occurs at


the lower-left boundary of the
feasible region, where x1 = 3,
x2 = 1, and y = 14. Notice that
the objective function has the
same slope as the bounding
constraint equation at the
right-hand boundary of the
feasible region; therefore, the
maximum value of the objec-
tive function occurs at every
Figure 10.10 point along the boundary of
the feasible region that falls
along the line 4x1 + 2x2 = 20. This includes two of the corner points of the feasi-
ble region (the point x1 = 4.5, x2 = 1, and the point x1 = 3, x2 = 4), as well as the
points along the boundary between these two points. This indicates that while the
extreme values of the function do occur at corner points, the solution to a linear
constrained optimization problem may not be unique; more than one corner point
may provide identical optimal values for an objective function, as may all of the
points along a constraint line. As we move to more complex problems and
employ computer-based algorithmic solutions, bear in mind that the solution that
we find may not be the only possible solution to the problem, it is simply one of
the solutions that yields the optimum value.
ch10_mus80164.qxd 8/27/08 2:52 PM Page 299

CHAPTER 10 Optimization 299

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.

In this case, the feasible region is not a closed poly-


gon; since there are no upper bounds on the design
variables, the region extends to infinity in both direc-
tions. Such a feasible region is known as an open fea-
sible region or an unbounded feasible region. If we
overlay our objective function contours on this feasi-
ble region, as in Figure 10.12, we can conclude that
in this example, the maximum value is unbounded,
yielding a solution at infinity.

This two-variable example demonstrates another


general property of the solution to linear constrained
optimization problems; in problems with an open
feasible region, the solution to the problem may be
unbounded. While the solution may be unbounded, it Figure 10.11
may also simply be located at one of the corner points
of the open feasible region; this can be demonstrated
by considering the minimization version of our
example:

Minimize
y = 4x1 + 2x2
subject to:
x1 ≥ 3
x2 ≥ 1 (10.21)
ch10_mus80164.qxd 8/27/08 2:52 PM Page 300

300 CHAPTER 10 Optimization

By examining Figure 10.12 again, we can conclude


that the solution to this problem occurs at the corner
point of the feasible region, where x1 = 3, x2 = 1, and
y = 14. Therefore, we can conclude that while the fea-
sible region is open, the optimal solution may still
occur at a corner point.

To summarize the main conclusions we can draw


from these examples:
■ The solution to a linear constrained optimiza-
tion problem with a closed feasible region will
occur at a corner point of the feasible region.
■ The solution to a linear constrained optimiza-
tion problem with an open feasible region will
either occur at a corner point of the feasible
region or will be unbounded.
Figure 10.12 ■ The solution to a constrained linear optimiza-
tion problem may not be unique; more than one
corner point may yield the same optimal value
for the objective function.
These conclusions were based on two-variable examples, but can be generalized
to any number of variables and constraint equations. As we move on to more
complex problems that do not lend themselves to graphical solutions, we can use
these conclusions to evaluate and interpret the results of our computational solu-
tions.

10.3.3 Nonlinear Constrained Optimization


Of the classifications we established in Section 10.2, the most complex class of
problems we may confront are the nonlinear constrained optimization problems.
Recall that if even one of the constraint equations or the objective function con-
tain even a single nonlinear term, then the problem is classified as nonlinear.

The nature of nonlinear optimization problems is that it is not possible to predict


where the solution point might lie; it must be contained in the feasible region, but
no other generalization can be made. The solution might lie:
■ at a corner point of the feasible region,
■ along the boundary line of the feasible region, or
■ somewhere in the interior space of the feasible region.
ch10_mus80164.qxd 8/27/08 2:52 PM Page 301

CHAPTER 10 Optimization 301

In addition, the generalizations we made for nonlinear unconstrained optimiza-


tion problems in Section 10.3.1 still apply:
■ the solution approach may lead to local extrema rather than global extrema
■ solutions may not be unique (i.e., more than one point may yield the same
optimum value for the objective function)
Because of their unpredictable nature, complex algorithmic solutions are often
required to solve this class of problems, and the results of these solution algo-
rithms must be carefully checked and interpreted before they are used in design.

10.4 Solution of an Optimization Problem Using MAT-


LAB
The standard MATLAB function toolbox (funfun toolbox) contains two functions
for solution of optimization problems:
■ fminseach, for performing nonlinear unconstrained multivariable optimiza-
tion
■ fminbnd, for solving a particular type of nonlinear constrained optimization
problems containing a single design variable
These functions are available in most standard MATLAB installations. Note that
MATLAB also has an Optimization Toolbox available that contains a variety of
more powerful tools used to solve a wider class of optimization problems. This
toolbox is not included with standard MATLAB installations.

10.4.1 Tutorial: Nonlinear Unconstrained Optimization Using


fminsearch

Minimization of a Function of a Single Variable EXAMPLE 10.1

Determine the value of x that minimizes the function:


y = 3x4 + x3 cosπx (10.22)

■ 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

302 CHAPTER 10 Optimization

Save the function using the default name “objfunc”.

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:

>> fplot(‘objfunc’,[-1 1])

The plot window shown in Figure 10.13 appears.

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

CHAPTER 10 Optimization 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.

As it turns out, this is a “well-conditioned” problem, without many of the pitfalls


associated with optimization by computational algorithm. As the plot shows, the
function has one unique minimum value. To demonstrate this, repeat the opti-
mization with different initial guesses, such as:

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

Minimization of a Function of a Single Variable with Local Minima EXAMPLE 10.2

Determine the value of x that minimizes the function:


y = 3x4 + x3 cos 10πx (10.23)

■ 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

304 CHAPTER 10 Optimization

Save the function.

We will again generate a plot of the function, to determine the value of the ini-
tial guess:

>> fplot(‘objfunc’,[-1 1])

The plot window shown in Figure 10.14 appears.

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

CHAPTER 10 Optimization 305

Evaluate the objective function at this point:

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

Minimization of a Multivariable Function EXAMPLE 10.3

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

306 CHAPTER 10 Optimization

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=fminsearch(‘objfunc’,[0 0 0])

xmin =
0.5000 0.6300 0.3855

Evaluate the objective function at this point:

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

Is this the global minimum? In actuality, there is no way to determine whether or


not we have reached a true minimum. One test we can use to increase our confi-
dence in the result is to rerun the fminsearch function with different initial
guesses. For example, try:

>> xmin=fminsearch(‘objfunc’,[-10 -10 -10])

xmin =
0.5000 0.6299 0.3854
ch10_mus80164.qxd 8/27/08 2:52 PM Page 307

CHAPTER 10 Optimization 307

We can also try, for example:

>> xmin=fminsearch(‘objfunc’,[50 -50 50])

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.

10.4.2 Tutorial: Nonlinear Constrained Optimization Using fminbnd


The fminbnd function can be used to solve nonlinear constrained optimization
problems, subject to the following restrictions:
■ The problem is restricted to a single design variable x
■ The constraints may only be used to set limits on the design variable x (i.e.,
xmin ≤ x ≤ xmax)
The following example will demonstrate the use of this function.

Minimization of a Function of a Single Variable EXAMPLE 10.4

Determine the value of x that minimizes the function:


y = 3x4 + x 3 cos 10π x (10.25)
in the range 0.8 ≤ x ≤ 1.0.

■ 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);

Save the function.

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

308 CHAPTER 10 Optimization

>> xmin=fminbnd(‘objfunc’,.8,1)

xmin =
0.8910

Evaluate the objective function at this point:

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

10.5 Solution of an Optimization Problem Using Excel


The Excel Solver add-in is a powerful tool for solving all classes of optimization
problems, including nonlinear constrained optimization. If Solver has been
loaded on your computer, it should appear under the Data tab, as shown in
Figure 10.15.

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.

10.5.1 Tutorial: Unconstrained Optimization Using Excel

EXAMPLE 10.5 Unconstrained Minimization of a Function of a Single Variable


Determine the value of x that minimizes the function:
y = 3x4 + x3 cos πx (10.26)
ch10_mus80164.qxd 8/27/08 2:52 PM Page 309

CHAPTER 10 Optimization 309

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

Figure 10.16 Figure 10.17

In cell B2, we will enter our objective function, referencing


cell B1 as the design variable in our equation, as shown in
Figure 10.18.

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

The Solver Parameters dialog box will open. Click on the


selection icon next to the “Set Target Cell:” box, as shown in
Figure 10.20.

Click on cell B2 (where the objective function equation is


located) to select it, as shown in Figure 10.21.

Since our problem is set up as a minimization problem, click


to set the “Equal To:” option to Min, as shown in Figure
10.22. Figure 10.20
ch10_mus80164.qxd 8/27/08 2:53 PM Page 310

310 CHAPTER 10 Optimization

Figure 10.21

Click the selection icon next to the “By Changing Cells:” box, as shown in Fig-
ure 10.23.

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

Figure 10.24 Figure 10.25

Click OK to accept the solution, as shown in Figure 10.26.


ch10_mus80164.qxd 8/27/08 2:53 PM Page 311

CHAPTER 10 Optimization 311

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.

Figure 10.26 Figure 10.27

These results correspond with those previously obtained using MATLAB.

Minimization of an Unconstrained Multivariable Function EXAMPLE 10.6

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

312 CHAPTER 10 Optimization

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

This will select all of the cells containing the


design variables.

Click Solve, and then click OK to accept the


solution. The results are shown in Figure 10.31.

These results are identical to those obtained


Figure 10.31
using MATLAB.

10.5.2 Tutorial: Constrained Optimization Using Excel

EXAMPLE 10.7 Minimization of a Constrained Nonlinear Function


Solve the following optimization problem:

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

CHAPTER 10 Optimization 313

Add the second constraint


equation in cell B9, as shown
in Figure 10.33.

Initiate Solver under the


Data tab. The values set in
the previous example should
be the defaults (cell B6 for
the target, Min option, cells
B2:B4 to be changed). If they Figure 10.33 Figure 10.34
are not, reset these values.
We must now add the constraint equations. Next to the “Subject to the Con-
straints:” box, click the Add button, as shown in Figure 10.34.

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

From the pull-down menu, set the equation to be a “≥”


inequality, as shown in Figure 10.36.

Note that in addition to the equality/inequality constraints,


there are options to constrain values to be integers (int) or to
have values of only zero or one (bin, for binary).
Figure 10.36
In the “Constraint:” box, type the value of the right-hand
side of the constraint equation (in this case, 4). Click OK, as
shown in Figure 10.37.

Figure 10.37
ch10_mus80164.qxd 8/27/08 2:53 PM Page 314

314 CHAPTER 10 Optimization

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.

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

As was discussed in the previous section, we have no particular way of knowing


whether this is a global optimum, or merely a local optimum. One check we can
employ is to restart the algorithm at a different initial guess, and see if we arrive
at the same solution. To do this, manually modify the values in cells B2, B3, and
B4, as shown in Figure 10.41.

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.

Figure 10.40 Figure 10.41 Figure 10.42


ch10_mus80164.qxd 8/27/08 2:53 PM Page 315

CHAPTER 10 Optimization 315

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.

Minimization of a Constrained Linear Function EXAMPLE 10.8

Solve the following optimization problem:


Minimize
y = 3x1 + x2 + 5x3
subject to:
x1 + 2x2 ≥ 4
x1 – x3 ≤ 0.1 (10.29)

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

To begin, modify the spreadsheet to include the new objective function in


cell B6, as shown in Figure 10.43.

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.

The Solver Options dialog box


will open. Click the check box
next to the Assume Linear Model
option, as shown in Figure
10.45. Note that there are many
other options we could adjust; in
advanced optimization work,
adjustment of these other options
might be required. We will use the
default values in our work. Figure 10.44 Figure 10.45
ch10_mus80164.qxd 8/27/08 2:53 PM Page 316

316 CHAPTER 10 Optimization

Click OK to close the dialog box and click Solve to execute


the solution. The algorithm will execute, and the message
shown in Figure 10.46 results.

The message indicates to us that the algorithm did not con-


verge; this is an indication that our problem may be formu-
Figure 10.46 lated such that the feasible region is unbounded, as is the
minimum.

Click OK; the variables will be changed to new values, but the “solution” has
no meaning.

EXAMPLE 10.9 Minimization of a Constrained Linear Function (continued)


Solve the following optimization problem:

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

CHAPTER 10 Optimization 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.

With the spreadsheet set up as in Example 10.8, initiate Solver.


Click the Options button. In the Solver Options dialog box,
click the Assume Non-Negative check box, as shown in Figure
10.47.

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

318 CHAPTER 10 Optimization

■ Portland, OR
The weekly production capacity and production cost for their top-grade adhesive
at each plant is shown in Table 10.1.

Table 10.1 Capacity and Production Costs at Adhesive Plants


Plant Production Capacity Production Cost

New Orleans 18,000 gallons/week $0.71 per gallon


Gary 22,000 gallons/week $0.98 per gallon
Buffalo 14,000 gallons/week $1.12 per gallon
Portland 10,000 gallons/week $1.29 per gallon

Three major customers place regular weekly orders; their locations, standard
orders, and negotiated pricing are shown in Table 10.2.

Table 10.2 Demand and Pricing at Customer Locations


Customer Location Order Price

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.

Table 10.3 Shipping Costs


To\From: New Orleans Gary Buffalo Portland

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

CHAPTER 10 Optimization 319

■ Solution

■ Step 1: Identification of the design variables: The “design” in this case is


the identification of how much adhesive should be produced at each plant
and sold to each customer. Therefore, there are 12 total design variables:
x1: Volume produced in New Orleans and sold to MMI
x2: Volume produced in New Orleans and sold to WCC
x3: Volume produced in New Orleans and sold to TMC
x4: Volume produced in Gary and sold to MMI
x5: Volume produced in Gary and sold to WCC
x6: Volume produced in Gary and sold to TMC
x7: Volume produced in Buffalo and sold to MMI
x8: Volume produced in Buffalo and sold to WCC
x9: Volume produced in Buffalo and sold to TMC
x10: Volume produced in Houston and sold to MMI
x11: Volume produced in Houston and sold to WCC
x12: Volume produced in Houston and sold to TMC
■ Step 2: Creation of the objective function: The goal of this production plan-
ning problem is to maximize profits; taking into account the price, produc-
tion cost, and shipping costs per gallon, the equation for profit can be
written as follows:
Maximize
P = (2.00 – 0.71 – 0.22)x1 + (2.75 – .71 – .26)x2 + (3.00 – .71 – .12)x3
+(2.00 – .98 – .12)x4 + (2.75 – .98 – .20)x5 + (3.00 – .98 – .18)x6
+ (2.00 – 1.12 – .16)x7 + (2.75 – 1.12 – .39)x8 + (3.00 – 1.12 – .21)x9
+ (2.00 – 1.29 – .17)x10 + (2.75 – 1.29 – .11)x11 + (3.00 – 1.29 – .20)x12

(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

320 CHAPTER 10 Optimization

■ Step 3: Identification of constraints: Each plant is limited in capacity;


therefore, there are four constraint equations for manufacturing limitations.
For example, since the New Orleans plant can produce no more than
18,000 gallons, we can write:
x1 + x2 + x3 ≤ 18,000 (10.33)
Similarly:
x4 + x5 + x6 ≤ 22,000 (10.34)
x7 + x8 + x9 ≤ 14,000 (10.35)
x10 + x11 + x12 ≤ 10,000 (10.36)
In addition, all customer orders must be met; for example, since MMI has placed
orders for 26,000 gallons, we can write:
x1 + x4 + x7 + x10 = 26,000 (10.37)
Similarly:
x2 + x5 +x8 + x11 = 13,000 (10.38)
x3 + x6 + x9 + x12 = 11,000 (10.39)
The only other constraints are the implied constraints that all of the design vari-
ables (which represent production quantities) must be non-negative:
x1, ..., x12 ≥ 0 (10.40)
Since this is a multivariable constrained optimization problem, Excel is our com-
putational tool of choice for this problem. We can create a spreadsheet, with for-
mulas entered for our objective function and constraints. Create the spreadsheet,
using the format and formulas shown in Figure 10.49. Enter zeros at the ini-
tial guesses for the design variables.

Figure 10.49

Initiate Solver and set the parameters, as shown in Figure 10.50.

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

CHAPTER 10 Optimization 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.50 Figure 10.51

Execute Solver. The solution is shown in Figure 10.52.

Figure 10.52

The optimization indicates that the following production plan is optimal:


■ Produce 18,000 gallons at the New Orleans plant and distribute it as
follows:
■ Supply 7,000 gallons to West Coast Corp.
■ Supply 11,000 gallons to Texas Manufacturing Co.
■ Produce 22,000 gallons at the Gary plant and distribute it as follows:
■ Supply 16,000 gallons to Midwest Manufacturing, Inc.
■ Supply 6,000 gallons to West Coast Corp.
■ Produce 10,000 gallons at the Buffalo plant, and supply all of it to Midwest
Manufacturing, Inc.
ch10_mus80164.qxd 8/27/08 2:53 PM Page 322

322 CHAPTER 10 Optimization

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

CHAPTER 10 Optimization 323

Use Excel Solver to determine the objects that should be retrieved


within the 4-minute time limit in order to maximize the team’s score.
Hint: The independent variables in this problem will be the number of
each object that is retrieved. Since there is only one of each, the value of
each independent variable will be either one or zero. Therefore, the con-
straints will be that each value is less than or equal to one, each value is
an integer, and each value is non-negative. These constraints can be
added in groups. For example, you can add a new constraint in Solver,
select the range of cells containing all of the independent variables, and
enter the constraint that all are less than or equal to one in one step.
10.10 Reconsider the robot competition problem described in Problem 10.9.
How would the optimal strategy change if the time limit is changed to
5 minutes?
10.11 Revisit the production scheduling problem shown in Section 10.6. An
engineer at the Portland plant implements a process improvement that
will result in a production cost savings of $0.10 per gallon of adhesive.
How will this change the optimal production plan?
10.12 Revisit the production scheduling problem shown in Section 10.6. West
Coast Corp. has offered to increase their order to 22,000 gallons per
week, but is demanding a $0.50 per gallon price reduction. How will
this change the optimal production plan?
10.13 In Problems 10.11 and 10.12, it was necessary to change the equation of
the objective function and/or a constraint equation. If this model were to
be used to explore a variety of possible scenarios, then this method
would be time consuming and error-prone. Modify your spreadsheet for
this problem so that all of the input quantities (capacities, production
costs, order quantities, customer prices, and shipping costs) are entered
at the top of the sheet, as in the shaded cells in Figure P10.13. Modify
your equations to show the total revenue (sales), cost, and profit associ-
ated with each plant/customer combination, as well as the total sales,
cost, and profit for the week. Also add cells to show the total production
for each plant, the pounds shipped to each customer, the excess capacity
of each plant, and the profit broken down by plant and by customer.
Modify your Solver model so that the total profit is maximized by
changing the volumes shipped from each plant to each customer. Modify
the constraint equations so that they refer to the input values of capaci-
ties and sales. These changes will enable you to leave your Solver model
unchanged when you change one of the input parameters.
Check your modified spreadsheet by verifying the solution to the sce-
nario presented in Section 10.6. Use your spreadsheet to evaluate the
change to the weekly profit if:
ch10_mus80164.qxd 8/27/08 2:53 PM Page 324

324 CHAPTER 10 Optimization

a. production capacity at the New Orleans facility is temporarily cut in


half, to 9,000 lb/week
b. Texas Manufacturing Company increases their order to
18,000 lb/week
c. a new labor contract with employees in Buffalo increases produc-
tion costs to $1.18/lb

Figure P10.13
ch10_mus80164.qxd 8/27/08 2:53 PM Page 325

CHAPTER 10 Optimization 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

nonlinear equations, 214–216 Excel solutions, 214–216 engineering application for,


plot displacement example, MATLAB solutions, 209–211 317–322
148–156 Global minimum, 295 Linear equation, 199–201
plotting equations, 147–159 Global variables, MATLAB, 81 Excel solutions for, 240–247
sample problems, 54–61 Goal seeker, 214–216 MATLAB solutions for, 247–250
solver, 214–216, 250–253, problems for, 253 and optimization, 291
308–312 simultaneous equations, 242–243 solving simultaneously, 239–250
solving nonlinear simultaneous Graphs systems of, 239–240
equations, 250–253 bar, 145–146 Linear optimization problem, 291
transposing matrices, 227–228 guidelines for, 178–179 Local maximum, 295
trapezoid rule, 263–266 pie, 145–146 Local variables, MATLAB, 82
unconstrained optimization types of, 143–146 Logic statements, 105
solutions, 308–312 XY, 143–145, 147–178 Logical branching statements,
VLOOKUP, 50–54 Guaranteed range, example for, 117–126
274–276 Logical functions, and Excel, 43–49
F
Logical operators, 119
H
Feasible region, 297 Lookup tables, and Excel, 50–54
Finite element analysis, 19 Histogram, 146 Loops, 105
Fit line, 144 HLOOKUP, and Excel, 50–54 MATLAB example, 110–114
Flowcharts Hold on command, 166 while, 114–117
and MATLAB, 105–108 MATLAB, 166 Loops and logic, MATLAB
symbols for, 106 combining, 127–132
I
fminbnd
M
and MATLAB, 301 Identity matrix, 224
optimization problem solutions, IF statement, and Excel, 43–49, 122 Mathematical model, 5
301, 307–308 If statement, and MATLAB Mathematical operations, and Excel,
fminsearch programming, 118–122 32
and MATLAB, 301 If-else block, 122–126 MATLAB, 4; See also MATLAB
optimization problem solutions, If-elseif-else block, 117, 122–126 programming
301, 301–307 Index, 15 adding matrices, 231–232
for loop, 109–114 Infinite loop, 115 arrays, 86–97
Forecast option, 171 Input, MATLAB function, 80 calculating the determinant,
Formatting data, and Excel, 24–29 Input argument, MATLAB, 82 234–235
Formula Window, Excel, 23 Input variables, MATLAB, 84 command window usage, 64–74
Formulas, and Excel, 30–38 Integration, 259–262 data storage, 98–99
fplot, MATLAB, 159, 167–169 Interface, and Excel, 21–24 fminbnd, 301, 307–308
fprintf, and MATLAB Interpolating, and Excel, 54–56 fminsearch, 301–307
programming, 133–137 Inverse, of matrix, 225 function files, 82–86
Function files, MATLAB, 82–86 functions, 71–72, 74
K
Functions, 13–14 fundamentals, 63–104
creation in MATLAB, 83–86 Kirchhoff's current law, 244–245 general nonlinear equations,
and Excel, 38–43 209–211
L
and MATLAB, 71–72 interface, 63–64
Least-squares fit, 171 inverting matrices, 233–234
G
Linear algebraic equations, 199–201 matrices formatting, 230
General nonlinear equation, Linear constrained optimization, matrix operations, 230–235
200–201 296–300 multiplying matrices, 231–232
ch11_mus80164.qxd 8/29/08 8:54 AM Page 329

Index 329

optimization problem solutions, N P


301–308 Newton-Raphson Method, 205–208 Pareto diagram, 146
optimization toolbox, 301 Newton's Method, 205–208 Pareto graph, Excel, 188–191
plotting equations, 159–176 Nonlinear algebraic equations, Perfect square, 129
polynomial equations, 211–214 199–201 Perimeter, MATLAB example,
roots command, 211–214 Nonlinear constrained optimization, 68–74, 76–82, 91–93
sample problems, 100–104 300–301 Pie chart, 145–146
saving session, 98–99, 163 using fminbnd, 307–308 Pie graph
script files, 74–82 Nonlinear equation, 199–201 Excel, 180–185
simultaneous linear equations, and optimization, 291 Excel formatting of, 183–185
247–250 solving using Excel, 250–253 Plot command; See also Graphs
transposing matrices, 232–233 Nonlinear optimization problem, MATLAB, 159–166
trapezoid rule, 266–270 292 Polynomial equation, 200–201
MATLAB programming Nonlinear unconstrained MATLAB solutions, 211–214
combining loops and logic, optimization, 292–296 Polynomial fit, Excel, 174
127–132 using fminsearch, 301–307 Population, 271
flowcharts, 105–108 Normal distribution, 270–271 Precision, 17–19
for loop, 109–114 Numerical integration Programming tools, 11–13
formatting output, 132–137 calculus concepts, 259–262 Projectile motion problem, 4–11
fprintf, 133–137 of functions, 263–276 algorithmic solutions, 4–11
if statement, 118–122 measured data, 276–280 analytic solutions, 4–11
if-else block, 122–126 problems for, 281–285 Property editor, MATLAB, 162
if-elseif-else block, 117, 122–126 Pseudocode, 7
logical branching statements, O
117–126 Objective function, 289 Q
loop commands, 108–117 Office button, Excel, 22 Quick Access Toolbar, Excel, 22
plot command, 112 Ohm's law, 243
problems for, 137–141 Optimization R
save and run command, 113 constrained problem, 291 Relational operators, 119
while loop, 114–117 defined, 287 Repetitive calculations, for loop,
Matrices, 16–17 engineering, 288–290 109–114
and MATLAB, 93–97 engineering application for, Ribbon, Excel, 23
properties of, 221–225 317–321 Rough curve, 144
Matrix, 221; See also Matrices Excel solutions for, 309–317 Row array, 87
addition, 222 formulating a problem, 290–292 Row matrices, 17
determinant, 224–225 introduction, 287–288 Row vector, 17
Excel operations, 225–230 linear, 291
identity, 224 linear constrained, 296–300 S
inverse, 225 MATLAB solutions for, 301–308 Sample, 271
multiplication, 222–223 nonlinear, 291 Scalars, 14–16
problems for, 235–237 nonlinear constrained, 300–301 and matrix, 223
scalar, 223 nonlinear unconstrained, 292–296 Scaling, 223
transpose, 224 problem solutions, 292–301 Scatter graph, See also Graphs; XY
Matrix Laboratory; See MATLAB problems for, 317–325 graph
Mean, 271 unconstrained problem, 291 Excel example, 172–176
Multiplication, and matrix, 222–223 Order of operations, MATLAB, 69 Scatter plot, 144; See also Graphs,
Multiplication operator, MATLAB, Output, MATLAB, 82 XY graph
68
ch11_mus80164.qxd 8/29/08 8:54 AM Page 330

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

Вам также может понравиться