100% found this document useful (3 votes)
18 views40 pages

Instant Access to Programming with MATLAB for Scientists A Beginner s Introduction 1st Edition Mikhailov Eugeniy E ebook Full Chapters

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

Get ebook downloads in full at ebookmeta.

com

Programming with MATLAB for Scientists A Beginner


s Introduction 1st Edition Mikhailov Eugeniy E

https://ebookmeta.com/product/programming-with-matlab-for-
scientists-a-beginner-s-introduction-1st-edition-mikhailov-
eugeniy-e/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Introduction to R for Social Scientists A Tidy Programming


Approach 1st Edition Ryan Kennedy

https://ebookmeta.com/product/introduction-to-r-for-social-scientists-
a-tidy-programming-approach-1st-edition-ryan-kennedy/

ebookmeta.com

Applied Numerical Methods with MATLAB for Engineers and


Scientists, 5th Edition Steven Chapra

https://ebookmeta.com/product/applied-numerical-methods-with-matlab-
for-engineers-and-scientists-5th-edition-steven-chapra/

ebookmeta.com

Programming with OpenSCAD A Beginner s Guide to Coding 3D


Printable Objects 1st Edition Justin Gohde

https://ebookmeta.com/product/programming-with-openscad-a-beginner-s-
guide-to-coding-3d-printable-objects-1st-edition-justin-gohde/

ebookmeta.com

Energy Law: An Introduction 2nd Edition Raphael J. Heffron

https://ebookmeta.com/product/energy-law-an-introduction-2nd-edition-
raphael-j-heffron/

ebookmeta.com
Encryption in SAS 9 4 Sixth Edition Sas Institute Inc

https://ebookmeta.com/product/encryption-in-sas-9-4-sixth-edition-sas-
institute-inc/

ebookmeta.com

HCI International 2022 Late Breaking Papers Multimodality


in Advanced Interaction Environments 24th International
Conference on Human Computer Interaction HCII 2022 Virtual
Event June 26 July 1 2022 Proceedings Masaaki Kurosu
https://ebookmeta.com/product/hci-international-2022-late-breaking-
papers-multimodality-in-advanced-interaction-environments-24th-
international-conference-on-human-computer-interaction-
hcii-2022-virtual-event-june-26-july-1-2022-p/
ebookmeta.com

International Organizations and Member State


Responsibility Critical Perspectives 1st Edition Ana Sofia
Barros
https://ebookmeta.com/product/international-organizations-and-member-
state-responsibility-critical-perspectives-1st-edition-ana-sofia-
barros/
ebookmeta.com

A Structuralist Theory of Economics 1st Edition Adolfo


García De La Sienra

https://ebookmeta.com/product/a-structuralist-theory-of-economics-1st-
edition-adolfo-garcia-de-la-sienra/

ebookmeta.com

Dirty Love 1st Edition Ainsley Booth

https://ebookmeta.com/product/dirty-love-1st-edition-ainsley-booth/

ebookmeta.com
Bette Davis Black and White 1st Edition Julia A. Stern

https://ebookmeta.com/product/bette-davis-black-and-white-1st-edition-
julia-a-stern/

ebookmeta.com
Programming with
MATLAB for Scientists
A Beginner’s Introduction
Programming with
MATLAB for Scientists
A Beginner’s Introduction

Eugeniy E. Mikhailov
MATLAB® and Simulink® are trademarks of the MathWorks, Inc. and are used with permission. The
MathWorks does not warrant the accuracy of the text or exercises in this book. This book’s use or discussion of
MATLAB® and Simulink® software or related products does not constitute endorsement or sponsorship by the
MathWorks of a particular pedagogical approach or particular use of the MATLAB® and Simulink® software.

Published in 2017 by CRC Press


Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742

© 2017 by Taylor & Francis Group, LLC

CRC Press is an imprint of Taylor & Francis Group

No claim to original U.S. Government works

Printed in the United States of America on acid-free paper

10 9 8 7 6 5 4 3 2 1

International Standard Book Number-13: 978-1-4987-3831-6 (eISBN)

This book contains information obtained from authentic and highly regarded sources. Reprinted material is
quoted with permission, and sources are indicated. A wide variety of references are listed. Reasonable efforts
have been made to publish reliable data and information, but the author and the publisher cannot assume
responsibility for the validity of all materials or for the consequences of their use.

No part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic,
mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and
recording, or in any information storage or retrieval system, without written permission from the publishers.

For permission to photocopy or use material electronically from this work, please access www.copyright.com
(http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive,
Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration
for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate
system of payment has been arranged.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only
for identification and explanation without intent to infringe.

Library of Congress Cataloging-in-Publication Data

Names: Mikhailov, Eugeniy E., 1975- author.


Title: Programming with MATLAB for scientists : a beginner’s introduction / Eugeniy E. Mikhailov.
Description: Boca Raton, FL : CRC Press, Taylor & Francis Group, [2017]
Identifiers: LCCN 2017031570 | ISBN 9781498738286 | ISBN 1498738281
Subjects: LCSH: MATLAB. | Science–Data processing. | Engineering mathematics–Data processing.
| Numerical analysis–Data processing.
Classification: LCC Q183.9.M55 2017 | DDC 510.285/53–dc23
LC record available at https://lccn.loc.gov/2017031570

Visit the Taylor & Francis Web site at


http://www.taylorandfrancis.com

and the CRC Press Web site at


http://www.crcpress.com
Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

I Computing Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1 Computers and Programming Languages: An Introduction . . . . . . . . . . . . 3


1.1 Early History of Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Modern Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Common features of a modern computer . . . . . . . . . . . . . . . . . . 4
1.3 What Is Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Programming Languages Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Numbers Representation in Computers and Its
Potential Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.1 Discretization—the main weakness of computers . . . . . . . . . . 7
1.5.2 Binary representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5.3 Floating-point number representation . . . . . . . . . . . . . . . . . . . . . 8
1.5.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 MATLAB Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.1 MATLAB’s Graphical User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 MATLAB as a Powerful Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.1 MATLAB’s variable types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.2 Some built-in functions and operators . . . . . . . . . . . . . . . . . . . . . 15
2.2.3 Operator precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Efficient Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Using Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.5.1 Creating and accessing matrix elements . . . . . . . . . . . . . . . . . . . 19
2.5.2 Native matrix operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.5.3 Strings as matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.6 Colon (:) Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.1 Slicing matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.7 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.7.1 Saving plots to files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.8 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

v
vi Contents

3 Boolean Algebra, Conditional Statements, Loops . . . . . . . . . . . . . . . . . . . . . . 31


3.1 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1.1 Boolean operators precedence in MATLAB . . . . . . . . . . . . . . . . 32
3.1.2 MATLAB Boolean logic examples . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2.1 Comparison with vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2.2 Comparison with matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3.1 The if-else-end statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3.2 Short form of the “if” statement . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.4 Common Mistake with the Equality Statement . . . . . . . . . . . . . . . . . . . 36
3.5 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.1 The “while” loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.2 Special commands “break” and “continue” . . . . . . . . . . . . . . . . 38
3.5.3 The “for” loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.6 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

4 Functions, Scripts, and Good Programming Practice . . . . . . . . . . . . . . . . . . . 41


4.1 Motivational Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.1.1 Bank interest rate problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.1.2 Time of flight problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.2 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2.1 Quadratic equation solver script . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3.1 Quadratic equation solver function . . . . . . . . . . . . . . . . . . . . . . . 46
4.4 Good Programming Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.4.1 Simplify the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.4.2 Try to foresee unexpected behavior . . . . . . . . . . . . . . . . . . . . . . . 48
4.4.3 Run test cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.4.4 Check and sanitize input arguments . . . . . . . . . . . . . . . . . . . . . . 49
4.4.5 Is the solution realistic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.4.6 Summary of good programming practice . . . . . . . . . . . . . . . . . . 51
4.5 Recursive and Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.5.1 Recursive functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.5.2 Anonymous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.6 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

II Solving Everyday Problems with MATLAB . . . . . . . . . . . . . . . . . . . . . . 57

5 Solving Systems of Linear Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . 59


5.1 The Mobile Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.2 Built-In MATLAB Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.2.1 The inverse matrix method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Contents vii

5.2.2 Solution without inverse matrix calculation . . . . . . . . . . . . . . . 62


5.2.3 Which method to use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.3 Solution of the Mobile Problem with MATLAB . . . . . . . . . . . . . . . . . . . 63
5.3.1 Solution check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.4 Example: Wheatstone Bridge Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.5 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

6 Fitting and Data Reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


6.1 Necessity for Data Reduction and Fitting . . . . . . . . . . . . . . . . . . . . . . . . 69
6.2 Formal Definition for Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.2.1 Goodness of the fit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3 Fitting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4 Parameter Uncertainty Estimations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.5 Evaluation of the Resulting Fit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.6 How to Find the Optimal Fit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.1 Example: Light diffraction on a single slit . . . . . . . . . . . . . . . . . 77
6.6.2 Plotting the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.6.3 Choosing the fit model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.6.4 Making an initial guess for the fit parameters . . . . . . . . . . . . . . 79
6.6.5 Plotting data and the model based on the
initial guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.6.6 Fitting the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.7 Evaluating uncertainties for the fit parameters . . . . . . . . . . . . . 82
6.7 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

7 Numerical Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.1 Estimate of the Derivative via the Forward Difference . . . . . . . . . . . . 87
7.2 Algorithmic Error Estimate for Numerical Derivative . . . . . . . . . . . . . 88
7.3 Estimate of the Derivative via the Central Difference . . . . . . . . . . . . . 89
7.4 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

8 Root Finding Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93


8.1 Root Finding Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 Trial and Error Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.3 Bisection Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3.1 Bisection use example and test case . . . . . . . . . . . . . . . . . . . . . . . 97
8.3.2 Possible improvement of the bisection code . . . . . . . . . . . . . . . 100
8.4 Algorithm Convergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.5 False Position (Regula Falsi) Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.6 Secant Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.7 Newton–Raphson Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.7.1 Using Newton–Raphson algorithm with the analytical
derivative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.7.2 Using Newton–Raphson algorithm with the numerical
derivative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
viii Contents

8.8 Ridders’ Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


8.9 Root Finding Algorithms Gotchas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
8.10 Root Finding Algorithms Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.11 MATLAB’s Root Finding Built-in Command . . . . . . . . . . . . . . . . . . . . . 110
8.12 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

9 Numerical Integration Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113


9.1 Integration Problem Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
9.2 The Rectangle Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.2.1 Rectangle method algorithmic error . . . . . . . . . . . . . . . . . . . . . . . 116
9.3 Trapezoidal Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
9.3.1 Trapezoidal method algorithmic error . . . . . . . . . . . . . . . . . . . . . 117
9.4 Simpson’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
9.4.1 Simpson’s method algorithmic error . . . . . . . . . . . . . . . . . . . . . . 118
9.5 Generalized Formula for Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.6 Monte Carlo Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.6.1 Toy example: finding the area of a pond . . . . . . . . . . . . . . . . . . . 119
9.6.2 Naive Monte Carlo integration . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.6.3 Monte Carlo integration derived . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.6.4 The Monte Carlo method algorithmic error . . . . . . . . . . . . . . . . 121
9.7 Multidimensional Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.7.1 Minimal example for integration in
two dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.8 Multidimensional Integration with Monte Carlo . . . . . . . . . . . . . . . . . 123
9.8.1 Monte Carlo method demonstration . . . . . . . . . . . . . . . . . . . . . . 124
9.9 Numerical Integration Gotchas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9.9.1 Using a very large number of points . . . . . . . . . . . . . . . . . . . . . . 124
9.9.2 Using too few points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9.10 MATLAB Functions for Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.11 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

10 Data Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129


10.1 The Nearest Neighbor Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.2 Linear Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10.3 Polynomial Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.4 Criteria for a Good Interpolation Routine . . . . . . . . . . . . . . . . . . . . . . . . 134
10.5 Cubic Spline Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
10.6 MATLAB Built-In Interpolation Methods . . . . . . . . . . . . . . . . . . . . . . . . 135
10.7 Extrapolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.8 Unconventional Use of Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.8.1 Finding the location of the data crossing y = 0 . . . . . . . . . . . . . 136
10.9 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Contents ix

III Going Deeper and Expanding the Scientist’s Toolbox . . . . . . . . . . . . 139

11 Random Number Generators and Random Processes . . . . . . . . . . . . . . . . . . 141


11.1 Statistics and Probability Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.1.1 Discrete event probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.1.2 Probability density function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
11.2 Uniform Random Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
11.3 Random Number Generators and Computers . . . . . . . . . . . . . . . . . . . . 143
11.3.1 Linear congruential generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
11.3.2 Random number generator period . . . . . . . . . . . . . . . . . . . . . . . . 145
11.4 How to Check a Random Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
11.4.1 Simple RNG test with Monte Carlo integration . . . . . . . . . . . . 146
11.5 MATLAB’s Built-In RNGs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
11.6 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

12 Monte Carlo Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149


12.1 Peg Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
12.2 Coin Flipping Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
12.3 One-Dimensional Infection Spread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
12.4 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

13 The Optimization Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161


13.1 Introduction to Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
13.2 One-Dimensional Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
13.2.1 The golden section optimum search algorithm . . . . . . . . . . . . . 163
13.2.2 MATLAB’s built-in function for the one-dimension
optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
13.2.3 One-dimensional optimization examples . . . . . . . . . . . . . . . . . . 165
13.3 Multidimensional Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
13.3.1 Examples of multidimensional optimization . . . . . . . . . . . . . . . 168
13.4 Combinatorial Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
13.4.1 Backpack problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
13.4.2 Traveling salesman problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
13.5 Simulated Annealing Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
13.5.1 The backpack problem solution with the
annealing algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
13.6 Genetic Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
13.7 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

14 Ordinary Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


14.1 Introduction to Ordinary Differential Equation . . . . . . . . . . . . . . . . . . . 195
14.2 Boundary Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
14.3 Numerical Method to Solve ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
14.3.1 Euler’s method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
14.3.2 The second-order Runge–Kutta method (RK2) . . . . . . . . . . . . . 199
x Contents

14.3.3 The fourth-order Runge–Kutta method (RK4) . . . . . . . . . . . . . . 200


14.3.4 Other numerical solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
14.4 Stiff ODEs and Stability Issues of the Numerical Solution . . . . . . . . . 201
14.5 MATLAB’s Built-In ODE Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
14.6 ODE Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
14.6.1 Free fall example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
14.6.2 Motion with the air drag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
14.7 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

15 Discrete Fourier-Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


15.1 Fourier Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
15.1.1 Example: Fourier series for |t| . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
15.1.2 Example: Fourier series for the step function . . . . . . . . . . . . . . . 217
15.1.3 Complex Fourier series representation . . . . . . . . . . . . . . . . . . . . 218
15.1.4 Non-periodic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
15.2 Discrete Fourier Transform (DFT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
15.3 MATLAB’s DFT Implementation and Fast Fourier
Transform (FFT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
15.4 Compact Mathematical Notation for Fourier Transforms . . . . . . . . . . 222
15.5 DFT Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
15.6 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

16 Digital Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229


16.1 Nyquist Frequency and the Minimal Sampling Rate . . . . . . . . . . . . . . 229
16.1.1 Under-sampling and aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
16.2 DFT Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
16.2.1 Low-pass filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
16.2.2 High-pass filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
16.2.3 Band-pass and band-stop filters . . . . . . . . . . . . . . . . . . . . . . . . . . 235
16.3 Filter’s Artifacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
16.4 Windowing Artifacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
16.5 Self-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Preface

Intended Audience
This book is intended for anyone who wants to learn how to program with
MATLAB and seeks a concise and accessible introduction to programming,
MATLAB, and numerical methods. The author hopes that readers will find here
all necessary materials for handling their everyday computational and program-
ming problems. Even more seasoned readers may find useful insights on familiar
methods or explanations for puzzling issues they might encounter.
We will start with simple concepts and build up a skill set suitable to model,
simulate, and analyze real-life systems. Additionally, this book provides a broad
overview of the numerical methods necessary for successful scientific or engineer-
ing work. We will get familiar with a “lore” of computing, so you will know what
to look for when you decide to move to more advanced techniques.
The book is based on material of the one semester “Practical Computing for
Scientists” class taught at the College of William & Mary for students who have
not yet declared a major or students majoring in physics, neuroscience, biology,
computer science, applied math and statistics, or chemistry. The students who
successfully took this class were at all levels of their academic careers; some were
freshmen, some where seniors, and some were somewhere in between.

Why MATLAB?
A couple words about MATLAB, as it is our programming language of choice.
MATLAB has a good balance of already implemented features, which are impor-
tant for scientists and for ease of learning. MATLAB hides a lot of low-level details
from users: you do not need to think about variable types, compilation processes,
and so on. It just works. You can also do a calculation on a whole array of data
without tracking every element of the array. This part is deep inside of MATLAB.
From an instructor’s point of view, you do not need to worry about the instal-
lation of MATLAB for your class. It is easy and students are capable of doing it
alone. More importantly, it looks and works the same on variety of operational
systems, such as Windows, Mac, and Linux. MATLAB produces exactly the same
result on all computers.
From a student’s point of view, MATLAB is probably the most frequently
required programming language for an engineering or scientific position. There-
fore, if you learn MATLAB now, you likely will not need to retrain yourself to
another industry standard programming language.

xi
xii Preface

MATLAB has a downside: it is expensive to purchase if your school or work-


place does not provide it. This is not a big worry; you can do exercises from all the
chapters, except the data fitting, with a free alternative: GNU Octave. The fitting in
Octave uses a different set of commands, but everything else will work the same
(you might need minor tweaking for more advanced options).

What Is not Covered in This Book?


This book does not extensively cover MATLAB’s commands. There is no reason to
write another manual for MATLAB (which has an excellent one already) or redo
tutorials available on the web.
This book is also not a substitute for a book explaining the ins and outs of
numerical methods. Whenever possible, we discuss what interesting things can
be done with a numerical method and do not bother with the most efficient imple-
mentation. However, the beginning of the book is an exception. There, the basics
of programming are explained via implementations of some numerical method
algorithms (which often have MATLAB’s built-in equivalents already).

How to Read This Book


If you have programmed before, you can skip the majority of Part I, but make sure
that you are fluent with the element operations described there, the differences
between array and element-wise operations, and array slicing.
If you are scientist, then the plotting and fitting materials are a must. Make
sure that you have read the fitting chapter. If you need to learn anything important
about data analysis, then learn this.
The material in Part III is somewhat optional, although the author strongly
recommends the optimization problem chapter (see Chapter 13). It is amazing to
see how many other problems are essentially optimization problems and can be
solved with methods presented there. The time to use the material in this section
will probably come in upper undergraduate classes.
As you get more and more fluent with programming, reread the good pro-
gramming practice materials in Section 4.4 and try to implement more and more
techniques from there.
Preface xiii

Data files and MATLAB listings locations


All MATLAB’s listing and required data files used in the book are available on
the web.* The PDF version of this book contains direct links to such files.

MATLAB® is a registered trademark of The MathWorks, Inc.


For 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: [email protected]
Web: www.mathworks.com

* Please visit http://physics.wm.edu/programming_with_MATLAB_book.


Other documents randomly have
different content
fell wrath of Juno’s bottomless heart constrains me, Neptune,
to stoop to all the abasement of prayer—wrath that no
length of time softens, no piety of man, unconquered and unsilenced
by Jove’s behest, by destiny itself. It is not enough 5
that her monstrous malice has torn the heart from the breast
of Phrygia,[o] and dragged a city through an infinity of vengeance—
the
remnants of Troy, the very ashes and bones
of the slain—these she pursues; rage so fiendish let her
trace to its source. Thou thyself canst bear me witness 10
but now in the Libyan waters, what mountains she raised
all in a moment—all ocean she confounded with heaven,
blindly relying on Æolus’ storms to convulse a realm where
thou art master. See now—goading the matrons of
Troy to crime, she has basely burnt their ships, and driven 15
them in the ruins of their fleet to leave their mates to a
home on an unknown shore. These poor relics, then, let
them, I beg, spread the sail in safety along thy waters; let
them touch the mouth of Laurentian Tiber, if my prayer
is lawful, if that city is granted them of Fate.” 20

Then thus spake Saturn’s son, lord of the ocean deep:


“All right hast thou, queen of Cythera, to place thy trust
in these realms of mine, whence thou drawest thy birth.
And I have earned it too—often have I checked the madness,
the mighty raving of sky and sea; nor less on earth 25
(bear witness Xanthus and Simois!) has thy Æneas known
my care. When Achilles was chasing Troy’s gasping
bands, forcing them against their own ramparts, and offering
whole hecatombs to Death, till the choked rivers
groaned again, and Xanthus could not thread his way, 30
or roll himself into the sea—in that day, as Æneas confronted
Peleus’ mighty son with weaker arm and weaker aid
from heaven, I snatched him away in a circling cloud even
while my whole heart was bent on overthrowing from their
base the buildings of my own hand, the walls of perjured 35
Troy. As my mind was then, it abides now. Banish thy
fears; safely, according to thy prayer, he shall reach
Avernus haven. One there shall be, and one only, whom
thou shalt ask in vain from the engulfing surge—one life,
and one only, shall be given for thousands.”

With these words, having soothed to joy the goddess’


heart, the august Father yokes his steeds with a yoke of
gold, and puts to their fierce mouth the foaming bit, and 5
gives full course to his flowing reins. The azure car glides
lightly over the water’s surface—the waves sink down,
the swelling sea stills its waters under the wheels of thunder—the
storm-clouds fly away over the wide waste of
heaven. Then come the hundred shapes of attendant 10
powers: enormous whales and Glaucus’[198] aged train, and
Ino’s young Palæmon,[199] and rapid Tritons, and the whole
host that Phorcus leads; on the left are Thetis, and Melite,
and maiden Panopea, Nesæa, and Spio, and Thalia, and
Cymodoce. 15

And now father Æneas feels a soft thrill of succeeding


joy shoot through his anxious bosom; at once he bids
every mast be reared, every sail stretched on its yard-arm.
One and all strain the rope and loosen the sheet, now right,
now left—one and all turn to and fro the sailyard’s lofty 20
horns; the fleet is wafted by the gales it loves. First,
before all, Palinurus led the crowding ranks; after him the
rest, as bidden, shaped their course. And now dewy
Night had well-nigh reached the cope of heaven’s arch—in
calm repose the sailors were relaxing their limbs, 25
stretched each by his oar along the hard benches—when
Sleep’s power, dropping lightly down from the stars of
heaven, parted the dusky air, and swam through the night,
in quest of you, poor Palinurus, with a fatal freight of
dreams for your guiltless head. The god has sat down 30
high on the stern, in the likeness of Phorbas, and these are
the words he utters: “Son of Iasus, Palinurus, the sea
itself is steering the fleet; the winds breathe evenly and
fully; it is slumber’s own hour; come, relax that strained
head, and let those weary eyes play truant from their toil. 35
I myself will undertake your functions awhile in your
stead.” Hardly raising his eyes, Palinurus answered him
thus:—“I blind myself to smiling seas and sleeping
waves: is that your will? I place my faith on this fickle
monster? What? trust Æneas to lying gales and fair
skies, whose fraud I have rued so often?” So he said,
and went on cleaving and clinging, never dropping his
hand from the rudder, nor his eye from the stars. When 5
lo! the god waves over his two temples a bough dripping
with Lethe’s[200] dews, and drugged by the charms of Styx,
and in his own despite closes his swimming eyes. Scarce
had sudden slumber begun to unstring his limbs, when
the power, leaning over him, hurled him headlong into the 10
streaming waves, tearing away part of the vessel’s stern
and the rudder as he fell, with many a cry for help that
never came, while Sleep himself soared high on his wings
into the yielding air. Safely, nevertheless, rides the fleet
over the water, travelling undaunted in the strength of 15
Neptune’s royal promise. And now it was nearing the
cliffs of the Sirens’[201] isle, cliffs unfriendly in days of old, and
white with many a seaman’s bones, and the rocks were
sounding hollow from afar with the untiring surge, when
the great Father perceived the unsteady reel of the masterless 20
ship, and guided it himself through the night of waters,
groaning oft, and staggering under the loss of his friend:
“Victim of faith in the calm of sky and sea, you will lie,
Palinurus, a naked[202] corpse on a strand unknown.”
BOOK VI
So saying and weeping, he gives rope to his fleet, and in
due time is wafted smoothly to Cumæ’s shores of Eubœan
fame. They turn their prows seaward: then the anchor
with griping fang began to moor vessel after vessel, and
crooked keels fringe all the coast. With fiery zeal the 5
crews leap out on the Hesperian shore: some look for the
seed of fire where it lies deep down in the veins of flint:
some strip the woods, the wild beast’s shaggy covert, and
point with joy to the streams they find. But good Æneas
repairs to the heights on which Apollo sits exalted, and 10
the privacy of the dread Sibyl,[203] stretching far away into a
vast cavern—the Sibyl, into whose breast the prophet that
speaks at Delos breathes his own mighty mind and soul,
and opens the future to her eye. And now they are entering
the groves of the Trivian goddess and the golden 15
palace.

Dædalus, so runs the legend, flying from Minos’ sceptre,


dared to trust himself in air on swift wings of his own workmanship,
sailed to the cold north along an unwonted way,
and at last stood buoyant on the top of this Eubœan hill. 20
Grateful to the land that first received him, he dedicated
to thee, Phœbus, his feathery oarage, and raised a mighty
temple. On the doors was seen Androgeos’ death: there
too were the sons of Cecrops,[204] constrained—O cruel woe!
to pay in penalty the yearly tale of seven of their sons’ 25
lives: the urn is standing, and the lots drawn out. On the
other side, breasting the wave, the Gnossian land frowns
responsive. There is Pasiphaë’s tragic passion for the
bull, and the mingled birth, the Minotaur, half man, half
brute, a monument of monstrous love. There is the edifice,[205] 30
that marvel of toiling skill, and its inextricable maze—inextricable,
had not Dædalus in pity for the enthralling
passion of the royal princess, himself unravelled
the craft and mystery of those chambers, guiding the
lover’s dark steps with a clue of thread. You too, poor
Icarus,[206] had borne no mean part in that splendid portraiture, 5
would grief have given art its way. Twice the artist
essayed to represent the tragedy in gold: twice the father’s
hands dropped down palsied. So they would have gone on
scanning all in succession, had not Achates returned from
his errand, and with him the priestess of Phœbus and 10
Diana, Deïphobe, Glaucus’ daughter, who thus bespeaks
the king: “Not this the time for shows like these; your
present work is to sacrifice seven bullocks untouched by the
yoke, seven sheep duly chosen.”

This said to Æneas, whose followers swiftly perform the 15


prescribed rites, she summons the Teucrians into the lofty
temple, herself its priestess. One huge side of the Eubœan
cliff has been hollowed into a cave, approached by a hundred
broad avenues, a hundred mouths—from these a
hundred voices are poured, the responses of the Sibyl. 20
Just as they were on the threshold, “It is the moment
to pray for the oracle,” cries the maiden; “the god, the god
is here.” Thus as she spoke at the gate, her visage, her
hue changed suddenly—her hair started from its braid—her
bosom heaves and pants, her wild soul swells with 25
frenzy—she grows larger to the view, and her tones are
not of earth, as the breath of the divine presence comes
on her nearer and nearer. “What! a laggard at vows and
prayers? Æneas of Troy a laggard? for that is the only
spell to part asunder the great closed lips of the terror-smitten 30
shrine.” She said, and was mute. A cold
shudder runs through the Teucrians’ iron frames, and their
king pours out his very soul in prayer: “Phœbus, ever
Troy’s pitying friend in her cruel agonies—thou who
didst level Paris’ Dardan[207] bow and string his Dardan arm 35
against the vast frame of Æacides[208]—by thy guidance I
have penetrated all these unknown seas that swathe
mighty continents. The Massylian tribes, thrust away by
Nature out of view, and the quicksands that environ their
coasts—now at last our hands are on the flying skirts of
Italy. Oh, let it suffice Troy’s fortune to have followed
us thus far! Ye too may now justly spare our nation of
Pergamus, gods and goddesses all, whose eyes were 5
affronted by Troy and the great glories of Dardan land.
And thou, most holy prophetess, that canst read the future
as the present, grant me—I am asking for no crown that
Fate does not owe me—grant a settlement in Latium to the
Teucrians and their wandering gods, even the travel-tost 10
deities of Troy. Then to Phœbus and his Trivian sister
I will set up a temple of solid marble, and appoint feast-days
in Phœbus’ name. For thee too an august shrine
is in store in that our future realm. For there I will lodge
thy oracles and the secret words of destiny which thou 15
shalt speak to my nation, and consecrate chosen men to
thy gracious service. Only commit not thy strains to
leaves, lest they float all confusedly the sport of the
whirling winds. Utter them with thine own mouth, I
implore thee.” So his prayer ended. 20

But the prophetess, not yet Phœbus’ willing slave, is


storming with giant frenzy in her cavern, as though she
hoped to unseat from her bosom the mighty god. All
the more sharply he plies her mouth with his bit till its
fury flags, tames her savage soul, and moulds her to his 25
will by strong constraint. And now the hundred mighty
doors of the chamber have flown open of their own accord,
and are wafting through the air the voice of prophecy: “O
you whose vast perils by sea are over at length! but on
land there are heavier yet in store. The sons of Dardanus 30
shall come to the realm of Lavinium—from this care set
your mind at rest—but think not that they shall also
have joy of their coming. War, savage war, and the
Tiber foaming with surges of blood, is the vision I see. No
lack for you of Simois, or Xanthus, or a Dorian[209] camp. 35
Another Achilles is reserved for Latium, he too goddess-born—nor
will Juno ever be seen to quit her fastened hold
on Troy—while you, a needy suppliant—what nation,
what city in Italy will not have had you knocking at its
gates! Once more will an alien bride bring on the Teucrians
all this woe—once more a foreign bed. But you,
yield not to affliction, but go forth all the bolder to meet it,
so far as your destiny gives you leave. The first glimpse of 5
safety, little as you dream it, shall dawn on you from a
Grecian town.”

Such are the words with which Cumæ’s Sibyl from her
cell shrills forth awful mysteries and booms again from
the cavern, robing her truth in darkness—such the violence 10
with which Apollo shakes the bridle in her frenzied mouth
and plies her bosom with his goad. Soon as her frenzy
abated and the madness of her lips grew calm, Æneas the
hero began: “No feature, awful maiden, that suffering can
show rises on my sight new or unlooked-for—I have 15
foreseen all and scanned all in fancy already. I have
but one prayer to make: since here it is that Fame tells of
the gate of the infernal monarch, and the murky pool of
Acheron’s overflow, grant me to pass to the sight, to
the presence of my loved father—teach the way, and unlock 20
the sacred doors. Him I bore away through flames
and a driving tempest of darts on these my shoulders and
rescued him from the midst of the foe: he was the companion
of my journey, and encountered with me all the
waves of ocean, all the terrors of sea and sky in his own 25
feeble frame, beyond the strength and the day of old age.
Nay more—that I would kneel to thee and approach thy
dwelling—this was his charge, his oft-repeated prayer.
Oh, of thy grace, pity the son and the sire; for thou art
all-powerful, nor is it for nought that Hecate has set thee 30
over the groves of Avernus. If Orpheus had the power to
fetch back the shade of his wife, by the help of his Thracian
lyre and its sounding strings—if Pollux redeemed
his brother by dying in turn with him, and went and returned
on the path those many times—why talk of Theseus, 35
why of great Alcides[210]? my line, like theirs, is from
Jove most high.”

Such were his prayers, while his hands clasped the altar,
when thus the prophetess began: “Heir of the blood of
gods, son of Anchises of Troy, easy is the going down to
Avernus—all night and all day the gate of gloomy
Pluto stands unbarred; but to retrace your footsteps, and
win your way back to the upper air, that is the labour, that 5
the task. There have been a few, favourites of gracious
Jove, or exalted to heaven by the blaze of inborn worth,
themselves sprung from the gods, who have had the power.
The whole intervening space is possessed by woods,
and lapped round by the black windings of Cocytus’[211] 10
stream. And now, if your heart’s yearning is so great,
your passion so strong, twice to stem the Stygian pool,
twice to gaze on the night of Tartarus—if it be your joy
to give scope to a madman’s striving—hear what must
first be done. Deep in the shade of a tree lurks a branch, all 15
of gold, foliage alike and limber twig, dedicated to the
service of the Juno of the shades; it is shrouded by the
whole labyrinth of the forest, closed in by the boskage that
darkens the glens. Yet none may pierce the subterranean
mystery, till a man have gathered from the tree that leafy 20
sprout of gold, for this it is that fair Proserpine has ordained
to be brought her as her own proper tribute. Pluck
off one, another is there unfailingly, of gold as pure, a twig
burgeoning with as fine an ore. Let then your eye be
keen to explore it, your hand quick to pluck it when duly 25
found, for it will follow the touch with willingness and
ease, if you have a call from Fate; if not, no strength of
yours will overcome it, no force of steel tear it away.
But, besides this, you have the breathless corpse of a
friend lying unburied—alas! you know it not—tainting 30
your whole fleet with the air of death, while you are asking
Heaven’s will, and lingering on this our threshold. Him
first consign to his proper place, and hide him in the grave.
Lead black cattle to the altar: be this the expiation to
pave your way. Thus at last you shall look on the groves 35
of Styx and the realms untrodden of the living.” She
said, and closed her lips in silence.

Æneas, with saddened face and steadfast eye, moves on,


leaving the cave behind, and revolves in his mind the secrets
of the future. Achates, ever faithful, walks at his
side, and plants his foot with no less consciousness of
care. Many were the things exchanged in their ranging
talk—who could be the dead comrade that the priestess 5
spoke of, what the corpse that needed burial. And lo!
Misenus, soon as they came, there on the dry beach they
see him, snatched by death that should have spared him—Misenus,
son of Æolus, than whom none was mightier to
stir men’s hearts with his clarion, and kindle with music 10
the war-god’s flame. Hector the great had been his chief:
in Hector’s service he performed a warrior’s part, famous
alike with the trumpet and the spear. But after the conquering
arm of Achilles robbed his master of life, valiant
hero, he made himself the comrade of the Dardan Æneas, 15
nor found the standard he followed meaner than of old.
But in those days, as he was making his hollow shell ring
over the waters, infatuate mortal, challenging the gods to
compete, Triton, roused to jealousy, seized him, if the
story be true, and plunged him in a moment in the billow 20
that laps among the rocks. So they all stood round, uttering
loud shrieks; louder than the rest Æneas the good.
And then without delay they set about the Sibyl’s bidding,
weeping sore, and in mournful rivalry heap up the funeral
pyre with trees, and carry it into the sky. 25

Away they go to an ancient wood, the wild beast’s tall


covert—down go the pitch-trees; the holm-oak rings with
the axe’s blows, and so do the ashen beams; the wedge
cleaves through the fissile[212] oak; they roll down from the
heights huge mountain ashes. There is Æneas, in this, 30
as in other labours, the first to cheer on his comrades, and
wielding a weapon like theirs; and thus he ponders in the
sad silence of his own breast, looking at the immeasurable
wood, and thus gives utterance to his prayer: “Oh that
at this moment that golden branch on the tree would reveal 35
itself to our sight in all this depth of forest! for I see that
in all things the prophetess has told us of you, Misenus,
alas! too truly!” Scarce had he spoken, when, as by
chance, a pair of doves come flying along the sky, under the
hero’s very eyes, and settle on the turf at his feet. At once
the mighty chief recognizes his mother’s birds, and gladly
breathes a second prayer: “Oh guide us on our way, wherever
it be, and as ye fly direct our steps into the grove 5
where the precious branch casts its shade on the rich
ground! Thou too forsake not our perplexity, O goddess
mother!” Thus much he said, and checked his advancing
foot, watching to see what prognostics they bring, whither
they aim their onward course. They, as they graze, go 10
ever forward on the wing, as far as the eyes of the travellers
can keep them in view. Then when they come to Avernus’
noisome jaws, swiftly they soar aloft, and gliding through
the clear sky, settle twain on the same tree, their chosen
seat, whence there flashed through the branches the contrasted 15
gleam of gold. Even as in the woods, in the cold of
midwinter, the mistletoe is wont to put forth new leaves, a
vegetable growth, but of no parent tree, and with its
yellow produce to surround the tapering boles, so looked
the leafy gold among the holm-oak’s dark shade—so in the 20
light breeze tinkled the foil. Æneas snatches it at once,
plucks it off with eagerness overpowering its delay, and
carries it to the home of the prophetic Sibyl.

Meantime, with not less zeal, the Teucrians on the


shore were mourning for Misenus, and paying the last 25
honour to the thankless ashes. First they raised a pile,
unctuous with pine-wood, and high-heaped with planks of
oak: they wreath its sides with gloomy foliage, and set
up before it funeral cypresses, and adorn it with a covering
of refulgent armour. Some make ready heated water and 30
cauldrons bubbling over the fire, and wash and anoint the
cold corpse. Loud rings the wail: then, the dirge over,
they place the limbs on the couch that claims them,
and fling over them purple garments, the dead men’s
usual covering. Some put their shoulders to the heavy 35
bier in melancholy service, and after ancestral fashion,
with averted eyes, apply the torch from under. The rich
heap is ablaze—offerings of incense, sacrificial viands, oil
streaming from the bowl. After that the ashes were fallen
in and the blaze was lulled, they drenched with wine the
relics and the thirsty embers on the pyre, and Corynæus
gathered up the bones, and stored them in a brazen urn.
He, too, carried round pure water, and sprinkled thrice 5
the comrades of the dead, scattering the thin drops with
a branch of fruitful olive—so he expiated the company,
and spoke the last solemn words. But good Æneas raises
over the dead a monument of massive size, setting up for
the hero his own proper arms, the oar and the trumpet, 10
under a skyey mountain, which is now from him called
Misenus, and retains from age to age the everlasting name.

This done, he hastens to execute the Sibyl’s bidding.


A deep cave there was, yawning wide with giant throat,
rough and shingly, shadowed by the black pool and the 15
gloom of the forest—a cave, over whose mouth no winged
thing could fly unharmed, so poisonous the breath that
exhaling from its pitchy jaws steamed up to the sky—whence
Greece has given the spot the name Aornos.[213]
Here first the priestess places in sacrificial station four 20
black-skinned bullocks, and empties wine over their
brows, and plucking from between their horns the hairs of
the crown, throws them into the hallowed flame, as the
firstfruits of worship, with loud cries on Hecate, queen in
heaven and Erebus both. Others put the knife to the 25
throat, and catch in chargers the steaming blood. With
his own sword Æneas strikes down a lamb of sable fleece,
for the Furies’[214] mother and her mighty sister, and a
barren heifer for thee, dread Proserpine. Then to the
Stygian monarch he rears altars, blazing through the 30
darkness, and piles on the flame the bulls’ carcases
entire, pouring fat oil on the entrails all aglow. When,
hark! as the sun began to glimmer and dawn, the ground
is bellowing under their feet, and the wood-crowned heights
are nodding, and the baying of dogs sounds through the 35
gloom, for the goddess is at hand. “Hence, hence with
your unhallowed feet!” clamours the prophetess, “and rid
the whole grove of your presence. And you—strike into
the road, and pluck your sword from his scabbard—now
is the hour for courage, Æneas, now for a stout heart.”
No more she said, but flung herself wildly into the cavern’s
mouth; and he, with no faltering step, keeps pace with his
guide. 5

Ye gods, whose empire is the shades—spirits of silence,


Chaos and Phlegethon, stretching wide in the stillness of
night, suffer me to tell what has reached my ears; grant
me your aid to reveal things buried underground, deep and
dark. 10

On they went, darkling in solitary night, far into the


gloom, through Pluto’s void halls and ghostly realms—like
a journey in a wood under the niggard beams of a
doubtful moon, when Jupiter has shrouded heaven in
shadow, and black Night has stolen the colour from 15
Nature’s face. There before the threshold, in the very
mouth of Hell, Agony and the fiends of Remorse have made
their lair: there dwell wan Diseases, and woful Age, and
Terror, and Hunger that prompts to Sin, and loathly
Want—shapes of hideous view—and Death, and Suffering; 20
then comes Sleep, Death’s blood-brother, and the
soul’s guilty joys, and deadly War couched in the gate,
and the Furies’ iron chambers, and frantic Strife, with
bloody fillets wreathed in her snaky hair.

In the midst there stands, with boughs and aged arms 25


outspread, a massive elm, of broad shade, the chosen
seat, so Rumour tells, of bodiless dreams, which cling
close to its every leaf. There, too, are a hundred monstrous
shapes of wild beasts of divers kinds, Centaurs
stalled in the entrance and two-formed Scyllas, and 30
Briareus,[215] the hundred-handed, and the portent of Lerna,[216]
hissing fearfully, and Chimæra[217] in her panoply of flames,
Gorgons,[218] and Harpies, and the semblance of the three-bodied
spectre. At once Æneas grasps his sword, in the
haste of sudden alarm, and meets their advance with its 35
drawn blade; and did not his companion warn him, of
her own knowledge, that they are but thin unbodied
spirits flitting in a hollow mask of substance, he would
be rushing among them, and slashing shadows asunder
with the steel’s unavailing blows.

Hence runs the road that leads to the waters of Tartarean


Acheron, whose gulfy stream, churning mud in its
monstrous depths, is all aglow, and disgorges into Cocytus 5
the whole of its sand. These waters are guarded by a
grisly ferryman, frightful and foul—Charon; his chin an
uncleared forest of hoary hair; his eyes a mass of flame;
while his uncleanly garb hangs from his shoulders, gathered
into a knot. With his own hand he pushes on the craft 10
with a pole, and trims the sails, and moves the dead
heavily along in his boat of iron-gray, himself already in
years; but a god’s old age is green and vigorous. Towards
him the whole crowd was pouring to the bank: matrons
and warriors, and bodies of mighty heroes discharged of 15
life, boys and unwedded maidens, and youths laid on the
pile of death in their parents’ eyes—many as are the
leaves that drop and fall in the woods in autumn’s early
cold, or many as are the birds that flock massed together
from the deep to the land, when the wintry year drives 20
them over sea to tenant a sunnier clime. There they
stood, each praying that he might be the first to cross,
with hands yearningly outstretched towards the further
shore; but the grim boatman takes on board now these,
now those, while others he drives away, and bars them 25
from the river’s brink. Æneas cries as a man perplexed
and startled by the tumult: “Tell me, dread maiden,
what means this concourse to the stream? Of what are
these spirits in quest? What choice decides that these
shall retire from the shore, while those are rowing through 30
that leaden pool?” To him in brief returned the aged
priestess: “Son of Anchises, Heaven’s undoubted offspring,
before you are Cocytus’ depths and the marshy
flood of Styx, that power by whose name the gods fear
to swear in vain. The whole multitude you see here is 35
helpless and tombless; Charon is the ferryman; those
who ride the wave are the buried. He may not ferry
them from the dreadful banks across that noisy current
till their bones have found a place of rest. A hundred
years they wander hovering about these shores; then at
last they embark, and see again the flood of their longing.”
Anchises’ son stood and paused, musing deeply, and pitying
at his heart a lot so unkind. Yes, there he sees, sadly 5
wandering without death’s last tribute, Leucaspis and
Orontes, the captain of Lycia’s fleet: both had sailed
with him from Troy over the stormy water, and the south
wind whelmed them both, engulfing the vessel and its
crew. 10

Lo! he sees his pilot, Palinurus, moving along—Palinurus,


who but now, while voyaging from Libya, his eyes
bent on the stars, had fallen’ from the stern, flung out
into the wide waste of waters. So when he had at last
taken knowledge of his features, now saddened, in the 15
deep gloom, he thus accosts him first: “Who was it,
Palinurus, of all the gods, that tore you from us, and
whelmed you in the wide sea? Tell me who. Till now
I never found him false; but in this one response Apollo
has proved a cheat, foretelling that you would be unharmed 20
on the deep, and win your way to the Ausonian
frontier, and thus it is that he keeps his word!” “Nay,”
returned he, “my chief, Anchises’ son, Phœbus’ tripod has
told you no lie, nor did any god whelm me in the sea.
No, I chanced to fall, tearing away by main force the 25
rudder, to which I was clinging like sentry to his post,
as I guided your course, and dragging it with me in my
headlong whirl. Witness those cruel waters, I felt no
fear for my own life like that which seized me for your
ship, lest, disarmed and disabled, shaken loose from her 30
ruler’s hand, she should give way under the great sea that
was rising then. Three long nights of storm the south
wind swept me over the vast wilderness of convulsed
ocean. Hardly at last, at the fourth dawn, I looked out
aloft upon Italy from the crest of the wave. Stroke by 35
stroke I was swimming to shore; and now I was just
laying hold on safety, had not the savage natives come
on me, sword in hand, clogged as I was with my dripping
clothes, and clutching with talon fingers the steep mountain-top,
and deemed blindly they had found a prize.
Now the wave is my home, and the winds keep tossing
me on the beach. Oh, by heaven’s pleasant sunshine
and bright sky; by your father, I adjure you; by the 5
promise growing up with your Iulus, rescue me with that
unconquered arm from this cruel fate: be yourself, and
either spread earth upon me, for that you can surely do,
and put back to Velia’s haven; or, if any way there be,
any that your goddess mother can reveal—for well I 10
ween it is not without Heaven’s leave that you purpose
to stem these fearful tides and the reluctant pool of Styx—stretch
your hand to your poor friend, and take me
with you over the water, that at least I may find in death
a place of rest and peace.” So had he spoken, when thus 15
the priestess begins: “What demon, Palinurus, has set
on you so monstrous a desire? You, unburied, look on
the Stygian water, and the dread river of the furies?
You set foot on the bank unbidden? Cease to dream
that Heaven’s destiny can be swayed by prayer. Yet 20
hear and retain a word which may console your hard lot.
For know that the dwellers in that fatal border, goaded
far and wide through their cities by prodigies from heaven,
shall propitiate your dust: they shall erect a tomb, and
through that tomb send down your funeral dues, and the 25
spot shall bear forever the name of Palinurus.” These
words allayed his cares, and banished for a while grief
from that sad bosom: his heart leaps to the land that is
called by his name.

They accordingly continue their journey, and approach 30


the river. Soon as the boatman saw them, at the moment,
from the wave of Styx, moving through the stilly forest,
and turning their steps to the bank, he first bespeaks
them thus, and assails them unaccosted: “You, whoever
you are, that are making for these waters of ours in warlike 35
trim, speak your errand from the spot where you
are, and come no nearer. This is the place for the shadows,
for Sleep and slumberous Night. The bodies of the living
may not be ferried in my Stygian barque. Nay, it was
not to my joy that I gave Alcides a passage over the lake,
nor Theseus and Pirithous, born of gods though they
were, and of strength unsubdued. The one laid a jailer’s
hand on the warder of Tartarus, even at the foot of the 5
king’s own throne, and dragged him trembling along:
the others essayed to carry off the queen from Pluto’s
bridal chamber.” To which the Amphrysian priestess
replied in brief: “Here there are no stratagems like those;
be not discomposed; these weapons are not borne for 10
violence; the monstrous guardian of your gate is free to
terrify the bloodless spectres from his den with his unending
bark; Proserpine is free to keep her uncle’s home
as faithful wife should. This is Æneas of Troy, renowned
for piety and arms alike: it is to see his father that he 15
is going down to Erebus’ lowest depth of gloom. If thou
art moved in nought by the spectacle of piety so signal,
yet let this branch”—she uncovered the branch which
was concealed in her robe—‘claim recognition.’ At
once the angry swell subsides, and the breast is calm. 20
No further parley. Gazing in wonder at the sacred offering
of the fated bough, last seen so long ago, he turns to
them the sea-green boat, and draws near the bank.
Then he dislodges other ghostly passengers who were sitting
along the benches, and clears the gangways, while 25
he takes into the vessel’s hollow the mighty Æneas. The
sutures of the boat cracked beneath the weight, as through
its rents it drew in large draughts of marsh-water. At
length priestess and prince are safe across the flood, set
down amid featureless mud and blue-green rushes. 30

Cerberus,[219] the monster, makes the whole realm ring


with his three barking throats, as he lies in giant length
fronting them in his den’s mouth. The priestess, seeing
the snakes already bristling on his neck, throws him a
morsel steeped in the slumber of honey and medicated 35
meal. He, in the frenzy of hunger, opens his triple jaws
to catch it as it comes, and stretches his enormous back at
length on the ground, till his huge bulk covers the den.
Æneas masters the approach while the warder sleeps, and
swiftly passes from the bank of the river without return.

At once there breaks on his ear a voice of mighty wailing,


infant spirits sobbing and crying on the threshold,
babes that, portionless of the sweets of life, were snatched 5
from the breast by the black death-day’s tyranny, and
whelmed in untimely night. Next to them are those
who were done to death by false accusation. Yet let
none think that the lot of award or the judge’s sentence
are wanting here. There sits Minos,[220] the president, urn 10
in hand: he summons an assembly of the speechless, and
takes cognizance of earthly lives and earthly sins.

Next to them comes the dwelling-place of the sons of


sorrow, who, though guiltless, procured their own death by
violence, and, for mere hatred of the sunshine, flung their 15
lives away. Oh, how gladly would they now, in the air
above, bear to the end the load of poverty and the full
extremity of toil! But Fate bars the way: the unlovely
pool swathes them round in her doleful waters, and Styx,
with her ninefold windings, keeps them fast. 20

Not far hence the traveller’s eye sees stretching on every


side the Mourning Fields: such the name they bear.
Here dwell those whom cruel Love’s consuming tooth
has eaten to the heart, in the privacy of hidden walks
and an enshrouding myrtle wood: their tender sorrows 25
quit them not even in death. In this region he sees
Phædra and Procris, and sad Eriphyle, pointing to the
wounds of her ruthless son, and Evadne, and Pasiphaë:
along with them moves Laodamia, and Cæneus, once a
man, now a woman, brought back by the turn of fate to 30
her former self. Among these was Phœnicia’s daughter,
Dido, fresh from her death-wound, wandering in that
mighty wood: soon as the Trojan hero stood at her side,
and knew her, looming dimly through the dusk—as a
man sees or thinks he sees through the clouds, when the 35
month is young, the rising moon—his tears broke forth,
and he addressed her tenderly and lovingly. “Unhappy
Dido! and was it then a true messenger that reached
me with the tale that you were dead: that the sword
had done its worst? Was it, alas, to a grave that I
brought you? By the stars of heaven I swear, by the
powers above, by all that is most sacred here underground,
against my will, fair queen, I quitted your coast. 5
No; it was the command of the gods; the same stern
force which compels me now to pass through this realm
of shade, this wilderness of squalor and abysmal night;
it was that which drove me by its uttered will: nor could
I have thought that my departure would bring on you 10
such violence of grief. Stay your step, and withdraw not
from the look I bend on you. Whom would you shun?
the last word which fate suffers me to address you is this.”
With words like these, Æneas kept soothing the soul that
blazed forth through those scowling eyes, and moving 15
himself to tears. She stood with averted head and eyes
on the ground, her features as little moved by the speech
he essayed as if she held the station of a stubborn flint,
or a crag of Marpessa.[221] At length she flung herself
away, and, unforgiving still, fled into the shadow of the 20
wood, where her former lord, Sychæus, answers her sorrows
with his, and gives her full measure for her love.
Yet, none the less, Æneas, thrilled through and through
by her cruel fate, follows far on her track with tears, and
sends his pity along with her. 25

Thence he turns, to encounter the appointed way.


And now they were already in the furthest region, the
separate place tenanted by the great heroes of war.
Here there meets him Tydeus, here Parthenopæus, illustrious
in arms, and the spectre of pale Adrastus. Here 30
are chiefs of Dardan line, wailed long and loudly in the
upper air as they lay low in fight: as he saw them all in
long array, he groaned heavily. Glaucus and Medon, and
Thersilochus, the three sons of Antenor, and Polyphœtes,
Ceres’ priest, and Idæus, with his hand still on the car, 35
still on the armour. They surround him, right and left,
the ghostly crowd; one look is not sufficient: they would
fain linger on and on, and step side by side with him,
and learn the cause of his coming. But the nobles of the
Danaans, and the flower of Agamemnon’s bands, when
they saw the hero and his armour gleaming through the
shade, were smitten with strange alarm: some turn their
backs in flight, as erst they fled to the ships: others raise 5
a feeble war-shout. The cry they essay mocks their
straining throats.

Here it is that he sees Priam’s son, mangled all over,


Deiphobus, his face cruelly marred—face and both
hands—his temples despoiled of his ears, and his nose 10
lopped by unseemly carnage. Scarce, in truth, he recognized
him, trembling as he was, and trying to hide the
terrible vengeance wreaked on him: unaccosted, he addresses
him in the tones he knew of old: “Deiphobus,
mighty warrior, scion of Teucer’s illustrious stock, who 15
has had the ambition to avenge himself so cruelly? who
has had his will of you thus? For me, Rumour told me
on that fatal night that you had sunk down, tired with
the work of slaughtering the Greeks, on a heap of undistinguished
carnage. Then with my own hand, I set up 20
an empty tomb on the Rhœtean shore, and thrice with a
loud voice invoked your spirit. There are your name and
your arms to keep the spot in memory: your self, dear
friend, I could not see, so as to give you repose in the
fatherland I was leaving.” To whom the son of Priam: 25
“Dear friend, you have failed in nought: all that Deiphobus
could claim has been paid by you to him and to his
shade. No; it was my own destiny and the deadly
wickedness of the Spartan woman that plunged me thus
deep in ill: these tokens are of her leaving. How we 30
spent that fatal night in treacherous joyance you know
well: too good cause is there to bear it in mind. When
the fateful horse at one bound surmounted the height of
Pergamus, and brought a mailclad infantry in its laden
womb, she feigned a solemn dance, and led round the 35
city Phrygian dames in Bacchic ecstasy; herself in their
midst raising a mighty torch aloft, and calling to the
Danaans from the top of the citadel. That hour I, spent
with care and overborne with sleep, was in the hold of

You might also like