You are on page 1of 67

MATLAB for Engineering Applications,

5e ISE 5th/ISE Edition William J. Palm Iii


Visit to download the full and correct content document:
https://ebookmass.com/product/matlab-for-engineering-applications-5e-ise-5th-ise-edi
tion-william-j-palm-iii/
MATLAB® for
page i
Engineering
Applications

William J. Palm III


University of Rhode Island
page ii

MATLAB® FOR ENGINEERING APPLICATIONS

Published by McGraw Hill LLC, 1325 Avenue of the Americas, New York,
NY 10019. Copyright ©2023 by McGraw Hill LLC. All rights reserved.
Printed in the United States of America. 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 McGraw
Hill LLC, 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 LCR 27 26 25 24 23 22

ISBN 978-1-265-13919-3
MHID 1-265-13919-9

Cover Image: ©Getty Images/iStockphoto

All credits appearing on page or at the end of the book are considered to be
an extension of the copyright page.

The Internet addresses listed in the text were accurate at the time of
publication. The inclusion of a website does not indicate an endorsement by
the authors or McGraw Hill LLC, and McGraw Hill LLC does not
guarantee the accuracy of the information presented at these sites.
mheducation.com/highered
To my sisters, Linda and Chris, and to my parents, page iii

Lillian and William


ABOUT THE AUTHOR page iv

William J. Palm III is Emeritus Professor of Mechanical Engineering at


the University of Rhode Island. In 1966 he received a B.S. from Loyola
College in Baltimore, and in 1971 a Ph.D. in Mechanical Engineering and
Astronautical Sciences from Northwestern University in Evanston, Illinois.
During his 44 years as a faculty member, he taught 19 courses. One of
these is a freshman MATLAB course, which he helped develop. He has
authored eight textbooks dealing with modeling and simulation, system
dynamics, control systems, and MATLAB. These include System Dynamics,
4th ed. (McGraw Hill, 2021). He wrote a chapter on control systems in the
Mechanical Engineers’ Handbook, 3rd ed. (M. Kutz, ed., Wiley, 2016), and
was a special contributor to the fifth editions of Statics and Dynamics, both
by J. L. Meriam and L. G. Kraige (Wiley, 2002).
Professor Palm’s research and industrial experience are in control
systems, robotics, vibrations, and system modeling. He was the Director of
the Robotics Research Center at the University of Rhode Island from 1985
to 1993, and is the coholder of a patent for a robot hand. He served as
Acting Department Chair from 2002 to 2003. His industrial experience is in
automated manufacturing; modeling and simulation of naval systems,
including underwater vehicles and tracking systems; and design of control
systems for underwater-vehicle engine-test facilities.
CONTENTS page v

Numbered Examples vii


Preface ix

CHAPTER 1
An Overview of MATLAB® 3
1.1 MATLAB Interactive Sessions 4
1.2 The Toolstrip 17
1.3 Built-In Functions, Arrays, and Plots 18
1.4 Working with Files 24
1.5 The MATLAB Help System 32
1.6 Problem-Solving Methodologies 35
1.7 Summary 42
Problems 43

CHAPTER 2
Numeric, Cell, and Structure Arrays 51
2.1 One- and Two-Dimensional Numeric Arrays 52
2.2 Multidimensional Numeric Arrays 61
2.3 Element-by-Element Operations 62
2.4 Matrix Operations 72
2.5 Polynomial Operations Using Arrays 91
2.6 Cell Arrays 96
2.7 Structure Arrays 98
2.8 Summary 102
Problems 103

CHAPTER 3
Functions 121
3.1 Elementary Mathematical Functions 121
3.2 User-Defined Functions 128
3.3 Additional Function Types 143
3.4 File Functions 158
3.5 Summary 160
Problems 161

CHAPTER 4
Programming with MATLAB 169
4.1 Program Design and Development 170
4.2 Relational Operators and Logical Variables 177
4.3 Logical Operators and Functions 179
4.4 Conditional Statements 186
4.5 for Loops 194
4.6 while Loops 206
4.7 The switch Structure 212
4.8 Debugging MATLAB Programs 214
4.9 Additional Examples and Applications 217
4.10 Summary 231
Problems 232

CHAPTER 5
Advanced Plotting 251
5.1 xy Plotting Functions 251
5.2 Additional Commands and Plot Types 261
5.3 Interactive Plotting in MATLAB 278
5.4 Three-Dimensional Plots 280
5.5 Summary 286
Problems 287

CHAPTER 6
Model Building and Regression 299
6.1 Function Discovery 299
6.2 Regression 310
6.3 The Basic Fitting Interface 326
6.4 Summary 329
Problems 330

7
page vi
CHAPTER
Statistics, Probability, and Interpolation 341
7.1 Statistics and Histograms 342
7.2 The Normal Distribution 346
7.3 Random Number Generation 352
7.4 Interpolation 361
7.5 Summary 370
Problems 370

CHAPTER 8
Linear Algebraic Equations 379
8.1 Matrix Methods for Linear Equations 380
8.2 The Left-Division Method 383
8.3 Underdetermined Systems 389
8.4 Overdetermined Systems 398
8.5 A General Solution Program 402
8.6 Summary 404
Problems 405

CHAPTER 9
Numerical Methods for Calculus and Differential Equations
419
9.1 Numerical Integration 420
9.2 Numerical Differentiation 428
9.3 First-Order Differential Equations 431
9.4 Higher-Order Differential Equations 439
9.5 Special Methods for Linear Equations 445
9.6 Summary 458
Problems 459

CHAPTER 10
Simulink 471
10.1 Simulation Diagrams 472
10.2 Introduction to Simulink 473
10.3 Linear State-Variable Models 478
10.4 Piecewise-Linear Models 481
10.5 Transfer-Function Models 487
10.6 Nonlinear State-Variable Models 489
10.7 Subsystems 491
10.8 Dead Time in Models 496
10.9 Simulation of a Nonlinear Vehicle Suspension Model 499
10.10 Control Systems and Hardware-in-the-Loop Testing 503
10.11 Summary 513
Problems 514

CHAPTER 11
Symbolic Processing with MATLAB 525
11.1 Symbolic Expressions and Algebra 527
11.2 Algebraic and Transcendental Equations 536
11.3 Calculus 543
11.4 Differential Equations 555
11.5 Laplace Transforms 562
11.6 Symbolic Linear Algebra 570
11.7 Summary 575
Problems 576

CHAPTER 12
Projects with Matlab 589
12.1 MATLAB Mobile 590
12.2 Programming Game Projects in MATLAB 595
12.3 The MATLAB App Designer 600

APPENDIX A
Guide to Commands and Functions in This Text 603

APPENDIX B
Animation and Sound in MATLAB 615

APPENDIX C
References 626
APPENDIX D
Formatted Output in MATLAB 627
Answers to Selected Problems 631
Index 634
Numbered Examples page vii

Number and Topic


CHAPTER ONE
1.1–1 Volume of a Circular Cylinder
1.6–1 Piston Motion
CHAPTER TWO
2.3–1 Vectors and Displacement
2.3–2 Aortic Pressure Model
2.3–3 Transportation Route Analysis
2.3–4 Current and Power Dissipation in Resistors
2.3–5 A Batch Distillation Process
2.4–1 Miles Traveled
2.4–2 Height versus Velocity
2.4–3 Manufacturing Cost Analysis
2.4–4 Product Cost Analysis
2.4–5 Force Analysis of a 3-Bar Simple Truss
2.4–6 Circuit with Three Resistances
2.4–7 Production Planning
2.4–8 Force Analysis of a Bolt
2.4–9 Computing Forces and Moments on a Tower
2.5–1 Earthquake-Resistant Building Design
2.6–1 An Environment Database
2.7–1 A Student Database
CHAPTER THREE
3.2–1 Minimum Cost Design of a Water Tower
3.2–2 Optimization of an Irrigation Channel
3.3–1 Extra Parameters in fzero and fminbnd
3.3–2 An Intercept Course
3.3–3 Topping the Green Monster
3.3–4 Speed Estimation from Sonar Measurements
3.4–1 Creating a Data File and Loading It into a Variable
CHAPTER FOUR
4.3–1 Height and Speed of a Projectile
4.5–1 Series Calculation with a for Loop
4.5–2 Plotting with a for Loop
4.5–3 Analyzing Trajectories
4.5–4 Motion in One Dimension
4.5–5 Data Sorting
4.6–1 Series Calculation with a while Loop
4.6–2 Growth of a Bank Account
4.6–3 Structural Analysis
4.7–1 Using the switch Structure for Calendar Calculations
4.9–1 A Pursuit Curve
4.9–2 Flight of an Instrumented Rocket
4.9–3 Time to Reach a Specified Height
4.9–4 A College Enrollment Model: Part I
4.9–5 A College Enrollment Model: Part II
CHAPTER FIVE
5.1–1 Plotting Trajectories
5.2–1 Fishing Near an International Boundary
5.2–2 Plotting Orbits
CHAPTER SIX
6.1–1 Speed Estimation from Sonar Measurements
6.1–2 Temperature Dynamics
6.1–3 Hydraulic Resistance
6.1–4 A Cantilever Beam Model
6.2–1 Effect of Polynomial Degree

6.2–2 Estimation of Traffic Flow page viii


6.2–3 Modeling Bacteria Growth
6.2–4 Breaking Strength and Alloy Composition
6.2–5 Response of a Biomedical Instrument
6.2–6 Fitting the Logistic Model
CHAPTER SEVEN
7.1–1 Breaking Strength of Thread
7.2–1 Mean and Standard Deviation of Heights
7.2–2 Estimation of Height Distribution
7.3–1 Statistical Analysis and Manufacturing Tolerances
7.3–2 A Random Walk with Drift
CHAPTER EIGHT
8.1–1 The Matrix Inverse Method
8.2–1 Left-Division Method with Three Unknowns
8.2–2 Calculation of Cable Tension
8.2–3 An Electric Resistance Network
8.2–4 Ethanol Production
8.3–1 An Underdetermined Set with Three Equations and Three
Unknowns
8.3–2 A Statically Indeterminate Problem
8.3–3 Three Equations in Three Unknowns
8.3–4 Production Planning
8.3–5 Traffic Engineering
8.4–1 The Least-Squares Method
8.4–2 An Overdetermined Set
CHAPTER NINE
9.1–1 Velocity from an Accelerometer
9.1–2 Evaluation of Fresnel’s Cosine Integral
9.1–3 Double Integral over a Nonrectangular Region
9.3–1 Response of an RC Circuit
9.3–2 Liquid Height in a Spherical Tank
9.4–1 Pursuit Equations
9.4–2 A Nonlinear Pendulum Model
9.5–1 Trapezoidal Profile for a DC Motor
CHAPTER TEN
10.2–1 Simulink Solution of y ˙ = −10y + f(t)
10.3–1 Simulink Model of a Two-Mass Suspension System
10.4–1 Simulink Model of a Rocket-Propelled Sled
10.4–2 Model of a Relay-Controlled Motor
10.5–1 Response with a Dead Zone
10.6–1 Model of a Nonlinear Pendulum
CHAPTER ELEVEN
11.2–1 Intersection of Two Circles
11.2–2 Positioning a Robot Arm
11.3–1 Topping the Green Monster
PREFACE page ix

F
ormerly used mainly by specialists in signal processing and numerical
analysis, MATLAB® has achieved widespread and enthusiastic
acceptance throughout the engineering community. Many engineering
schools require a course based entirely or in part on MATLAB early in the
curriculum. MATLAB is programmable and has the same logical,
relational, conditional, and loop structures as other programming languages.
Thus it can be used to teach programming principles. In most engineering
schools, MATLAB is the principal computational tool used throughout the
curriculum. In some technical specialties, such as signal processing and
control systems, it is the standard software package for analysis and design.
The popularity of MATLAB is partly due to its long history, and thus it is
well developed and well tested. People trust its answers. Its popularity is
also due to its user interface, which provides an easy-to-use interactive
environment that includes extensive numerical computation and
visualization capabilities. Its compactness is a big advantage. For example,
you can solve a set of many linear algebraic equations with just three lines
of code, a feat that is impossible with traditional programming languages.
MATLAB is also extensible; currently more than 30 “toolboxes” in various
application areas can be used with MATLAB to add new commands and
capabilities.
MATLAB is available for a number of operating systems. It is
compatible across all these platforms, which enables users to share their
programs, insights, and ideas. This text is based on release R2021a of the
software. This includes MATLAB version 9.10. Some of the material in
Chapter 9 is based on the Control System toolbox, Version 10.10. Chapter
10 is based on Version 10.3 of Simulink®, and Chapter 11 is based on
Version 8.7 of the Symbolic Math toolbox.

TEXT OBJECTIVES AND PREREQUISITES


This text is intended as a stand-alone introduction to MATLAB. It can be
used in an introductory course, as a self-study text, or as a supplementary
text. The text’s material is based on the author’s experience in teaching a
required two-credit semester course devoted to MATLAB for engineering
freshmen. In addition, the text can serve as a reference for later use. The
text’s many tables and its referencing system in an appendix have been
designed with this purpose in mind. A secondary objective is to introduce
and reinforce the use of problem-solving methodology as practiced by the
engineering profession in general and as applied to the use of computers to
solve problems in particular. This methodology is introduced in Chapter 1.

The reader is assumed to have some knowledge of algebra and page x


trigonometry; knowledge of calculus is not required for the first eight
chapters. Some knowledge of high school chemistry and physics, primarily
simple electric circuits, and basic statics and dynamics, is required to
understand some of the examples.

TEXT ORGANIZATION
In addition to updating material from the previous edition to include new
features, new functions, and changes in syntax and function names, the text
incorporates the many suggestions made by reviewers and other users.
More examples and homework problems have been added.
The text consists of 12 chapters. The first five chapters constitute a basic
course in MATLAB. The remaining seven chapters are independent of each
other and cover more advanced applications of MATLAB, the Control
Systems toolbox, Simulink, and the Symbolic Math toolbox.
Chapter 1 gives an overview of MATLAB features, including its
windows and menu structures. It also introduces the problem-solving
methodology.
Chapter 2 introduces the concept of an array, which is the fundamental
data element in MATLAB, and describes how to use numeric arrays, cell
arrays, and structure arrays for basic mathematical operations.
Chapter 3 discusses the use of functions and files. MATLAB has an
extensive number of built-in math functions, and users can define their own
functions and save them as a file for reuse.
Chapter 4 introduces programming with MATLAB and covers relational
and logical operators, conditional statements, for and while loops, and the
switch structure.
Chapter 5 deals with two- and three-dimensional plotting. It first
establishes standards for professional-looking, useful plots. In the author’s
experience, beginning students are not aware of these standards, so they are
emphasized. The chapter then covers MATLAB commands for producing
different types of plots and for controlling their appearance. The Live
Editor, which is a major addition to MATLAB, is covered in Section 5.1.
Chapter 6 covers function discovery, which uses data plots to discover a
mathematical description of the data and is a useful tool for model building.
It is a common application of plotting, and a separate section is devoted to
this topic. The chapter also treats polynomial and multiple linear regression
as part of its modeling coverage.
Chapter 7 reviews basic statistics and probability and shows how to use
MATLAB to generate histograms, perform calculations with the normal
distribution, and create random number simulations. The chapter concludes
with linear and cubic spline interpolation.
Chapter 8 covers the solution of linear algebraic equations, which arise in
applications in all fields of engineering. This coverage establishes the
terminology and some important concepts required to use the computer
methods properly. The chapter then shows how to use MATLAB to solve
underdetermined and overdetermined systems of linear equations.

Chapter 9 covers numerical methods for calculus and differential page xi


equations. Numerical integration and differentiation methods are
treated. Ordinary differential equation solvers in the core MATLAB
program are covered, as well as the linear system solvers in the Control
System toolbox. For those readers not familiar with differential equations,
this chapter provides some background for Chapter 10.
Chapter 10 introduces Simulink, which is a graphical interface for
building simulations of dynamic systems. Simulink has increased in
popularity and has seen increased use in industry. The MathWorks provides
Simulink support packages for computer hardware such as LEGO©
MINDSTORMS©, Arduino©, and Raspberry Pi©, which are popular with
researchers and hobbyists for controlling drones and robots. These packages
let you develop and simulate algorithms that run standalone on the
supported hardware. They include a library of Simulink blocks for
configuring and accessing the hardware’s sensors, actuators, and
communication interfaces. You can also tune parameters live from your
Simulink model while your algorithm runs on the hardware. The
MathWorks supports an active user community online where you can see
applications and download files. Chapter 10 discusses some of the robotic
vehicle applications.
Chapter 11 covers symbolic methods for manipulating algebraic
expressions and for solving algebraic and transcendental equations,
calculus, differential equations, and matrix algebra problems. The calculus
applications include integration and differentiation, optimization, Taylor
series, series evaluation, and limits. Laplace transform methods for solving
differential equations are also introduced. This chapter requires the use of
the Symbolic Math toolbox.
Chapter 12 introduces MATLAB Mobile, which is an application
available from The Mathworks that enables you to connect a mobile device
like a smartphone to a MATLAB session running on the MathWorks
Computing Cloud or on your computer. The chapter shows how to use
smartphone sensors, such as an accelerometer, to collect data in the field.
The chapter also contains some suggestions for course projects, based on
the author’s experience in teaching a freshman MATLAB course. The
chapter concludes with a brief introduction to the MATLAB App Designer.
Appendix A contains a guide to the commands and functions introduced
in the text. Appendix B is an introduction to producing animation and sound
with MATLAB. While not essential to learning MATLAB, these features
are helpful for generating student interest. Appendix C is a list of
references. Appendix D summarizes functions for creating formatted
output. Answers to selected problems and an index appear at the end of the
text.
All figures, tables, equations, and exercises have been numbered
according to their chapter and section. For example, Figure 3.4–2 is the
second figure in Chapter 3, Section 4. This system is designed to help the
reader locate these items. The end-of-chapter problems are the exception to
this numbering system. They are numbered 1, 2, 3, and so on to avoid
confusion with the in-chapter exercises.

NEW TO THIS EDITION


As well as updating the coverage to include changes in MATLAB syntax
and MATLAB screens, this edition includes 20 percent more numbered,
major engineering examples. Also, 30 percent of the chapter problems are
new. A new chapter has been added, Chapter 12 Projects with MATLAB,
which introduces MATLAB Mobile and the MATLAB App Designer, and
which covers programming for game projects in MATLAB.

SPECIAL REFERENCE FEATURES page xii

The text has the following special features, which have been designed to
enhance its usefulness as a reference.
■ Throughout each of the chapters, numerous tables summarize the
commands and functions as they are introduced.
■ Appendix A is a complete summary of all the commands and functions
described in the text, grouped by category, along with the number of the
page on which they are described.
■ At the end of the chapter is a list of the key terms introduced in the
chapter, with a reference to where they are introduced.
■ The index has four sections: a listing of MATLAB symbols, an
alphabetical list of MATLAB commands and functions, a list of
Simulink block names, and an alphabetical list of topics.

PEDAGOGICAL AIDS
The following pedagogical aids have been included:
■ Each chapter begins with an overview.
■ Test Your Understanding exercises appear throughout the chapters near
the relevant text. These relatively straightforward exercises allow
readers to assess their grasp of the material as soon as it is covered. In
most cases the answer to the exercise is given with the exercise.
Students should work these exercises as they are encountered.
■ Each chapter ends with numerous problems, grouped according to the
relevant section.
■ Each chapter contains numerous practical examples. The major
examples are numbered.
■ Each chapter has a summary section that reviews the chapter’s
objectives.
■ Answers to many end-of-chapter problems appear at the end of the text.
These problems are denoted by an asterisk next to their number (for
example, 15*).
Two features have been included to motivate the student toward
MATLAB and the engineering profession:
■ Most of the examples and the problems deal with engineering
applications. These are drawn from a variety of engineering fields and
show realistic applications of MATLAB. A guide to these examples
appears on page vii.

■ The facing page of each chapter contains a photograph of a page xiii


recent engineering achievement that illustrates the challenging
and interesting opportunities that await engineers in the 21st century. A
description of the achievement, its related engineering disciplines, and a
discussion of how MATLAB can be applied in those disciplines
accompanies each photo.

ONLINE RESOURCES
An Instructor’s Manual is available online for instructors who have adopted
this text. This manual contains the complete solutions to all of the Test Your
Understanding exercises and to all of the chapter problems. The text
website also has downloadable files containing the major programs and
PowerPoint slides keyed to the text.

MATLAB INFORMATION
For MATLAB and Simulink product information, please contact:

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA, 01760-2098 USA
Tel: 508-647-7000
Fax: 508-647-7001
E-mail: info@mathworks.com
Web: www.mathworks.com
How to buy: www.mathworks.com/store
ACKNOWLEDGMENTS
Many individuals are due credit for this text. Working with faculty at the
University of Rhode Island in developing and teaching a freshman course
based on MATLAB has greatly influenced this text. Email from many users
contained useful suggestions. The author greatly appreciates their
contributions.
The MathWorks, Inc., has always been very supportive of educational
publishing. I especially want to thank Naomi Fernandes of The MathWorks,
Inc., for her help. Theresa Collins, Maria McGreal, and Beth Bettcher of
McGraw Hill Education and Beth Baugh efficiently handled the manuscript
reviews and guided the text through production.
My sisters, Linda and Chris, have always been there, cheering my efforts.
My parents, Lillian and William, were always there for support before they
passed away. Finally, I want to thank my wife, Mary Louise, and my
children, Aileene, Bill, and Andy, for their understanding and support of
this project over the last 25 years.

William J. Palm III


Kingston, Rhode Island
March 2021

_________
®
MATLAB and Simulink are registered trademarks of The MathWorks, Inc.
page xiv

page xv
page 1
Engineering in the 21st Century. page 2

..
Remote Exploration

Source: NASA

I
t will be many years before humans can travel to other planets. In the
meantime, unmanned probes have been rapidly increasing our knowledge
of the universe. Their use will increase in the future as our technology
develops to make them more reliable and more versatile. Better sensors are
expected for imaging and other data collection. Improved robotic devices
will make these probes more autonomous, and more capable of interacting
with their environment, instead of just observing it.
NASA’s planetary rover Sojourner landed on Mars on July 4, 1997, and
excited people on Earth while they watched it successfully explore the
Martian surface to determine wheel-soil interactions, to analyze rocks and
soil, and to return images of the lander for damage assessment.
Then in early 2004, two improved rovers, Spirit and Opportunity, landed
on opposite sides of the planet. In one of the major discoveries of the 21st
century, they obtained strong evidence that water once existed on Mars in
significant amounts. Although planned to operate for only 90 Martian days,
Spirit operated for seven years. The rover likely lost power due to
excessively cold internal temperatures. Opportunity went inactive in 2018,
having already exceeded its planned operational life by many Earth years.
The rover Curiosity used the innovative “skycrane” to land on Mars in
2012 less than 2.4 km (1.5 mi) from its intended target after a 563,000,000
km (350,000,000 mi) journey. It was designed to investigate the Martian
climate and geology; to assess whether the Gale crater ever had an
environment suitable for microbial life, and to determine the habitability of
the site for future human exploration. Curiosity has a mass of 899 kg (1,982
lb) including 80 kg (180 lb) of instruments. The rover is 2.9 m (9.5 ft) long
by 2.7 m (8.9 ft) wide by 2.2 m (7.2 ft) in height. It discovered unexplained
variations in oxygen and methane, and found remnants of an ancient oasis.
Perseverance is a car-sized rover designed to explore the crater Jezero on
Mars. It was launched in July 2020 and successfully landed in February
2021. Perseverance has a design similar to Curiosity, but also carries the
experimental mini-helicopter Ingenuity that was able to fly in the weak
Martian atmosphere. The rover is intended to seek out evidence of former
microbial life, to collect rock and soil samples to store for retrieval by a
future mission, and to test oxygen production from the Martian atmosphere
in support of future crewed missions.
All engineering disciplines were involved with the rover projects. From
the design of the rocket propulsion of the launch vehicles and the calculation
of the interplanetary trajectories, to the design of the rovers’ systems,
MATLAB was used in many of these applications, and it is well suited to
assist designers of future probes and autonomous vehicles like the Mars
rovers. ■

page 3
CHAPTER
1

An Overview of MATLAB®*
OUTLINE
1.1 MATLAB Interactive Sessions
1.2 The Toolstrip
1.3 Built-In Functions, Arrays, and Plots
1.4 Working with Files
1.5 The MATLAB Help System
1.6 Problem-Solving Methodologies
1.7 Summary
Problems

This chapter covers many of the basic features of MATLAB. After you have
finished this chapter, you will be able to use MATLAB to solve many kinds
of problems. Section 1.1 provides an introduction to MATLAB as an
interactive calculator. Section 1.2 covers the main menus and the Toolstrip.
Section 1.3 introduces built-in functions, arrays, and plots. Section 1.4
discusses how to create, edit, and save MATLAB programs. Section 1.5
introduces the extensive MATLAB Help System and Section 1.6 introduces
the methodology of engineering problem solving, with emphasis on the use
of computers.

How to Use This Book


The book’s chapter organization is flexible enough to accommodate a variety
of users. However, it is important to cover at least the first four chapters, in
that order. Chapter 2 covers arrays, which are the basic building blocks in
MATLAB. Chapter 3 covers file usage, functions built into MATLAB, and
user-defined functions. Chapter 4 covers programming using relational and
logical operators, conditional statements, and loops.

Chapters 5 through 11 are independent chapters. They contain in- page 4


depth discussions of how to use MATLAB to solve several common
types of problems. Chapter 5 covers two- and three-dimensional plots in
greater detail. Chapter 6 shows how to use plots to build mathematical
models from data. Chapter 7 covers probability, statistics, and interpolation
applications. Chapter 8 treats linear algebraic equations in more depth by
developing methods for the overdetermined and underdetermined cases.
Chapter 9 introduces numerical methods for calculus and ordinary
differential equations. Simulink®*, the topic of Chapter 10, is a graphical
user interface for solving differential equation models. Chapter 11 covers
symbolic processing with the MATLAB Symbolic Math toolbox, with
applications to algebra, calculus, differential equations, transforms, and
special functions. Chapter 12 discusses creating course projects using
MATLAB, and it introduces MATLAB Mobile and the App Designer.

Reference and Learning Aids


The book has been designed as a reference as well as a learning tool. The
special features useful for these purposes are as follows.
■ Throughout each chapter margin notes identify where new terms are
introduced.
■ Throughout each chapter short Test Your Understanding exercises
appear. Where appropriate, answers immediately follow the exercise so
you can measure your mastery of the material.
■ Homework exercises are at the end of a chapter. These usually require
greater effort than the Test Your Understanding exercises.
■ Most chapters contain tables summarizing the MATLAB commands
introduced in that chapter.
■ At the end of each chapter is
■ A summary of what you should be able to do after completing that
chapter
■ A list of key terms you should know
■ Appendix A contains tables of MATLAB commands, grouped by
category, with the appropriate page references.
■ The index has four parts: MATLAB symbols, MATLAB commands,
Simulink blocks, and topics.

1.1 MATLAB Interactive Sessions


We now show how to start MATLAB, how to make some basic calculations,
and how to exit MATLAB.

Conventions
In this text we use typewriter font to represent MATLAB commands, any
text that you type in the computer, and any MATLAB responses that appear
on the screen, for example, y = 6*x. Variables in normal mathematics text
appear in italics, for example, y = 6x. We use boldface type for three
purposes: to represent vectors and matrices in normal mathematics text (for
example, Ax = b), to represent an action on the keyboard (for example, press
Enter), and to represent the name of a screen menu or an item a menu when
it is the object of an action (for example, click on File). It is assumed that
you press the Enter key after you type a command. We do not show this
action with a separate symbol.

Starting MATLAB page 5

To start MATLAB on a Windows system, double-click on the MATLAB


icon. You will then see the MATLAB Desktop. The Desktop manages the
Command window and a Help Browser as well as other tools. The Desktop
may appear differently in different versions of MATLAB, but the basic
features should be similar to those discussed here. The default appearance of
the Desktop in MATLAB version R2021a is shown in Figure 1.1–1. Four
windows appear. These are the Command window in the center, the
Workspace window in the right, the Details window in the lower left, and the
Current Folder window in the upper left. Across the top of the Desktop are a
row of menu names and a row of icons called the Toolstrip. The default
Desktop shows three tabs: HOME, PLOT, and APPS. Use of these tabs is
discussed in Section 1.2. To the right of the tabs is a box showing the
Shortcut button that enables you to create easy access to commonly used
procedures. The remaining items in the box are used for more advanced
features and are initially inactive. We will describe the various menus later in
this chapter.

Figure 1.1–1 The default MATLAB Desktop for version R2021a. Source:
MATLAB

DESKTOP

You use the Command window to communicate with the MATLAB


program, by typing instructions of various types called commands, functions,
and statements. Later we will discuss the differences between these types,
but for now, to simplify the discussion, we will call the instructions by the
generic name commands. MATLAB displays the prompt (>>) to indicate that
it is ready to receive instructions. Before you give MATLAB instructions,
make sure the cursor is located just after the prompt. If it is not, use the
mouse to move the cursor. The prompt in the Student Edition looks like
EDU >>. We will use the normal prompt symbol >> to illustrate commands
in this text. The Command window in Figure 1.1–1 shows some commands
and the results of the calculations. We will cover these commands later in
this chapter.
COMMAND WINDOW

Three other windows appear in the default Desktop. The Current page 6
Folder window is much like a file manager window; you can use it to
access files. Double-clicking on a file name with the extension .m will open
that file in the MATLAB Editor. The Editor is discussed in Section 1.4.
Figure 1.1–1 shows the files in the author’s folder Examples.
Underneath the Current Folder window is the Details window. It displays
the first comment (if any) in the file. Note that four file types are shown in
the Current Folder. These in order are a MATLAB script file, a JPEG figure
file, a MATLAB user-defined file, and a Simulink model file. These have the
extensions .m, .jpg, m, and .mdl, respectively. Each file type has its own
icon. We will cover m files in this chapter. The other file types will be
covered in later chapters. You can have other file types in the folder.
The Workspace window appears to the right. The Workspace window
displays the variables created in the Command window. Double-click on a
variable name to open the Variables Editor, which is discussed in Chapter 2.
VARIABLE

You can alter the appearance of the Desktop if you wish. For example, to
eliminate a window, just click on its Close-window button (×) in its upper
right-hand corner. To undock, or separate the window from the Desktop,
click on the button containing a curved arrow. An undocked window can be
moved around on the screen. You can manipulate other windows in the same
way. To restore the default configuration, click on Layout in the toolbar, and
select Default.

Test Your Understanding


T1.1–1 Experiment with your Desktop. Type ver at the prompt to see
what MATLAB version you are using and to see details about
your computer. If you are not using version R2021a, find the
windows discussed in this section. Examine the toolbar to locate
items similar to those shown in Figure 1.1–1.

Entering Commands and Expressions


To see how simple it is to use MATLAB, try some practice. Make sure the
cursor is at the prompt in the Command window. To divide 8 by 10, type
8/10 and press Enter (the symbol / is the MATLAB symbol for division).
Your entry and the MATLAB response look like the following on the screen
(we call this interaction between you and MATLAB an interactive session,
or simply a session). Remember, the symbol >> automatically appears on the
screen; you do not type it.
SESSION

page 7

MATLAB indents the numerical result. MATLAB uses high precision for
its computations, but by default it usually displays its results using four
decimal places except when the result is an integer.
If you make a mistake, for now just press Enter and retype the line
correctly. Ignore for now any error messages you may see.

Using Variables MATLAB assigns the most recent answer to a variable


called ans, which is an abbreviation for answer. A variable in MATLAB is a
symbol used to contain a value. You can use the variable ans for further
calculations; for example, using the MATLAB symbol for multiplication (*),
we obtain

Note that the variable ans now has the value 4.


You can use variables to write mathematical expressions. Instead of using
the default variable ans, you can assign the result to a variable of your own
choosing, say, r, as follows:

This is called an assignment statement. The variable, and only the variable,
is always on the left of the = symbol. This symbol is called the assignment or
replacement operator, and it cannot be used the same way as the equals sign
is used in mathematics. The previous entry means “assign the value of 8/10
to the variable r”.
If you now type r at the prompt and press Enter, you will see
thus verifying that the variable r has the value 0.8. You can use this variable
in further calculations. For example,

A common mistake is to forget the multiplication symbol * and page 8


type the expression as you would in algebra, as s = 20r. If you do this
in MATLAB, you will get an error message.
Spaces in the line improve its readability; for example, you can put a
space before and after the = symbol and the multiplication symbol * if you
want. So you could type

MATLAB ignores spaces when making its calculations, with one exception
that we will discuss in Chapter 2.

Order of Precedence
A scalar is a single number. A scalar variable is a variable that contains a
single number. MATLAB uses the symbols + − * / ^ for addition,
subtraction, multiplication, division, and exponentiation (power) of scalars.
These are listed in Table 1.1–1. For example, typing x = 8 + 3*5 returns the
answer x = 23. Typing 2^3 − 10 returns the answer ans = −2. The forward
slash (/) represents right division, which is the normal division operator
familiar to you. Typing 15/3 returns the result ans = 5.

Table 1.1–1 Scalar arithmetic operations


SCALAR

MATLAB has another division operator, called left division, which is


denoted by the backslash (\). The left division operator is useful for solving
sets of linear algebraic equations, as we will see. A good way to remember
the difference between the right and left division operators is to note that the
slash slants toward the denominator. For example, 7/2 = 2\7 = 3.5.
The mathematical operations represented by the symbols + − * / \ and ^
follow a set of rules called precedence. Mathematical expressions are
evaluated starting from the left, with the exponentiation operation having the
highest order of precedence, followed by multiplication and division with
equal precedence, followed by addition and subtraction with equal
precedence.
PRECEDENCE

Parentheses can be used to alter this order. Evaluation begins with the
innermost pair of parentheses and proceeds outward. Table 1.1–2
summarizes these rules. For example, note the effect of precedence on the
following session.
Table 1.1–2 Order of precedence

Table 1.1–3 Commands for managing the work session

page 9
To avoid mistakes, feel free to insert parentheses wherever you are unsure of
the effect precedence will have on the calculation. Use of parentheses also
improves the readability of your MATLAB expressions. For example,
parentheses are not needed in the expression 8 + (3*5), but they make clear
our intention to multiply 3 by 5 before adding 8 to the result.

page 10
Parentheses must be balanced, which means that there must be an equal
number of left-facing and right-facing parentheses. However, just because
they are balanced does not mean the expression is correct. For example, to
evaluate the expression

the following code gives the correct answer.

However, if you type by mistake

the parentheses are balanced and MATLAB will not give an error message
but the answer will be incorrect. For example, if x = 8, the correct answer is
180, but the previous code gives 100.

Test Your Understanding


T1.1–2 Use MATLAB to compute the following expressions.

T1.1–3 What answer is produced by the following MATLAB


expressions?

Proper Use of the Assignment Operator


It is important to understand that the = symbol in MATLAB works
differently than the equals sign you know from mathematics. When you type
x = 3, you tell MATLAB to assign the value 3 to the variable x. This usage
is no different than in mathematics. However, in MATLAB we can also type
something like this: x = x + 2. This tells MATLAB to add 2 to the current
value of x, and to replace the current value of x with this new value. If x
originally had the value 3, its new value would be 5. This use of the =
operator is different from its use in mathematics. For example, the
mathematics equation x = x + 2 is invalid because it implies that 0 = 2.

In MATLAB the variable on the left-hand side of the = operator is page 11


replaced by the value generated by the right-hand side. Therefore,
one variable, and only one variable, must be on the left-hand side of the =
operator. Thus in MATLAB you cannot type 6 = x. Another consequence of
this restriction is that you cannot write in MATLAB expressions like the
following:

The corresponding equation x + 2 = 20 is acceptable in algebra and has the


solution x = 18, but MATLAB cannot solve such an equation without
additional commands (these commands are available in the Symbolic Math
toolbox, which is described in Chapter 11).
Another restriction is that the right-hand side of the = operator must have
a computable value. For example, if the variable y has not been assigned a
value, then the following will generate an error message in MATLAB.

In addition to assigning known values to variables, the assignment


operator is very useful for assigning values that are not known ahead of time,
or for changing the value of a variable by using a prescribed procedure. The
following example shows how this is done.

EXAMPLE 1.1–1
Volume of a Circular Cylinder
The volume of a circular cylinder of height h and radius r is given by V =
πr2h. A particular cylindrical tank is 15 m tall and has a radius of 8 m. We
want to construct another cylindrical tank with a volume 20 percent greater
but having the same height. How large must its radius be?
■ Solution
First solve the cylinder equation for the radius r. This gives

The session is shown below. First we assign values to the variables r and h
representing the radius and height. Then we compute the volume of the
original cylinder and increase the volume by 20 percent. Finally we solve for
the required radius. For this problem we can use the MATLAB built-in
constant pi.

Thus the new cylinder must have a radius of 8.7636 m. Note that the page 12
original values of the variables r and V are replaced with the new
values. This is acceptable as long as we do not wish to use the original
values again. Note how precedence applies to the line V = pi*r^2*h;. It is
equivalent to V = pi*(r^2)*h;.
The expression r = (V/(pi*h))^(1/2) is an example of the use of nested
parentheses where the inner pair makes clear our intention to multiply pi by
h before dividing their product into V. The outer pair of parentheses is
required to indicate the target of the square root operation. You may always
use nested parentheses to indicate your intentions. Make sure they are used
in balanced pairs; otherwise you will get an “unbalanced parentheses
warning.”

Variable Names
The term workspace refers to the names and values of any variables in use in
the current work session. Variable names must begin with a letter; the rest of
the name can contain letters, digits, and underscore characters, but no spaces.
MATLAB is case-sensitive. Thus the following names represent five
different variables: speed, Speed, SPEED, Speed_1, and Speed_2.
There is a large, but finite limit to the number of characters in a name. This
can depend on the particular MATLAB version. Type namelengthmax to
determine this limit. MATLAB ignores any extra characters.
WORKSPACE

Managing the Work Session


Table 1.1–3 summarizes some commands and special symbols for managing
the work session. A semicolon at the end of a line suppresses printing the
results to the screen. If a semicolon is not put at the end of a line, MATLAB
displays the results of the line on the screen. Even if you suppress the display
with the semicolon, MATLAB still retains the variable’s value.

You can put several commands on the same line if you separate page 13
them with a comma if you want to see the results of the previous
command or semicolon if you want to suppress the display. For example,

Note that the first value of x was not displayed. Note also that the value of x
changed from 2 to 15.
If you need to type a long line, you can use an ellipsis, by typing three
periods, to delay execution. For example,

Tab Completion
MATLAB suggests corrections for syntax errors, which are incorrect
expressions in the MATLAB language. Suppose you mistakenly typed the
line
If you pressed Enter, MATLAB responds with an error message and asks if
you meant to type x = 1 + 2*(6+5). But if you did not yet press Enter,
instead of retyping the entire line, press the left-arrow key (←) several times
to move the cursor and add the missing t, then press Enter.
The left-arrow (←) and right-arrow (→) keys move left and right through
a line one character at a time. To move through one word at a time, press
Ctrl and → simultaneously to move to the right; press Ctrl and ←
simultaneously to move to the left. Press Home to move to the beginning of
a line; press End to move to the end of a line.
You can use the tab completion feature to reduce the amount of typing.
MATLAB automatically completes the name of a function, variable, or file if
you type the first few letters of the name and press the Tab key. If the name
is unique, it is automatically completed. For example, in the session listed
earlier, if you type Fruit and press Tab, MATLAB completes the name and
displays FruitPurchased. Press Enter to display the value of the variable,
or continue editing to create a new executable line that uses the variable
FruitPurchased. The tab completion feature also corrects for misspelling. If
you type fruit and press Tab, MATLAB correctly displays FruitPurchased.

If there is more than one name that starts with the letters you page 14
typed, MATLAB displays these names when you press the Tab key.
Use the mouse to select the desired name from the pop-up list by double-
clicking on its name.

Command History
The Pop-up Command History displays commands recently used in the
Command Window. By default it displays in response to the up-arrow (↑) in
the Command Window. You can use it for recalling, viewing, filtering, and
searching recently used commands in the Command Window To retrieve a
command in the list, use the up arrow key to highlight the desired command
and then press Enter, or use the mouse to select it. To retrieve a command
using a partial match, type any part of the command at the prompt, and then
press the up-arrow key. Marks the same color as error messages appear on
the left side of the Command History to indicate commands that generate
errors.
Deleting and Clearing
Press Del to delete the character at the cursor; press Backspace to page 15
delete the character before the cursor. Press Esc to clear the entire
line; press Ctrl and k simultaneously to delete (kill) to the end of the line.
MATLAB retains the last value of a variable until you quit MATLAB or
clear its value. Overlooking this fact commonly causes errors in MATLAB.
For example, you might prefer to use the variable x in a number of different
calculations. If you forget to enter the correct value for x, MATLAB uses the
last value, and you get an incorrect result. You can use the clear function to
remove the values of all variables from memory, or you can use the form
clear var1 var2 to clear the variables named var1 and var2. The effect of
the clc command is different; it clears the Command window of everything
in the window display, but the values of the variables remain.
You can type the name of a variable and press Enter to see its current
value. If the variable does not have a value (i.e., if it does not exist), you see
an error message. You can also use the exist function. Type exist('x') to see
if the variable x is in use. If a 1 is returned, the variable exists; a 0 indicates
that it does not exist. The who function lists the names of all the variables in
memory, but does not give their values. The form who var1 var2 restricts
the display to the variables specified. The wildcard character * can be used
to display variables that match a pattern. For instance, who A* finds all
variables in the current workspace that start with A. The whos function lists
the variable names and their sizes and indicates whether they have nonzero
imaginary parts.
The difference between a function and a command or a statement is that
functions have their arguments enclosed in parentheses. Commands, such as
clear, need not have arguments; but if they do, they are not enclosed in
parentheses, for example, clear x. Statements cannot have arguments; for
example, clc and quit are statements.
Press Ctrl-C to cancel a long computation without terminating the
session. You can quit MATLAB by typing quit. You can also click on the
File menu, and then click on Exit MATLAB.

Predefined Constants
MATLAB has several predefined special constants, such as the built-in
constant pi we used in Example 1.1–1. Table 1.1–4 lists them. The symbol
Another random document with
no related content on Scribd:
building up her navy. Had the colonies been thirteen islands, the sea
power of England would quickly have settled the question; but
instead of such a physical barrier they were separated only by local
jealousies which a common danger sufficiently overcame. To enter
deliberately on such a contest, to try to hold by force so extensive a
territory, with a large hostile population, so far from home, was to
renew the Seven Years’ War with France and Spain, and with the
Americans, against, instead of for, England. The Seven Years’ War
had been so heavy a burden that a wise government would have
known that the added weight could not be borne, and have seen it
was necessary to conciliate the colonists. The government of the day
was not wise, and a large element of England’s sea power was
sacrificed; but by mistake, not willfully; through arrogance, not
through weakness.
This steady keeping to a general line of policy was doubtless made
specially easy for successive English governments by the clear
indications of the country’s conditions. Singleness of purpose was to
some extent imposed. The firm maintenance of her sea power, the
haughty determination to make it felt, the wise state of preparation
in which its military element was kept, were yet more due to that
feature of her political institutions which practically gave the
government, during the period in question, into the hands of a class,
—a landed aristocracy. Such a class, whatever its defects otherwise,
readily takes up and carries on a sound political tradition, is
naturally proud of its country’s glory, and comparatively insensible
to the sufferings of the community by which that glory is maintained.
It readily lays on the pecuniary burden necessary for preparation and
for endurance of war. Being as a body rich, it feels those burdens
less. Not being commercial, the sources of its own wealth are not so
immediately endangered, and it does not share that political timidity
which characterizes those whose property is exposed and business
threatened,—the proverbial timidity of capital. Yet in England this
class was not insensible to anything that touched her trade for good
or ill. Both houses of Parliament vied in careful watchfulness, over its
extension and protection, and to the frequency of their inquiries a
naval historian attributes the increased efficiency of the executive
power in its management of the navy. Such a class also naturally
imbibes and keeps up a spirit of military honor, which is of the first
importance in ages when military institutions have not yet provided
the sufficient substitute in what is called esprit-de-corps. But
although full of class feeling and class prejudice, which made
themselves felt in the navy as well as elsewhere, their practical sense
left open the way of promotion to its highest honors to the more
humbly born; and every age saw admirals who had sprung from the
lowest of the people. In this the temper of the English upper class
differed markedly from that of the French. As late as 1789, at the
outbreak of the Revolution, the French Navy List still bore the name
of an official whose duty was to verify the proofs of noble birth on the
part of those intending to enter the naval school.
Since 1815, and especially in our own day, the government of
England has passed very much more into the hands of the people at
large. Whether her sea power will suffer therefrom remains to be
seen. Its broad basis still remains in a great trade, large mechanical
industries, and an extensive colonial system. Whether a democratic
government will have the foresight, the keen sensitiveness to
national position and credit, the willingness to ensure its prosperity
by adequate outpouring of money in times of peace, all of which are
necessary for military preparation, is yet an open question. Popular
governments are not generally favorable to military expenditure,
however necessary, and there are signs that England tends to drop
behind.
17. Results of the Seven Years’ War[44]

Nevertheless, the gains of England were very great, not only in


territorial increase, nor yet in maritime preponderance, but in the
prestige and position achieved in the eyes of the nations, now fully
opened to her great resources and mighty power. To these results,
won by the sea, the issue of the continental war offered a singular
and suggestive contrast. France had already withdrawn, along with
England, from all share in that strife, and peace between the other
parties to it was signed five days after the Peace of Paris. The terms
of the peace was simply the status quo ante bellum. By the estimate
of the King of Prussia, one hundred and eighty thousand of his
soldiers had fallen or died in this war, out of a kingdom of five
million souls, while the losses of Russia, Austria, and France
aggregated four hundred and sixty thousand men. The result was
simply that things remained as they were.[45] To attribute this only to
a difference between the possibilities of land and sea war is of course
absurd. The genius of Frederick, backed by the money of England,
had proved an equal match for the mismanaged and not always
hearty efforts of a coalition numerically overwhelming.
What does seem a fair conclusion is, that States having a good
seaboard, or even ready access to the ocean by one or two outlets,
will find it to their advantage to seek prosperity and extension by the
way of the sea and of commerce, rather than in attempts to unsettle
and modify existing political arrangements in countries where a
more or less long possession of power has conferred acknowledged
rights, and created national allegiance or political ties. Since the
Treaty of Paris in 1763, the waste places of the world have been
rapidly filled; witness our own continent, Australia, and even South
America. A nominal and more or less clearly defined political
possession now generally exists in the most forsaken regions, though
to this statement there are some marked exceptions; but in many
places this political possession is little more than nominal, and in
others of a character so feeble that it cannot rely upon itself alone for
support or protection. The familiar and notorious example of the
Turkish Empire, kept erect only by the forces pressing upon it from
opposing sides, by the mutual jealousies of powers that have no
sympathy with it, is an instance of such weak political tenure; and
though the question is wholly European, all know enough of it to be
aware that the interest and control of the sea powers is among the
chief, if not the first, of the elements that now fix the situation; and
that they, if intelligently used, will direct the future inevitable
changes. Upon the western continents the political condition of the
Central American and tropical South American States is so unstable
as to cause constant anxiety about the maintenance of internal order,
and seriously to interfere with commerce and with the peaceful
development of their resources. So long as—to use a familiar
expression—they hurt no one but themselves, this may go on; but for
a long time the citizens of more stable governments have been
seeking to exploit their resources, and have borne the losses arising
from their distracted condition. North America and Australia still
offer large openings to immigration and enterprise; but they are
filling up rapidly, and as the opportunities there diminish, the
demand must arise for a more settled government in those
disordered States, for security to life and for reasonable stability of
institutions enabling merchants and others to count upon the future.
There is certainly no present hope that such a demand can be
fulfilled from the existing native materials; if the same be true when
the demand arises, no theoretical positions, like the Monroe
Doctrine, will prevent interested nations from attempting to remedy
the evil by some measure, which, whatever it may be called, will be a
political interference. Such interferences must produce collisions,
which may be at times settled by arbitration, but can scarcely fail at
other times to cause war. Even for a peaceful solution, that nation
will have the strongest arguments which has the strongest organized
force.
It need scarcely be said that the successful piercing of the Central
American Isthmus at any point may precipitate the moment that is
sure to come sooner or later. The profound modification of
commercial routes expected from this enterprise, the political
importance to the United States of such a channel of communication
between her Atlantic and Pacific seaboards, are not, however, the
whole nor even the principal part of the question. As far as can be
seen, the time will come when stable governments for the American
tropical States must be assured by the now existing powerful and
stable States of America or Europe. The geographical position of
those States, the climatic conditions, make it plain at once that sea
power will there, even more than in the case of Turkey, determine
what foreign State shall predominate,—if not by actual possession, by
its influence over the native governments. The geographical position
of the United States and her intrinsic power give her an undeniable
advantage; but that advantage will not avail if there is a great
inferiority of organized brute-force, which still remains the last
argument of republics as of kings.
Herein lies to us the great and still living interest of the Seven
Years’ War. In it we have seen and followed England, with an army
small as compared with other States, as is still her case to-day, first
successfully defending her own shores, then carrying her arms in
every direction, spreading her rule and influence over remote
regions, and not only binding them to her obedience, but making
them tributary to her wealth, her strength, and her reputation. As
she loosens the grasp and neutralizes the influence of France and
Spain in regions beyond the sea, there is perhaps seen the prophecy
of some other great nation in days yet to come, that will incline the
balance of power in some future sea war, whose scope will be
recognized afterward, if not by contemporaries, to have been the
political future and the economical development of regions before
lost to civilization; but that nation will not be the United States if the
moment find her indifferent, as now, to the empire of the seas.
The direction then given to England’s efforts, by the instinct of the
nation and the fiery genius of Pitt, continued after the war, and has
profoundly influenced her subsequent policy. Mistress now of North
America, lording it in India, through the company whose territorial
conquests had been ratified by native princes, over twenty millions of
inhabitants,—a population larger than that of Great Britain and
having a revenue respectable alongside of that of the home
government,—England, with yet other rich possessions scattered far
and wide over the globe, had ever before her eyes, as a salutary
lesson, the severe chastisement which the weakness of Spain had
allowed her to inflict upon that huge disjointed empire. The words of
the English naval historian of that war, speaking about Spain, apply
with slight modifications to England in our own day.
“Spain is precisely that power against which England can always
contend with the fairest prospect of advantage and honor. That
extensive monarchy is exhausted at heart, her resources lie at a great
distance, and whatever power commands the sea, may command the
wealth and commerce of Spain. The dominions from which she
draws her resources, lying at an immense distance from the capital
and from one another, make it more necessary for her than for any
other State to temporize, until she can inspire with activity all parts
of her enormous but disjointed empire.”[46]
It would be untrue to say that England is exhausted at heart; but
her dependence upon the outside world is such as to give a certain
suggestiveness to the phrase.
This analogy of positions was not overlooked by England. From
that time forward up to our own day, the possessions won for her by
her sea power have combined with that sea power itself to control
her policy. The road to India—in the days of Clive a distant and
perilous voyage on which she had not a stopping-place of her own—
was reinforced as opportunity offered by the acquisition of St.
Helena, of the Cape of Good Hope, of the Mauritius. When steam
made the Red Sea and Mediterranean route practicable, she acquired
Aden, and yet later has established herself at Socotra. Malta had
already fallen into her hands during the wars of the French
Revolution; and her commanding position, as the corner-stone upon
which the coalitions against Napoleon rested, enabled her to claim it
at the Peace of 1815. Being but a short thousand miles from
Gibraltar, the circles of military command exercised by these two
places intersect. The present day has seen the stretch from Malta to
the Isthmus of Suez, formerly without a station, guarded by the
cession to her of Cyprus. Egypt, despite the jealousy of France, has
passed under English control. The importance of that position to
India, understood by Napoleon and Nelson, led the latter at once to
send an officer overland to Bombay with the news of the battle of the
Nile and the downfall of Bonaparte’s hopes. Even now, the jealousy
with which England views the advance of Russia in Central Asia is
the result of those days in which her sea power and resources
triumphed over the weakness of D’Aché and the genius of Suffren,
and wrenched the peninsula of India from the ambition of the
French.
“For the first time since the Middle Ages,” says M. Martin,
speaking of the Seven Years’ War, “England had conquered France
single-handed almost without allies, France having powerful
auxiliaries. She had conquered solely by the superiority of her
government.”
Yes! but by the superiority of her government using the
tremendous weapon of her sea power. This made her rich and in turn
protected the trade by which she had her wealth. With her money she
upheld her few auxiliaries, mainly Prussia and Hanover, in their
desperate strife. Her power was everywhere that her ships could
reach, and there was none to dispute the sea to her. Where she would
she went, and with her went her guns and her troops. By this
mobility her forces were multiplied, those of her enemies distracted.
Ruler of the seas, she everywhere obstructed its highways. The
enemies’ fleets could not join; no great fleet could get out, or if it did,
it was only to meet at once, with uninured officers and crews, those
who were veterans in gales and warfare. Save in the case of Minorca,
she carefully held her own sea bases and eagerly seized those of the
enemy. What a lion in the path was Gibraltar to the French
squadrons of Toulon and Brest! What hope for French succor to
Canada, when the English fleet had Louisburg under its lee?
The one nation that gained in this war was that which used the sea
in peace to earn its wealth, and ruled it in war by the extent of its
navy, by the number of its subjects who lived on the sea or by the sea,
and by its numerous bases of operations scattered over the globe. Yet
it must be observed that these bases themselves would have lost their
value if their communications remained obstructed. Therefore the
French lost Louisburg, Martinique, Pondicherry; so England herself
lost Minorca. The service between the bases and the mobile force,
between the ports and the fleets, is mutual.[47] In this respect the
navy is essentially a light corps; it keeps open the communications
between its own ports, it obstructs those of the enemy; but it sweeps
the sea for the service of the land, it controls the desert that man may
live and thrive on the habitable globe.
18. Eighteenth Century Formalism in Naval
Tactics[48]

Tourville,[49] though a brilliant seaman, thus not only typified an era


of transition, with which he was contemporary, but fore-shadowed
the period of merely formal naval warfare, precise, methodical, and
unenterprising, emasculated of military virility, although not of mere
animal courage. He left to his successors the legacy of a great name,
but also unfortunately that of a defective professional tradition. The
splendid days of the French Navy under Louis XIV passed away with
him,—he died in 1701; but during the long period of naval lethargy
on the part of the state, which followed, the French naval officers, as
a class, never wholly lost sight of professional ideals. They proved
themselves, on the rare occasions that offered, before 1715 and
during the wars of Hawke and Rodney, not only gallant seamen after
the pattern of Tourville, but also exceedingly capable tacticians, upon
a system good as far as it went, but defective on Tourville’s express
lines, in aiming rather at exact dispositions and defensive security
than at the thorough-going initiative and persistence which
confounds and destroys the enemy. “War,” to use Napoleon’s phrase,
“was to be waged without running risks.” The sword was drawn, but
the scabbard was kept ever open for its retreat.
The English, in the period of reaction which succeeded the Dutch
wars, produced their own caricature of systematized tactics. Even
under its influence, up to 1715, it is only just to say they did not
construe naval skill to mean anxious care to keep one’s own ships
intact. Rooke, off Malaga, in 1704, illustrated professional
fearlessness of consequences as conspicuously as he had shown
personal daring in the boat attack at La Hogue; but his plans of battle
exemplified the particularly British form of inefficient naval action.
There was no great difference in aggregate force between the French
fleet and that of the combined Anglo-Dutch under his orders. The
former, drawing up in the accustomed line of battle, ship following
ship in a single column, awaited attack. Rooke, having the advantage
of the wind, and therefore the power of engaging at will, formed his
command in a similar and parallel line a few miles off, and thus all
stood down together, the ships maintaining their line parallel to that
of the enemy, and coming into action at practically the same
moment, van to van, center to center, rear to rear. This ignored
wholly the essential maxim of all intelligent warfare, which is so to
engage as markedly to outnumber the enemy at a point of main
collision. If he be broken there, before the remainder of his force
come up, the chances all are that a decisive superiority will be
established by this alone, not to mention the moral effect of partial
defeat and disorder. Instead of this, the impact at Malaga was so
distributed as to produce a substantial equality from one end to the
other of the opposing fronts. The French, indeed, by strengthening
their center relatively to the van and rear, to some extent modified
this condition in the particular instance; but the fact does not seem
to have induced any alteration in Rooke’s dispositions. Barring mere
accident, nothing conclusive can issue from such arrangements. The
result accordingly was a drawn battle, although Rooke says that the
fight, which was maintained on both sides “with great fury for three
hours, ... was the sharpest day’s service that I ever saw;” and he had
seen much,—Beachy Head, La Hogue, Vigo Bay, not to mention his
own great achievement in the capture of Gibraltar.
This method of attack remained the ideal—if such a word is not
misnomer in such a case—of the British Navy, not merely as a matter
of irreflective professional acceptance, but laid down in the official
“Fighting Instructions.”[50] It cannot be said that these err on the side
of lucidity; but their meaning to contemporaries in this particular
respect is ascertained, not only by fair inference from their contents,
but by the practical commentary of numerous actions under
commonplace commanders-in-chief. It further received authoritative
formulation in the specific finding of the Court-Martial upon
Admiral Byng, which was signed by thirteen experienced-officers.
“Admiral Byng should have caused his ships to tack together, and
should immediately have borne down upon the enemy; his van
steering for the enemy’s van, his rear for its rear, each ship making
for the one opposite to her in the enemy’s line, under such sail as
would have enabled the worst sailer to preserve her station in the
line of battle.”[51] Each phrase of this opinion is a reflection of an
article in the Instructions. The line of battle was the naval fetish of
the day; and, be it remarked, it was the more dangerous because in
itself an admirable and necessary instrument, constructed on
principles essentially accurate. A standard wholly false may have its
error demonstrated with comparative ease; but no servitude is more
hopeless than that of unintelligent submission to an idea formally
correct, yet incomplete. It has all the vicious misleading of a half-
truth unqualified by appreciation of modifying conditions; and so
seamen who disdained theories, and hugged the belief in themselves
as “practical,” became doctrinaires in the worst sense.
19. The New Tactics[52]

Rodney and De Guichen, April 17, 1780

Despite his brilliant personal courage and professional skill, which in


the matter of tactics was far in advance of his contemporaries in
England, Rodney, as a commander-in-chief, belongs rather to the
wary, cautious school of the French tacticians than to the impetuous,
unbounded eagerness of Nelson. As in Tourville we have seen the
desperate fighting of the seventeenth century, unwilling to leave its
enemy, merging into the formal, artificial—we may almost say
trifling—parade tactics of the eighteenth, so in Rodney we shall see
the transition from those ceremonious duels to an action which,
while skillful in conception, aimed at serious results. For it would be
unjust to Rodney to press the comparison to the French admirals of
his day. With a skill that De Guichen recognized as soon as they
crossed swords, Rodney meant mischief, not idle flourishes.
Whatever incidental favors fortune might bestow by the way, the
objective from which his eye never wandered was the French fleet,—
the organized military force of the enemy on the sea. And on the day
when Fortune forsook the opponent who had neglected her offers,
when the conqueror of Cornwallis failed to strike while he had
Rodney at a disadvantage, the latter won a victory[53] which
redeemed England from the depths of anxiety, and restored to her by
one blow all those islands which the cautious tactics of the allies had
for a moment gained, save only Tobago.
De Guichen and Rodney met for the first time on the 17th of April,
1780, three weeks after the arrival of the latter. The French fleet was
beating to windward in the channel between Martinique and
Dominica, when the enemy was made in the south-east. A day was
spent in maneuvering for the weather-gage, which Rodney got. The
two fleets being now well to leeward of the islands (see Plate), both
on the starboard tack heading to the northward and the French on
the lee bow of the English, Rodney, who was carrying a press of sail,
signalled to his fleet that he meant to attack the enemy’s rear and
center with his whole force; and when he had reached the position he
thought suitable, ordered them to keep away eight points (90°)
together (A, A, A). De Guichen, seeing the danger of the rear, wore
his fleet all together and stood down to succor it. Rodney, finding
himself foiled, hauled up again on the same tack as the enemy, both
fleets now heading to the southward and eastward.[54] Later, he again
made signal for battle, followed an hour after, just at noon, by the
order (quoting his own despatch), “for every ship to bear down and
steer for her opposite in the enemy’s line.” This, which sounds like
the old story of ship to ship, Rodney explains to have meant her
opposite at the moment, not her opposite in numerical order. His
own words are: “In a slanting position, that my leading ships might
attack the van ships of the enemy’s center division, and the whole
British fleet be opposed to only two thirds of the enemy” (B, B). The
difficulty and misunderstanding which followed seem to have sprung
mainly from the defective character of the signal book. Instead of
doing as the admiral wished, the leading ships (a) carried sail so as to
reach their supposed station abreast their numerical opposite in the
order. Rodney stated afterward that when he bore down the second
time, the French fleet was in a very extended line of battle; and that,
had his orders been obeyed, the center and rear must have been
disabled before the van could have joined.
There seems every reason to believe that Rodney’s intentions
throughout were to double on the French, as asserted. The failure
sprang from the signal book and tactical inefficiency of the fleet; for
which he, having lately joined, was not answerable. But the ugliness
of his fence was so apparent to De Guichen, that he exclaimed, when
the English fleet kept away the first time, that six or seven of his
ships were gone; and sent word to Rodney that if his signals had
been obeyed he would have had him for his prisoner.[55] A more
convincing proof that he recognized the dangerousness of his enemy
is to be found in the fact that he took care not to have the lee-gage in
their subsequent encounters. Rodney’s careful plans being upset, he
showed that with them he carried all the stubborn courage of the
most downright fighter; taking his own ship close to the enemy and
ceasing only when the latter hauled off, her foremast and mainyard
gone, and her hull so damaged that she could hardly be kept afloat.
20. Sea Power in the American Revolution[56]

Graves and De Grasse off the Chesapeake

[Preliminary to the events narrated, the general naval situation was


as follows: The main British and French fleets, under Rodney and De
Grasse, respectively, were in the West Indies, while a small British
division was under Graves at New York, and a French squadron
under De Barras was based on Newport, R. I. The squadrons on the
American coast had met in a desultory action off the Virginia capes
on March 16, 1781, after which the French commander had returned
to Newport and left the British in control.—Editor.]
The way of the sea being thus open and held in force, two thousand
more English troops sailing from New York reached Virginia on the
26th of March, and the subsequent arrival of Cornwallis in May
raised the number to seven thousand. The operations of the
contending forces during the spring and summer months, in which
Lafayette commanded the Americans, do not concern our subject.
Early in August, Cornwallis, acting under orders from Clinton,
withdrew his troops into the peninsula between the York and James
rivers, and occupied Yorktown.
Washington and Rochambeau had met on the 21st of May, and
decided that the situation demanded that the effort of the French
West Indian fleet, when it came, should be directed against either
New York or the Chesapeake. This was the tenor of the despatch
found by De Grasse at Cap Français,[57] and meantime the allied
generals drew their troops toward New York, where they would be on
hand for the furtherance of one object, and nearer the second if they
had to make for it.
In either case the result, in the opinion both of Washington and of
the French government, depended upon superior sea power; but
Rochambeau had privately notified the admiral that his own
preference was for the Chesapeake as the scene of the intended
operations, and moreover the French government had declined to
furnish the means for a formal siege of New York.[58] The enterprise
therefore assumed the form of an extensive military combination,
dependent upon ease and rapidity of movement, and upon blinding
the eyes of the enemy to the real objective,—purposes to which the
peculiar qualities of a navy admirably lent themselves. The shorter
distance to be traversed, the greater depth of water and easier
pilotage of the Chesapeake, were further reasons which would
commend the scheme to the judgment of a seaman; and De Grasse
readily accepted it, without making difficulties or demanding
modifications which would have involved discussion and delay.
Having made his decision, the French admiral acted with great
good judgment, promptitude, and vigor. The same frigate that
brought despatches from Washington was sent back, so that by
August 15 the allied generals knew of the intended coming of the
fleet. Thirty-five hundred soldiers were spared by the governor of
Cap Français, upon the condition of a Spanish squadron anchoring at
the place, which De Grasse procured. He also raised from the
governor of Havana the money urgently needed by the Americans;
and finally, instead of weakening his force by sending convoys to
France, as the court had wished, he took every available ship to the
Chesapeake. To conceal his coming as long as possible, he passed
through the Bahama Channel, as a less frequented route, and on the
30th of August anchored in Lynnhaven Bay, just within the capes of
the Chesapeake, with twenty-eight ships-of-the-line. Three days
before, August 27, the French squadron at Newport, eight ships-of-
the-line with four frigates and eighteen transports under M. de
Barras, sailed for the rendezvous; making, however, a wide circuit
out to sea to avoid the English. This course was the more necessary
as the French siege-artillery was with it. The troops under
Washington and Rochambeau[59] had crossed the Hudson on the
24th of August, moving toward the head of Chesapeake Bay. Thus
the different armed forces, both land and sea, were converging
toward their objective, Cornwallis.
The English were unfortunate in all directions. Rodney, learning of
De Grasse’s departure, sent fourteen ships-of-the-line under Admiral
Hood to North America, and himself sailed for England in August, on
account of ill health. Hood, going by the direct route, reached the
Chesapeake three days before De Grasse, looked into the bay, and
finding it empty went on to New York. There he met five ships-of-
the-line under Admiral Graves, who, being senior officer, took
command of the whole force and sailed on the 31st of August for the
Chesapeake, hoping to intercept De Barras before he could join De
Grasse. It was not till two days later that Sir Henry Clinton was
persuaded that the allied armies had gone against Cornwallis, and
had too far the start to be overtaken.

Admiral Graves was painfully surprised, on making the


Chesapeake, to find anchored there a fleet which from its numbers
could only be an enemy’s. Nevertheless, he stood in to meet it, and as
De Grasse got under way, allowing his ships to be counted, the sense
of numerical inferiority—nineteen to twenty-four—did not deter the
English admiral from attacking. The clumsiness of his method,
however, betrayed his gallantry; many of his ships were roughly
handled, without any advantage being gained.[60] De Grasse,
expecting De Barras, remained outside five days, keeping the English
fleet in play without coming to action; then returning to port he
found De Barras safely at anchor. Graves went back to New York,
and with him disappeared the last hope of succor that was to gladden
Cornwallis’s eyes. The siege was steadily endured, but the control of
the sea made only one issue possible, and the English forces were
surrendered October 19, 1781. With this disaster the hope of
subduing the colonies died in England. The conflict flickered through
a year longer, but no serious operations were undertaken.
... The defeat of Graves and subsequent surrender of Cornwallis
did not end the naval operations in the western hemisphere. On the
contrary, one of the most interesting tactical feats and the most
brilliant victory of the whole war were yet to grace the English flag in
the West Indies; but with the events at Yorktown the patriotic
interest for Americans closes. Before quitting that struggle for
independence, it must again be affirmed that its successful ending, at
least at so early a date, was due to the control of the sea,—to sea
power in the hands of the French, and its improper distribution by
the English authorities. This assertion may be safely rested on the
authority of the one man who, above all others, thoroughly knew the
resources of the country, the temper of the people, the difficulties of
the struggle, and whose name is still the highest warrant for sound,
quiet, unfluttered good sense and patriotism.
The keynote to all Washington’s utterances is set in the
“Memorandum for concerting a plan of operations with the French
army,” dated July 15, 1780, and sent by the hands of Lafayette:
“The Marquis de Lafayette will be pleased to communicate the
following general ideas to Count de Rochambeau and the Chevalier
de Ternay, as the sentiments of the underwritten:
“I. In any operation, and under all circumstances, a decisive
naval superiority is to be considered as a fundamental principle,
and the basis upon which every hope of success must ultimately
depend.”
This, however, though the most formal and decisive expression of
Washington’s views, is but one among many others equally distinct.
21. The French Navy Demoralized by the
Revolution[61]

... The seamen and the navy of France were swept away by the
same current of thought and feeling which was carrying before it the
whole nation; and the government, tossed to and fro by every wave of
popular emotion, was at once too, weak and too ignorant of the
needs of the service to repress principles and to amend defects which
were fatal to its healthy life.
It is particularly instructive to dwell upon this phase of the
revolutionary convulsions of France, because the result in this
comparatively small, but still most important, part of the body politic
was so different from that which was found elsewhere. Whatever the
mistakes, the violence, the excesses of every kind, into which this
popular rising was betrayed, they were symptomatic of strength, not
of weakness,—deplorable accompaniments of a movement which,
with all its drawbacks, was marked by overwhelming force.
It was the inability to realize the might in this outburst of popular
feeling, long pent up, that caused the mistaken forecasts of many
statesmen of the day; who judged of the power and reach of the
movement by indications—such as the finances, the condition of the
army, the quality of the known leaders—ordinarily fairly accurate
tests of a country’s endurance, but which utterly misled those who
looked to them only and did not take into account the mighty
impulse of a whole nation stirred to its depths. Why, then, was the
result so different in the navy? Why was it so weak, not merely nor
chiefly in quantity, but in quality? and that, too, in days so nearly
succeeding the prosperous naval era of Louis XVI. Why should the
same throe which brought forth the magnificent armies of Napoleon
have caused the utter weakness of the sister service, not only amid
the disorders of the Republic, but also under the powerful
organization of the Empire?
The immediate reason was that, to a service of a very special
character, involving special exigencies, calling for special aptitudes,
and consequently demanding special knowledge of its requirements
in order to deal wisely with it, were applied the theories of men
wholly ignorant of those requirements,—men who did not even
believe that they existed. Entirely without experimental knowledge,
or any other kind of knowledge, of the conditions of sea life, they
were unable to realize the obstacles to those processes by which they
would build up their navy, and according to which they proposed to
handle it. This was true not only of the wild experiments of the early
days of the Republic; the reproach may fairly be addressed to the
great emperor himself, that he had scarcely any appreciation of the
factors conditioning efficiency at sea; nor did he seemingly ever
reach any such sense of them as would enable him to understand
why the French navy failed. “Disdaining,” says Jean Bon Saint-
André, the Revolutionary commissioner whose influence on naval
organization was unbounded, “disdaining, through calculation and
reflection, skillful evolutions, perhaps our seamen will think it more
fitting and useful to try those boarding actions in which the
Frenchman was always conqueror, and thus astonish Europe by new
prodigies of valor.”[62] “Courage and audacity,” says Captain
Chevalier, “had become in his eyes the only qualities necessary to our
officers.” “The English,” said Napoleon, “will become very small
when France shall have two or three admirals willing to die.”[63] So
commented, with pathetic yet submissive irony, the ill-fated admiral,
Villeneuve, upon whom fell the weight of the emperor’s discontent
with his navy: “Since his Majesty thinks that nothing but audacity
and resolve are needed to succeed in the naval officer’s calling, I shall
leave nothing to be desired.”[64]
... In truth men’s understandings, as well as their morale and
beliefs, were in a chaotic state. In the navy, as in society, the morale
suffered first. Insubordination and mutiny, insult and murder,
preceded the blundering measures which in the end destroyed the
fine personnel that the monarchy bequeathed to the French republic.
This insubordination broke out very soon after the affairs of the
Bastille and the forcing of the palace at Versailles; that is, very soon
after the powerlessness of the executive was felt. Singularly, yet
appropriately, the first victim was the most distinguished flag-officer
of the French navy.[65]
During the latter half of 1789 disturbances occurred in all the
seaport towns; in Havre, in Cherbourg, in Brest, in Rochefort, in
Toulon. Everywhere the town authorities meddled with the concerns
of the navy yards and of the fleet, discontented seamen and soldiers,
idle or punished, rushed to the town halls with complaints against
their officers. The latter, receiving no support from Paris, yielded
continually, and things naturally went from bad to worse.

You might also like