100% found this document useful (1 vote)
420 views55 pages

Download full Essential MATLAB for engineers and scientists Hahn ebook all chapters

Hahn

Uploaded by

mowerjansska
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
420 views55 pages

Download full Essential MATLAB for engineers and scientists Hahn ebook all chapters

Hahn

Uploaded by

mowerjansska
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Essential MATLAB for engineers and scientists Hahn

https://textbookfull.com/product/essential-matlab-for-
engineers-and-scientists-hahn-3/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


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

Essential MATLAB for engineers and scientists Hahn

https://textbookfull.com/product/essential-matlab-for-engineers-and-
scientists-hahn-2/

textboxfull.com

Essential MATLAB for engineers and scientists Hahn

https://textbookfull.com/product/essential-matlab-for-engineers-and-
scientists-hahn-3/

textboxfull.com

Essential MATLAB for engineers and scientists Sixth


Edition. Edition Hahn

https://textbookfull.com/product/essential-matlab-for-engineers-and-
scientists-sixth-edition-edition-hahn/

textboxfull.com

Essential Quotes For Scientists And Engineers Konstantin


K. Likharev

https://textbookfull.com/product/essential-quotes-for-scientists-and-
engineers-konstantin-k-likharev/

textboxfull.com
Numerical Methods for Engineers and Scientists Using
MATLAB Second Edition Esfandiari

https://textbookfull.com/product/numerical-methods-for-engineers-and-
scientists-using-matlab-second-edition-esfandiari/

textboxfull.com

Numerical Methods for Engineers and Scientists Using


MATLAB® Ramin S. Esfandiari

https://textbookfull.com/product/numerical-methods-for-engineers-and-
scientists-using-matlab-ramin-s-esfandiari/

textboxfull.com

MATLAB Programming for Biomedical Engineers and Scientists


Andrew P. King And Paul Aljabar (Auth.)

https://textbookfull.com/product/matlab-programming-for-biomedical-
engineers-and-scientists-andrew-p-king-and-paul-aljabar-auth/

textboxfull.com

Applied Numerical Methods with MATLAB for Engineers and


Scientists Fourth Edition Steven C. Chapra Dr.

https://textbookfull.com/product/applied-numerical-methods-with-
matlab-for-engineers-and-scientists-fourth-edition-steven-c-chapra-dr/

textboxfull.com

The oceanographer's companion : essential nautical skills


for seagoing scientists and engineers 1st Edition Maul

https://textbookfull.com/product/the-oceanographers-companion-
essential-nautical-skills-for-seagoing-scientists-and-engineers-1st-
edition-maul/
textboxfull.com
Essential MATLAB
for Engineers and Scientists
This page intentionally left blank
Essential MATLAB
for Engineers and Scientists
Sixth Edition

Brian H. Hahn
Daniel T. Valentine

AMSTERDAM • BOSTON • HEIDELBERG • LONDON


NEW YORK • OXFORD • PARIS • SAN DIEGO
SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO
Academic Press is an imprint of Elsevier
Academic Press is an imprint of Elsevier
50 Hampshire Street, 5th Floor, Cambridge, MA 02139, United States
525 B Street, Suite 1800, San Diego, CA 92101-4495, United States
The Boulevard, Langford Lane, Kidlington, Oxford OX5 1GB, United Kingdom
125, London Wall, EC2Y, 5AS, United Kingdom

Copyright © 2017, 2013, 2010 Daniel T. Valentine. Published by Elsevier Ltd. All rights reserved.
Copyright © 2007, 2006, 2002 Brian D. Hahn and Daniel T. Valentine. Published by Elsevier Ltd.

MATLAB® is a trademark of The MathWorks, Inc. and is 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® software or related products does not constitute endorsement
or sponsorship by The MathWorks of a particular pedagogical approach or particular use of the
MATLAB® software.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior
written permission of the publisher.

Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford,
UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, E-mail: [email protected]. You may
also complete your request online via the Elsevier homepage (http://www.elsevier.com), by selecting
“Support & Contact” then “Copyright and Permission” and then “Obtaining Permissions.”

Library of Congress Cataloging-in-Publication Data


A catalog record for this book is available from the Library of Congress.

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library.

ISBN: 978-0-08-100877-5

For information on all Academic Press publications


visit our website at https://www.elsevierdirect.com

Publisher: Todd Green


Acquisition Editor: Stephen Merken
Editorial Project Manager: Nate McFadden
Production Project Manager: Stalin Viswanathan
Designer: Matthew Limbert

Typeset by VTeX
Contents

PREFACE .............................................................................................................xv

Part 1 Essentials................................................................. 1
CHAPTER 1 Introduction............................................................................... 3
1.1 Using MATLAB..............................................................................5
1.1.1 Arithmetic .........................................................................5
1.1.2 Variables............................................................................7
1.1.3 Mathematical functions ...................................................8
1.1.4 Functions and commands ...............................................8
1.1.5 Vectors...............................................................................9
1.1.6 Linear equations.............................................................11
1.1.7 Tutorials and demos.......................................................12
1.2 The desktop ................................................................................13
1.2.1 Using the Editor and running a script ..........................13
1.2.2 Help, publish and view ...................................................16
1.2.3 Symbolics and the MuPAD notebook APP....................18
1.2.4 Other APPS .....................................................................23
1.2.5 Additional features .........................................................23
1.3 Sample program ........................................................................25
1.3.1 Cut and paste..................................................................25
1.3.2 Saving a program: script files .......................................27
Current directory ................................................................................28
Running a script from the current folder browser ..........................29
1.3.3 A program in action........................................................29
Summary ....................................................................................30
Exercises.....................................................................................31

CHAPTER 2 MATLAB Fundamentals ......................................................... 33


2.1 Variables .....................................................................................33
2.1.1 Case sensitivity ...............................................................34
2.2 The workspace ...........................................................................34
2.2.1 Adding commonly used constants to the workspace ..35
2.3 Arrays: Vectors and matrices....................................................36
2.3.1 Initializing vectors: Explicit lists ...................................36
v
vi Contents

2.3.2 Initializing vectors: The colon operator ........................37


2.3.3 The linspace and logspace functions.........................38
2.3.4 Transposing vectors .......................................................39
2.3.5 Subscripts .......................................................................39
2.3.6 Matrices ..........................................................................40
2.3.7 Capturing output ............................................................40
2.3.8 Structure plan.................................................................41
2.4 Vertical motion under gravity....................................................42
2.5 Operators, expressions, and statements .................................44
2.5.1 Numbers .........................................................................45
2.5.2 Data types .......................................................................45
2.5.3 Arithmetic operators......................................................46
2.5.4 Operator precedence .....................................................46
2.5.5 The colon operator .........................................................47
2.5.6 The transpose operator .................................................47
2.5.7 Arithmetic operations on arrays ...................................48
2.5.8 Expressions.....................................................................49
2.5.9 Statements......................................................................49
2.5.10 Statements, commands, and functions........................50
2.5.11 Formula vectorization ....................................................51
2.6 Output..........................................................................................54
2.6.1 The disp statement........................................................54
2.6.2 The format command ....................................................55
2.6.3 Scale factors ...................................................................56
2.7 Repeating with for.....................................................................57
2.7.1 Square roots with Newton’s method ............................58
2.7.2 Factorials! .......................................................................59
2.7.3 Limit of a sequence ........................................................59
2.7.4 The basic for construct .................................................60
2.7.5 for in a single line..........................................................61
2.7.6 More general for ...........................................................61
2.7.7 Avoid for loops by vectorizing!......................................62
2.8 Decisions.....................................................................................64
2.8.1 The one-line if statement ............................................64
2.8.2 The if-else construct...................................................66
2.8.3 The one-line if-else statement ..................................67
2.8.4 elseif .............................................................................67
2.8.5 Logical operators ...........................................................68
2.8.6 Multiple ifs versus elseif ...........................................69
2.8.7 Nested ifs ......................................................................70
2.8.8 Vectorizing ifs?..............................................................71
2.8.9 The switch statement....................................................71
2.9 Complex numbers......................................................................72
Summary ....................................................................................74
Exercises.....................................................................................76

CHAPTER 3 Program Design and Algorithm Development ..................... 83


3.1 The program design process.....................................................84
Contents vii

3.1.1 The projectile problem ...................................................87


3.2 Programming MATLAB functions .............................................92
3.2.1 Inline objects: Harmonic oscillators.............................92
3.2.2 MATLAB function: y = f (x ).............................................93
Summary ....................................................................................96
Exercise.......................................................................................96

CHAPTER 4 MATLAB Functions and Data Import-Export Utilities.......... 99


4.1 Common functions.....................................................................99
4.2 Importing and exporting data..................................................104
4.2.1 The load and save commands....................................104
4.2.2 Exporting text (ASCII) data...........................................104
4.2.3 Importing text (ASCII) data ..........................................105
4.2.4 Exporting binary data...................................................105
4.2.5 Importing binary data...................................................106
Summary ..................................................................................106
Exercises...................................................................................106

CHAPTER 5 Logical Vectors ..................................................................... 109


5.1 Examples ..................................................................................110
5.1.1 Discontinuous graphs ..................................................110
5.1.2 Avoiding division by zero ..............................................111
5.1.3 Avoiding infinity.............................................................112
5.1.4 Counting random numbers .........................................113
5.1.5 Rolling dice ...................................................................114
5.2 Logical operators .....................................................................114
5.2.1 Operator precedence ...................................................116
5.2.2 Danger...........................................................................116
5.2.3 Logical operators and vectors.....................................117
5.3 Subscripting with logical vectors............................................118
5.4 Logical functions ......................................................................119
5.4.1 Using any and all ........................................................120
5.5 Logical vectors instead of elseif ladders.............................121
Summary ..................................................................................123
Exercises...................................................................................124

CHAPTER 6 Matrices and Arrays ............................................................. 127


6.1 Matrices ....................................................................................127
6.1.1 A concrete example......................................................127
6.1.2 Creating matrices.........................................................129
6.1.3 Subscripts .....................................................................129
6.1.4 Transpose......................................................................130
6.1.5 The colon operator .......................................................130
6.1.6 Duplicating rows and columns: tiling .........................133
6.1.7 Deleting rows and columns .........................................134
6.1.8 Elementary matrices....................................................135
6.1.9 Specialized matrices....................................................136
6.1.10 Using MATLAB functions with matrices .....................137
viii Contents

6.1.11 Manipulating matrices .................................................138


6.1.12 Array (element-by-element) operations on matrices138
6.1.13 Matrices and for ..........................................................139
6.1.14 Visualization of matrices .............................................140
6.1.15 Vectorizing nested fors: loan repayment tables .......140
6.1.16 Multi-dimensional arrays ............................................142
6.2 Matrix operations .....................................................................143
6.2.1 Matrix multiplication....................................................143
6.2.2 Matrix exponentiation ..................................................145
6.3 Other matrix functions.............................................................146
6.4 Population growth: Leslie matrices .......................................146
6.5 Markov processes ....................................................................150
6.5.1 A random walk..............................................................150
6.6 Linear equations ......................................................................152
6.6.1 MATLAB’s solution .......................................................153
6.6.2 The residual ..................................................................154
6.6.3 Over-determined systems ...........................................154
6.6.4 Under-determined systems ........................................155
6.6.5 Ill conditioning ..............................................................155
6.6.6 Matrix division...............................................................156
6.7 Sparse matrices .......................................................................158
Summary ..................................................................................160
Exercises...................................................................................161

CHAPTER 7 Function M-files.................................................................... 163


7.1 Example: Newton’s method again ..........................................163
7.2 Basic rules ................................................................................165
7.2.1 Subfunctions .................................................................170
7.2.2 Private functions ..........................................................170
7.2.3 P-code files ...................................................................170
7.2.4 Improving M-file performance with the profiler ........171
7.3 Function handles......................................................................171
7.4 Command/function duality......................................................173
7.5 Function name resolution .......................................................174
7.6 Debugging M-files....................................................................174
7.6.1 Debugging a script .......................................................174
7.6.2 Debugging a function ...................................................176
7.7 Recursion..................................................................................176
Summary ..................................................................................178
Exercises...................................................................................179

CHAPTER 8 Loops ..................................................................................... 181


8.1 Determinate repetition with for .............................................181
8.1.1 Binomial coefficient .....................................................181
8.1.2 Update processes .........................................................182
8.1.3 Nested fors ..................................................................184
8.2 Indeterminate repetition with while ......................................184
8.2.1 A guessing game ..........................................................184
Contents ix

8.2.2 The while statement....................................................185


8.2.3 Doubling time of an investment ..................................185
8.2.4 Prime numbers ............................................................187
8.2.5 Projectile trajectory......................................................188
8.2.6 break and continue.....................................................190
8.2.7 Menus............................................................................190
Summary ..................................................................................191
Exercises...................................................................................192

CHAPTER 9 MATLAB Graphics................................................................. 197


9.1 Basic 2-D graphs......................................................................197
9.1.1 Labels............................................................................198
9.1.2 Multiple plots on the same axes .................................199
9.1.3 Line styles, markers and color....................................200
9.1.4 Axis limits......................................................................200
9.1.5 Multiple plots in a figure: subplot..............................202
9.1.6 figure, clf and cla.....................................................203
9.1.7 Graphical input .............................................................203
9.1.8 Logarithmic plots .........................................................203
9.1.9 Polar plots.....................................................................204
9.1.10 Plotting rapidly changing mathematical functions:
fplot .............................................................................205
9.1.11 The property editor.......................................................206
9.2 3-D plots ...................................................................................206
9.2.1 plot3 .............................................................................206
9.2.2 Animated 3-D plots with comet3 .................................207
9.2.3 Mesh surfaces ..............................................................207
9.2.4 Contour plots ................................................................209
9.2.5 Cropping a surface with NaNs ......................................211
9.2.6 Visualizing vector fields ...............................................211
9.2.7 Visualization of matrices .............................................212
9.2.8 Rotation of 3-D graphs.................................................213
9.3 Handle graphics .......................................................................214
9.3.1 Getting handles ............................................................214
9.3.2 Graphics object properties and how to change them215
9.3.3 A vector of handles.......................................................217
9.3.4 Graphics object creation functions .............................218
9.3.5 Parenting.......................................................................218
9.3.6 Positioning figures .......................................................219
9.4 Editing plots..............................................................................220
9.4.1 Plot edit mode...............................................................220
9.4.2 Property Editor .............................................................221
9.5 Animation..................................................................................222
9.5.1 Animation with Handle Graphics.................................222
9.6 Color etc....................................................................................225
9.6.1 Colormaps.....................................................................225
9.6.2 Color of surface plots...................................................226
9.6.3 Truecolor .......................................................................228
x Contents

9.7 Lighting and camera ................................................................228


9.8 Saving, printing and exporting graphs ...................................229
9.8.1 Saving and opening figure files ...................................229
9.8.2 Printing a graph............................................................229
9.8.3 Exporting a graph .........................................................229
Summary ..................................................................................230
Exercises...................................................................................231

CHAPTER 10 Vectors as Arrays and Other Data Structures.................... 235


10.1 Update processes.....................................................................235
10.1.1 Unit time steps .............................................................236
10.1.2 Non-unit time steps .....................................................238
10.1.3 Using a function............................................................239
10.1.4 Exact solution ...............................................................241
10.2 Frequencies, bar charts and histograms ...............................242
10.2.1 A random walk..............................................................242
10.2.2 Histograms ...................................................................243
10.3 Sorting.......................................................................................244
10.3.1 Bubble Sort ...................................................................244
10.3.2 MATLAB’s sort .............................................................246
10.4 Structures .................................................................................247
10.5 Cell arrays ................................................................................249
10.5.1 Assigning data to cell arrays .......................................249
10.5.2 Accessing data in cell arrays.......................................250
10.5.3 Using cell arrays ..........................................................251
10.5.4 Displaying and visualizing cell arrays ........................252
10.6 Classes and objects .................................................................252
Summary ..................................................................................253

CHAPTER 11 Errors and Pitfalls ................................................................ 255


11.1 Syntax errors ............................................................................255
11.1.1 Incompatible vector sizes ............................................256
11.1.2 Name hiding..................................................................256
11.2 Logic errors ..............................................................................256
11.3 Rounding error .........................................................................257
Summary ..................................................................................258
Chapter exercises ....................................................................258

Part 2 Applications ..........................................................261


CHAPTER 12 Dynamical Systems .............................................................. 263
12.1 Cantilever beam .......................................................................265
12.2 Electric current ........................................................................266
12.3 Free fall .....................................................................................269
12.4 Projectile with friction..............................................................278
Summary ..................................................................................281
Exercises...................................................................................282

CHAPTER 13 Simulation ............................................................................. 283


Contents xi

13.1 Random number generation ...................................................283


13.1.1 Seeding rand.................................................................284
13.2 Spinning coins ..........................................................................284
13.3 Rolling dice ...............................................................................285
13.4 Bacteria division.......................................................................286
13.5 A random walk .........................................................................286
13.6 Traffic flow ................................................................................288
13.7 Normal (Gaussian) random numbers ....................................291
Summary ..................................................................................291
Exercises...................................................................................292

CHAPTER 14 Introduction to Numerical Methods.................................... 295


14.1 Equations ..................................................................................295
14.1.1 Newton’s method .........................................................295
14.1.2 The Bisection method ..................................................297
14.1.3 fzero .............................................................................299
14.1.4 roots .............................................................................299
14.2 Integration ................................................................................300
14.2.1 The Trapezoidal rule ....................................................300
14.2.2 Simpson’s rule..............................................................301
14.2.3 quad ...............................................................................302
14.3 Numerical differentiation ........................................................302
14.3.1 diff ...............................................................................303
14.4 First-order differential equations ...........................................304
14.4.1 Euler’s method .............................................................304
14.4.2 Example: bacteria growth............................................305
14.4.3 Alternative subscript notation.....................................307
14.4.4 A predictor-corrector method .....................................307
14.5 Linear ordinary differential equations (LODEs) .....................308
14.6 Runge-Kutta methods .............................................................309
14.6.1 A single differential equation ......................................309
14.6.2 Systems of differential equations: chaos ...................310
14.6.3 Passing additional parameters to an ODE solver ......312
14.7 A partial differential equation .................................................314
14.7.1 Heat conduction............................................................314
14.8 Complex variables and conformal mapping ..........................317
14.9 Other numerical methods .......................................................319
Summary ..................................................................................320
Exercises...................................................................................321

CHAPTER 15 Signal Processing ................................................................. 325


15.1 Harmonic analysis ...................................................................326
15.2 Fast Fourier Transform (FFT)..................................................331

CHAPTER 16 SIMULINK Toolbox............................................................. 337


16.1 Mass-spring-damper dynamic system ..................................342
16.2 Bouncing ball dynamic system ...............................................345
16.3 The van der Pol oscillator........................................................347
xii Contents

16.4 The Duffing oscillator ..............................................................350


Exercises...................................................................................351

CHAPTER 17 Symbolics Toolbox ................................................................ 355


17.1 Algebra......................................................................................356
17.1.1 Polynomials ..................................................................357
17.1.2 Vectors...........................................................................359
17.1.3 Matrices ........................................................................360
17.2 Calculus ....................................................................................363
17.3 Laplace and Z transforms .......................................................366
17.4 Generalized functions..............................................................367
17.5 Differential equations ..............................................................369
17.6 Implementation of funtool, MuPAD and help.........................370
17.6.1 The funtool ....................................................................370
17.6.2 The MuPAD notebook∗ and Symbolic help.................370
Exercises...................................................................................373
APPENDIX A Syntax: Quick Reference ...................................................... 375
A.1 Expressions ..............................................................................375
A.2 Function M-files .......................................................................375
A.3 Graphics ....................................................................................375
A.4 if and switch...........................................................................376
A.5 for and while...........................................................................377
A.6 Input/output..............................................................................377
A.7 load/save..................................................................................378
A.8 Vectors and matrices ...............................................................378
APPENDIX B Operators .............................................................................. 381
APPENDIX C Command and Function: Quick Reference......................... 383
C.1 General-purpose commands ..................................................383
C.1.1 Managing variables and the workspace .....................383
C.1.2 Files and the operating system...................................383
C.1.3 Controlling the Command Window .............................384
C.1.4 Starting and quitting MATLAB.....................................384
C.2 Logical functions ......................................................................384
C.3 MATLAB programming tools...................................................384
C.3.1 Interactive input............................................................385
C.4 Matrices ....................................................................................385
C.4.1 Special variables and constants..................................385
C.4.2 Time and date ...............................................................385
C.4.3 Matrix manipulation .....................................................385
C.4.4 Specialized matrices....................................................386
C.5 Mathematical functions ...........................................................386
C.6 Matrix functions .......................................................................387
C.7 Data analysis ............................................................................387
C.8 Polynomial functions ...............................................................387
C.9 Function functions ...................................................................387
C.10 Sparse matrix functions ..........................................................388
C.11 Character string functions ......................................................388
Contents xiii

C.12 File I/O functions ......................................................................388


C.13 2D graphics...............................................................................388
C.14 3D graphics...............................................................................389
C.15 General......................................................................................389
APPENDIX D Solutions to Selected Exercises .......................................... 391
INDEX ............................................................................................................... 403
This page intentionally left blank
Preface

The main reason for a sixth edition of Essential MATLAB for Engineers and Scien-
tists is to keep up with MATLAB, now in its latest version (9.0 Version R2016a).
Like the previous editions, this one presents MATLAB as a problem-solving
tool for professionals in science and engineering, as well as students in those
fields, who have no prior knowledge of computer programming.
In keeping with the late Brian D. Hahn’s objectives in previous editions, the
sixth edition adopts an informal, tutorial style for its “teach-yourself” ap-
proach, which invites readers to experiment with MATLAB as a way of discov-
ering how it works. It assumes that readers have never used this tool in their
technical problem solving.
MATLAB, which stands for “Matrix Laboratory,” is based on the concept of
the matrix. Because readers will be unfamiliar with matrices, ideas and con-
structs are developed gradually, as the context requires. The primary audience
for Essential MATLAB is scientists and engineers, and for that reason certain ex-
amples require some first-year college math, particularly in Part II. However,
these examples are self-contained and can be skipped without detracting from
the development of readers’ programming skills.
MATLAB can be used in two distinct modes. One, in keeping the modern-age
craving for instant gratification, offers immediate execution of statements (or
groups of statements) in the Command Window. The other, for the more pa-
tient, offers conventional programming by means of script files. Both modes
are put to good use here: The former encouraging cut and paste to take full
advantage of Windows’ interactive environment. The latter stressing program-
ming principles and algorithm development through structure plans.
Although most of MATLAB’s basic (“essential”) features are covered, this book
is neither an exhaustive nor a systematic reference. This would not be in keep-
ing with its informal style. For example, constructs such as for and if are not
always treated, initially, in their general form, as is common in many texts, but
are gradually introduced in discussions where they fit naturally. Even so, they
xv
xvi Preface

are treated thoroughly here, unlike in other texts that deal with them only su-
perficially. For the curious, helpful syntax and function quick references can be
found in the appendices.
The following list contains other highlights of Essential MATLAB for Engineers
and Scientists, Sixth Edition:
 Warnings of the many pitfalls that await the unwary beginner
 Numerous examples taken from science and engineering (simulation, pop-
ulation modeling, numerical methods) as well as business and everyday
life
 An emphasis on programming style to produce clear, readable code
 Comprehensive chapter summaries
 Chapter exercises (answers and solutions to many of which are given in an
appendix)
 A thorough, instructive index
Essential MATLAB is meant to be used in conjunction with the MATLAB soft-
ware. The reader is expected to have the software at hand in order to work
through the exercises and thus discover how MATLAB does what it is com-
manded to do. Learning any tool is possible only through hands-on expe-
rience. This is particularly true with computing tools, which produce correct
answers only when the commands they are given and the accompanying data
input are correct and accurate.

ACKNOWLEDGMENTS
I would like to thank Mary, Clara, Zoe Rae and Zach T. for their support and
encouragement. I dedicate the sixth edition of Essential MATLAB for Engineers
and Scientists to them.
Daniel T. Valentine
1
Part 1 concerns those aspects of MATLAB that you need to know in order to
come to grips with MATLAB’s essentials and those of technical computing. Be-
cause this book is a tutorial, you are encouraged to use MATLAB extensively
while you go through the text.
PART

Essentials
This page intentionally left blank
CHAPTER 1

Introduction

THE OBJECTIVES OF THIS CHAPTER ARE: CONTENTS


 To enable you to use some simple MATLAB commands from the Using MATLAB ...... 5
Command Window. Arithmetic ................. 5
 To examine various MATLAB desktop and editing features. Variables .................... 7
 To learn some of the new features of the MATLAB R2016a Desktop. Mathematical
 To learn to write scripts in the Editor and Run them from the Editor. functions.................... 8
 To learn some of the new features associated with the tabs (in particular, Functions and
the PUBLISH and APPS features). commands ................. 8
Vectors....................... 9
Linear equations ...... 11
Tutorials and demos 12
MATLAB is a powerful technical computing system for handling scientific and The desktop ......... 13
engineering calculations. The name MATLAB stands for Matrix Laboratory, be- Using the Editor and
cause the system was designed to make matrix computations particularly easy. running a script ....... 13
A matrix is an array of numbers organized in m rows and n columns. An exam- Help, publish and
ple is the following m × n = 2 × 3 array: view ......................... 16
Symbolics and the
  MuPAD notebook
1 3 5 APP .......................... 18
A= Other APPS.............. 23
2 4 6
Additional features .. 23
Any one of the elements in a matrix can be plucked out by using the row
and column indices that identify its location. The elements in this example Sample program . 25
Cut and paste .......... 25
are plucked out as follows: A(1, 1) = 1, A(1, 2) = 3, A(1, 3) = 5, A(2, 1) = 2,
Saving a program:
A(2, 2) = 4, A(2, 3) = 6. The first index identifies the row number counted from
script files................ 27
top to bottom; the second index is the column number counted from left to Current directory ....... 28
right. This is the convention used in MATLAB to locate information in an array. Running a script from
A computer is useful because it can do numerous computations quickly, so the current folder
operating on large numerical data sets listed in tables as arrays or matrices of browser .................... 29
rows and columns is quite efficient. A program in action . 29

This book assumes that you have never used a computer before to do the sort
of scientific calculations that MATLAB handles, but are able to find your way
3
Essential MATLAB for Engineers and Scientists. DOI:10.1016/B978-0-08-100877-5.00002-5
Copyright © 2017 Daniel T. Valentine. Published by Elsevier Ltd. All rights reserved.
4 CHAPTER 1: Introduction

Summary .............. 30 around a computer keyboard and know your operating system (e.g., Windows,
UNIX or MAC-OS). The only other computer-related skill you will need is
Exercises ............... 31
some very basic text editing.
Supplementary
material ................. 31 One of the many things you will like about MATLAB (and that distinguishes
it from many other computer programming systems, such as C++ and Java) is
that you can use it interactively. This means you type some commands at the
special MATLAB prompt and get results immediately. The problems solved in
this way can be very simple, like finding a square root, or very complicated, like
finding the solution to a system of differential equations. For many technical
problems, you enter only one or two commands—MATLAB does most of the
work for you.
There are three essential requirements for successful MATLAB applications:
 You must learn the exact rules for writing MATLAB statements and using
MATLAB utilities.
 You must know the mathematics associated with the problem you want to
solve.
 You must develop a logical plan of attack—the algorithm—for solving a
particular problem.
This chapter is devoted mainly to the first requirement: learning some basic
MATLAB rules. Computer programming is a precise science (some would also
say an art); you have to enter statements in precisely the right way. There is a
saying among computer programmers: Garbage in, garbage out. It means that if
you give MATLAB a garbage instruction, you will get a garbage result.
With experience, you will be able to design, develop and implement compu-
tational and graphical tools to do relatively complex science and engineering
problems. You will be able to adjust the look of MATLAB, modify the way you
interact with it, and develop a toolbox of your own that helps you solve prob-
lems of interest. In other words, you can, with significant experience, customize
your MATLAB working environment.
As you learn the basics of MATLAB and, for that matter, any other computer
tool, remember that applications do nothing randomly. Therefore, as you use
MATLAB, observe and study all responses from the command-line operations
that you implement, to learn what this tool does and does not do. To begin
an investigation into the capabilities of MATLAB, we will do relatively simple
problems that we know the answers because we are evaluating the tool and its
capabilities. This is always the first step. As you learn about MATLAB, you are
also going to learn about programming, (1) to create your own computational
tools, and (2) to appreciate the difficulties involved in the design of efficient,
robust and accurate computational and graphical tools (i.e., computer pro-
grams).
1.1 Using MATLAB 5

In the rest of this chapter we will look at some simple examples. Don’t be
concerned about understanding exactly what is happening. Understanding will
come with the work you need to do in later chapters. It is very important for
you to practice with MATLAB to learn how it works. Once you have grasped
the basic rules in this chapter, you will be prepared to master many of those
presented in the next chapter and in the Help files provided with MATLAB.
This will help you go on to solve more interesting and substantial problems.
In the last section of this chapter you will take a quick tour of the MATLAB
desktop.

1.1 USING MATLAB


Either MATLAB must be installed on your computer or you must have access
to a network where it is available. Throughout this book the latest version at
the time of writing is assumed (Version R2016a).
To start from Windows, double-click the MATLAB icon on your Windows desk-
top. To start from UNIX, type matlab at the operating system prompt. To start
from MAC-OS open X11 (i.e., open an X-terminal window), then type mat-
lab at the prompt. The MATLAB desktop opens as shown in Figure 1.1. The
window in the desktop that concerns us for now is the Command Window,
where the special >> prompt appears. This prompt means that MATLAB is
waiting for a command. You can quit at any time with one of the following
ways:
 Click the X (close box) in the upper right-hand corner of the MATLAB desk-
top.
 Type quit or exit at the Command Window prompt followed by pressing
the ‘enter’ key.
Starting MATLAB automatically creates a folder named MATLAB in the user’s
Documents Folder. This feature is quite convenient because it is the default
working folder. It is in this folder that anything saved from the Command
Window will be saved. Now you can experiment with MATLAB in the Com-
mand Window. If necessary, make the Command Window active by placing
the cursor in the Command Window and left-clicking the mouse button any-
where inside its border.

1.1.1 Arithmetic
Since we have experience doing arithmetic, we want to examine if MATLAB
does it correctly. This is a required step to gain confidence in any tool and in
our ability to use it.
Type 2+3 after the >> prompt, followed by Enter (press the Enter key) as
indicated by <Enter>:
>> 2+3 <Enter>
6 CHAPTER 1: Introduction

FIGURE 1.1 MATLAB desktop illustrating the Home task bar (version 2016a).

Commands are only carried out when you enter them. The answer in this case
is, of course, 5. Next try
>> 3-2 <Enter>
>> 2*3 <Enter>
>> 1/2 <Enter>
>> 23 <Enter>
>> 2\11 <Enter>
What about (1)/(2) and (2)^(3)? Can you figure out what the symbols *,
/, and ^ mean? Yes, they are multiplication, division and exponentiation. The
backslash means the denominator is to the left of the symbol and the numer-
ator is to the right; the result for the last command is 5.5. This operation is
equivalent to 11/2.
Now enter the following commands:
>> 2 .* 3 <Enter>
>> 1 ./ 2 <Enter>
>> 2 .ˆ 3 <Enter>
A period in front of the *, /, and ^, respectively, does not change the results
because the multiplication, division, and exponentiation is done with single
numbers. (An explanation for the need for these symbols is provided later
when we deal with arrays of numbers.)
1.1 Using MATLAB 7

Here are hints on creating and editing command lines:


 The line with the >> prompt is called the command line.
 You can edit a MATLAB command before pressing Enter by using various
combinations of the Backspace, Left-arrow, Right-arrow, and Del keys.
This helpful feature is called command-line editing.
 You can select (and edit) commands you have entered using Up-arrow and
Down-arrow. Remember to press Enter to have the command carried out
(i.e., to run or to execute the command).
 MATLAB has a useful editing feature called smart recall. Just type the first few
characters of the command you want to recall. For example, type the charac-
ters 2* and press the Up-arrow key—this recalls the most recent command
starting with 2*.
How do you think MATLAB would handle 0/1 and 1/0? Try it. If you insist
on using ∞ in a calculation, which you may legitimately wish to do, type the
symbol Inf (short for infinity). Try 13+Inf and 29/Inf.
Another special value that you may meet is NaN, which stands for Not-a-
Number. It is the answer to calculations like 0/0.

1.1.2 Variables
Now we will assign values to variables to do arithmetic operations with the
variables. First enter the command (statement in programming jargon) a = 2.
The MATLAB command line should look like this:
>> a = 2 <Enter>
The a is a variable. This statement assigns the value of 2 to it. (Note that this
value is displayed immediately after the statement is executed.) Now try enter-
ing the statement a = a + 7 followed on a new line by a = a * 10. Do you
agree with the final value of a? Do we agree that it is 90?
Now enter the statement
>> b = 3; <Enter>
The semicolon (;) prevents the value of b from being displayed. However, b
still has the value 3, as you can see by entering without a semicolon:
>> b <Enter>
Assign any values you like to two variables x and y. Now see if you can assign
the sum of x and y to a third variable z in a single statement. One way of doing
this is
>> x = 2; y = 3; <Enter>
>> z = x + y <Enter>
8 CHAPTER 1: Introduction

Notice that, in addition to doing the arithmetic with variables with assigned
values, several commands separated by semicolons (or commas) can be put
on one line.

1.1.3 Mathematical functions


MATLAB has all of the usual mathematical functions found on a scientific-
electronic calculator, like sin, cos, and log (meaning the natural logarithm).
See Appendix B.5 for many more examples.

 Find π with the command sqrt(pi). The answer should be 1.7725. Note
that MATLAB knows the value of pi because it is one of its many built-in
functions.
 Trigonometric functions like sin(x) expect the argument x to be in radians.
Multiply degrees by π/180 to get radians. For example, use MATLAB to cal-
culate sin(90◦ ). The answer should be 1 (sin(90*pi/180)).
x
 The exponential function e is computed in MATLAB as exp(x). Use this

information to find e and 1/e (2.7183 and 0.3679).


Because of the numerous built-in functions like pi or sin, care must be taken
in the naming of user-defined variables. Names should not duplicate those
of built-in functions without good reason. This problem can be illustrated as
follows:
>> pi = 4 <Enter>
>> sqrt(pi) <Enter>
>> whos <Enter>
>> clear pi <Enter>
>> whos <Enter>
>> sqrt(pi) <Enter>
>> clear <Enter>
>> whos <Enter>
Note that clear executed by itself clears all local variables in the workspace;
>>clear pi clears the locally defined variable pi. In other words, if you de-
cide to redefine a built-in function or command, the new value is used! The
command whos is executed to determine the list of local variables or com-
mands presently in the workspace. The first execution of the command pi = 4
in the above example displays your redefinition of the built-in pi: a 1-by-1 (or
1x1) double array, which means this data type was created when pi was assigned
a number (you will learn more about other data types later, as we proceed in
our investigation of MATLAB).

1.1.4 Functions and commands


MATLAB has numerous general functions. Try date and calendar for starters.
It also has numerous commands, such as clc (for clear command window). help
is one you will use a lot (see below). The difference between functions and
1.1 Using MATLAB 9

commands is that functions usually return with a value (e.g., the date), while
commands tend to change the environment in some way (e.g., clearing the
screen or saving some statements to the workspace).

1.1.5 Vectors
Variables such as a and b that were used in Section 1.1.2 above are called scalars;
they are single-valued. MATLAB also handles vectors (generally referred to as
arrays), which are the key to many of its powerful features. The easiest way
of defining a vector where the elements (components) increase by the same
amount is with a statement like
>> x = 0 : 10; <Enter>
That is a colon (:) between the 0 and the 10. There is no need to leave a space
on either side of it, except to make it more readable. Enter x to check that x
is a vector; it is a row vector—consisting of 1 row and 11 columns. Type the
following command to verify that this is the case:
>> size(x) <Enter>
Part of the real power of MATLAB is illustrated by the fact that other vectors
can now be defined (or created) in terms of the just defined vector x. Try
>> y = 2 .* x <Enter>
>> w = y ./ x <Enter>
and
>> y = sin(x) <Enter>
(no semicolons). Note that the first command line creates a vector y by multi-
plying each element of x by the factor 2. The second command line is an array
operation, creating a vector w by taking each element of y and dividing it by
the corresponding element of x. Since each element of y is two times the cor-
responding element of x, the vector w is a row vector of 11 elements all equal
to 2. Finally, z is a vector with sin(x) as its elements.
To draw a reasonably nice graph of sin(x), simply enter the following com-
mands:
>> x = 0 : 0.1 : 10; <Enter>
>> z = sin(x); <Enter>
>> plot(x,z), grid <Enter>
The graph appears in a separate figure window. To draw the graph of the sine
function illustrated in Figure 1.2 replace the last line above with
>> plot(x,y,’-rs’,’LineWidth’,2,’MarkerEdgeColor’,’k’,’MarkerSize’,5),grid
<Enter>
10 CHAPTER 1: Introduction

FIGURE 1.2 Figure window.

>> xlabel(’ x ’), ylabel(’ sin(x) ’) <Enter>


>> whitebg(’y’) <Enter>
You can select the Command Window or figure windows by clicking anywhere
inside them. The Windows pull-down menus can be used in any of them.
Note that the first command line above has three numbers after the equal sign.
When three numbers are separated by two colons in this way, the middle num-
ber is the increment. The increment of 0.1 was selected to give a reasonably
smooth graph. The command grid following the comma in the last command
line adds a grid to the graph.
Modifying the plot function as illustrated above, of the many options available
within this function, four were selected. A comma was added after the variable
y followed by ’-rs’. This selects a solid red line (-r) to connect the points at which
the sine is computed; they are surrounded by square (s) markers in the figure.
The line width is increased to 2 and the marker edge color is black (k) with
size 5. Axis labels and the background color were changed with the statements
following the plot command. (Additional changes in background color, object
colors etc. can be made with the figure properties editor; it can be found in the
pull-down menu under Edit in the figure toolbar. Many of the colors in the
figures in this book were modified with the figure-editing tools.)
If you want to see more cycles of the sine graph, use command-line editing to
change sin(x) to sin(2*x).
Try drawing the graph of tan(x) over the same domain. You may find aspects
of your graph surprising. To help examine this function you can improve the
graph by using the command axis([0 10 -10 10]) as follows:
1.1 Using MATLAB 11

>> x = 1:0.1:10; <Enter>


>> z = tan(x); <Enter>
>> plot(x,z),axis([0 10 -10 10]) <Enter>
An alternative way to examine mathematical functions graphically is to use the
following command:
>> ezplot(’tan(x)’) <Enter>
The apostrophes around the function tan(x) are important in the ezplot
command. Note that the default domain of x in ezplot is not 0 to 10.
A useful Command Window editing feature is tab completion: Type the first
few letters of a MATLAB name and then press Tab. If the name is unique, it is
automatically completed. If it is not unique, press Tab a second time to see all
the possibilities. Try by typing ta at the command line followed by Tab twice.

1.1.6 Linear equations


Systems of linear equations are very important in engineering and scientific
analysis. A simple example is finding the solution to two simultaneous equa-
tions:

x + 2y = 4
2x − y = 3

Here are two approaches to the solution.


Matrix method. Type the following commands (exactly as they are):
>> a = [1 2; 2 -1]; <Enter >
>> b = [4; 3]; <Enter >
>> x = a\b <Enter >
The result is

x =
2
1

i.e., x = 2, y = 1.
Built-in solve function. Type the following commands (exactly as they are):
>> [x,y] = solve(’x+2*y=4’,’2*x - y=3’) <Enter >
>> whos <Enter >
>> x = double(x), y=double(y) <Enter >
>> whos <Enter >
12 CHAPTER 1: Introduction

FIGURE 1.3 The Help documentation on MATLAB Examples.

The function double converts x and y from symbolic objects (another data type
in MATLAB) to double arrays (i.e., the numerical-variable data type associated
with an assigned number).
To check your results, after executing either approach, type the following com-
mands (exactly as they are):
>> x + 2*y % should give ans = 4 <Enter >
>> 2*x - y % should give ans = 3 <Enter >
The % symbol is a flag that indicates all information to the right is not part of
the command but a comment. (We will examine the need for comments when
we learn to develop coded programs of command lines later on.)

1.1.7 Tutorials and demos


If you want a spectacular sample of what MATLAB has to offer, type the com-
mand demo on the command line. After entering this command the Help
documentation is opened at MATLAB Examples (see Figure 1.3). Left-click on
“Getting Started”. This points you to the list of tutorials and demonstrations of
MATLAB applications that are at your disposal. Click on any of the other top-
ics to learn more about the wealth of capabilities of MATLAB. You may wish to
review the tutorials appropriate to the topics you are examining as part of your
technical computing needs. Scroll down to the “New Features Video” to learn
more about the Desktop and other new features, some of which are introduced
next.
Discovering Diverse Content Through
Random Scribd Documents
If there are any legal disputes or claims between members of the
staff of the British agent, both plaintiff and defendant are referred by
him to the Courts of Justice in India. If the British agent or any
member of his staff has a dispute with the Afghan subjects of the
Amir, such cases are usually decided in the Courts of Kabul, under
the law of that country. Complications of a very serious political
character are invariably referred to the Governments of India and
Afghanistan for arrangement between themselves.
The British agent puts his diary and also the private letters of the
whole of his staff into one package, which he hands to the Amir’s
Postmaster-General at Kabul, taking a receipt for their delivery under
seal; from the Amir’s post-office they are sent down to Peshawar,
where the Amir’s postmaster is given a discharge for their surrender
to the political agent at Peshawar. In the same manner the packages
of letters, which are delivered by the British political agent at
Peshawar to the Amir’s postmaster at that place, are forwarded to
the British agent at Kabul by the Amir’s Postmaster-General, who
also takes a voucher for their safe and proper condition. The
services and duties of the Amir’s political agent with the Viceroy of
India, who, together with his staff, is a Mahommedan subject of the
Amir, are nearly the same as those of the British agent at Kabul,
except that the term and time of his office is not limited and depends
entirely on the pleasure of the Amir. Besides the political agent, the
Amir has various commercial agents in India as well as in England,
the most important of these having been Sir Acquin Martin, Mr. T. B.
Guthrie and Mr. E. T. Pack. Each of these industrious and excellent
servants of the Amir has suffered the loss of large sums of money
through a very pronounced defect in the Amirs of Afghanistan, which
causes them to forget their obligations so long as there is a frontier
lying between the Government of Kabul and those with whom its
debts have been contracted. Representations remain unanswered
and, apparently, no authority exists which can make the Amir of
Afghanistan redeem his liabilities, although an obvious course awaits
if the Government of India would assent to the attachment of the
subsidy.
major cleveland’s residence in kabul

[36] Printed on page 365.


Adapted from “The Life of Abdur Rahman”: Sultan Mahomed
[37]
Khan and “The Middle Eastern Question”: Valentine Chirol.
[38] Born 1890.
[39] Born 1893.
[40] See p. 372.
[41] See p. 371.
CHAPTER XV

KABUL AND ITS BAZAARS


The bazaars of Kabul are quite unworthy of
the capital, but radical improvement in their
character could only be made by a complete
reconstruction of the city. Here and there
new ones have been built, Habib Ullah
himself having erected several at his own
expense, but the principle of construction,
adopted at the time of the building of the city,
is the great stumbling block to any extensive
alterations. The narrowness of the streets,
many of which are mere alleys, gives rise to
perpetual congestion; while, in consequence
of their contracted character, they are always
dirty and overloaded with the refuse of the
houses, more particularly in winter when they
are blocked with the snow, which is swept
from the roofs. Of the several bazaars of the
city,[42] the three principal, running irregularly
parallel to each other, are the Shor Bazar,
the famous cage on the the Erg Bazar, and the Darwaza Lahori
summit of the lataband Bazar. The former extends east and west
pass from the Bala Hissar to the Ziarat Baba
Khudi, a distance of little more than three-quarters of a mile. The
latter, stretching from the Darwaza Lahori, passes through the centre
of the wood market and terminates at the New Bridge. The Erg
Bazar crosses the town and communicates with the workshops. The
western portion of the Darwaza Lahori Bazar was the site of the
Char Chata, at one time undoubtedly the most magnificent bazaar in
Afghanistan. The structure, ascribed to Ali Mardan Khan, whose
name is immortal in these countries, was handsomely laid out and
highly embellished with paintings. Four covered arcades, of equal
length and dimensions, were separated from each other by open
squares, originally provided with wells and fountains. The entire
fabric was destroyed in October 1842 by General Pollock, as
retribution for the murder of Sir William Macnaghten and the
indignities offered to his remains.

weighing wood in the bazaar

The Nakush Bazar, or cattle market, is situated north of the Kabul


river and west of the Pul-i-Kishti in the Indarabi quarter. The Mandi
Kalan and the Mandi Shahzada, the chief grain bazaars, lie in the
Tandur Sazi quarter, between the Shor Bazar and the Darwaza
Lahori. The Shikarpuri quarter, adjoining the Pul-i-Kishti on the right
bank of the river, is the fruit market. Here are collected the various
fruits for which the capital of Afghanistan is so famous, the exhibition
of grapes, apples, apricots and pears becoming at once the glory of
the bazaars. Melons are missing from this bazaar, as this important
branch of the fruit trade of Afghanistan is conducted in the Mandi
Kalan. Near to the fruit bazaar are the wood and charcoal markets,
each section of trade possessing its particular locality and its special
marketplace.
In this way there is a shoe bazaar, a meat market, a vegetable
market, a copper bazaar, silk bazaar and certain central marts where
arms, tobacco, furs, medicines and cloth are sold. In the boot bazaar
there are a number of Anglo-Indian importations and no less a
quantity from Russia. The native shoes are made from leather which
is manufactured in Kabul at the Amir’s factory—articles of local
manufacture being put up as a rule upon the premises where they
are sold. The more important merchants possess accommodation
beneath their shops, where craftsmen, whose special industry is
allied with the business in the premises above them, are employed.
These underground rooms are so small that the men at work are
compelled to crouch over their knees, while customers, who bring
articles for repair, sit in the street. In the copper bazaar, where
domestic utensils are to be found, there is the ceaseless tapping of
countless hammers, as the men, assisted by boys who ply the
bellows or feed the furnace with charcoal, wield their tools upon
long-necked vases, hubble-bubbles, kettles, cooking pots, water-
bottles with delicate handles and graceful spouts, stoves, plates and
copper boxes of all shapes and sizes. These workers in metals,
whether they are the ironmongers or silversmiths, smelters of copper
or the moulders of brass, are worthy of their hire, and bring to their
labours an extraordinary patience and exactitude. The silversmiths
are, perhaps, the most wonderful craftsmen, although the men who
trace fantastic designs upon metal vessels with blunt instruments are
not to be despised. From early morning, without cessation until the
heat of the mid-day hours makes work impossible, they bend over
their tasks, actively working their pliers, tweezers and hammers as
they fashion ear-rings, bracelets or graven ewers. The business,
transacted at these stalls, seems out of proportion with the labour
involved, as sales are arranged between the merchant and his
customers only after many days of protracted dealing.
The method of barter is always the same in the East. Customers
sit down by the side of the merchant, examining and asking the
value of his goods, praising certain pieces and decrying others, until
conversation has worked round to the article which it is desired to
buy. Ten times the price will be asked at first, perhaps haggled over
with all sincerity, until, as the would-be purchaser rises to leave, a
few rupees will be knocked off the figure which the vendor has been
demanding. It is then prudent to leave, returning some other day to
begin over again. The hours spent in an Oriental bazaar are of such
supreme interest that they are sacrificed very willingly and are not
easily forgotten. The setting of the scene is romantic, while the life of
the city passes in endless, kaleidoscopic changes of character, of
costume and of men and beasts. It is never wise to hurry
transactions conducted amid such environment. Time is of no value
to the merchant, who regards the overtures with indifference. He
may hope that ultimately his customer will become his patron, but he
would never show his satisfaction nor lose an opportunity to drive a
haggling bargain. Around the shops there are always groups of idle
but profoundly interested spectators. Some one ascertains the price
the worker is paid; another inquires of the merchant the amount he
will receive for it; and, in the hope of extracting a commission from
the proprietor of the shop or his purchaser, all are eager to advise
the customer upon the merits of the article he may have chosen or
the sum he may have offered.
In the silk and cotton bazaar there is equally the press and bustle
of an active trade, a continuous passing of gaily-decked customers
and busy traders—from India with caravans of silk, from Turkestan
with bales of printed cottons, plain calicoes and other articles of
Russian manufacture, merchants and itinerant traders from the most
distant parts of Afghanistan, from Persia and from Kashgar. There is,
too, a wonderful blaze of colour in the silk stalls, while the display of
goods in the cotton shops reveals a various assortment of English
clothing—cotton and merino vests, men’s shirts, drawers and
socks—and a variety of coloured waistbands, a weird collection of
ties and some really startling handkerchiefs from India. These stalls,
whether their effects are imported from India or from Turkestan, are
mostly in the keeping of Hindus, who transact a very profitable
business with their Afghan masters. Nevertheless, long intercourse
with Afghanistan has quite crushed the Hindu, obliterating all trace of
his original individuality, and emphasising his inborn humility and
lack of spirit. In Kabul the Hindus pay a poll tax and wear turbans,
which may be only red or yellow—a similar rule prevailing in
Kandahar. Formerly they affected the red, the blue lungi, which is
prohibited to them, being favoured by the Afghans. Similar
indications of prosperity may be found in the skin bazaar, where the
furriers are engaged in making the fur coats for which Kabul has
become famous. Here there are several kinds of expensive furs such
as marten, a variety of red fox, squirrel, wild cat and astrakhan. Over
the latter fur the Amir exercises a monopoly. The cheaper kinds are
put to numerous purposes, figuring as lining for cloaks, hats and high
boots of the Russian and Turcoman pattern. Many of the fur caps are
costly in production and elaborate in design. Cut from a piece of
velvet, trimmed with fur and heavily embroidered with gold thread
from Benares, they are sold in the Kabul bazaars only to the richest
classes, becoming, as a rule, a finishing touch to a costume which,
on the score of colour effect, will leave little to be desired.
The character of the costume adopted by the average Afghan
depends, in a certain measure, upon whether he is a hillsman or one
who is accustomed to town-life. If he possess merely a casual
acquaintanceship with the life of the towns, coming to them from
some small village or in charge of a trading caravan from the border,
his costume is simple although effective. Probably he is a fine-
looking man: tall, with a long, blue-black beard; his head may be
shaven, or his long hair may hang in ringlets over his shoulders. He
will wear a small unembroidered skull-cap and wound round it a
blue, coarse, cotton lungi. A loose vest, caught at the waist by the
ample folds of a cummerbund, will reach the knees; and tucked
within these folds there will be pistols and an array of formidable
knives. His drawers of cotton and reaching only a little below the
knees are very baggy. Round his shoulders there will be thrown
carelessly, but with conspicuous grace, a heavy blue cotton shawl;
his feet will be ornamented by leather sandals with high curving toes.
The dress of a man of the better classes differs from that adopted
by the hillsman. He then wears tom-bons or pyjamas, gathered in at
the waist and falling in tapering folds from the hip to the ankle, where
they fit closely. The native shoes will be worn without socks, unless
the wearer is wealthy. An embroidered piran or chemise falls over
the pyjamas nearly to the knees, and a waistcoat, reaching a little
below the waist, with long sleeves and a slit at the hip, is also
affected. The costume is completed by a loose robe. The waistcoat
is of velvet or cloth, quilted and generally gold embroidered. The
coat is of thin native cloth. The Kabul man-about-town usually
amplifies the native costume with European innovations; as a rule
the higher he rises in the social scale the more Europeanised he
becomes in costume.

playground of amir’s school, kabul

Nevertheless, the readiness to follow certain European fashions


depends solely upon the personal influence of the Amir, although the
custom prevails more generally in Kabul than in many parts of India.
European weapons are, of course, acquired by all who can afford
them; but the earliest and the most striking change of dress is the
replacement of the cummerbund by a belt, with a brass or silver
buckle and decorated with two labels—“Made in Germany” and “God
Bless the Happy Home.” Upon more serious grounds the wisdom of
this innovation may be questioned, since the climate of Afghanistan
is subject to such great variations of temperature that the
cummerbund affords excellent protection to the abdominal region.
The purchase of socks and “foreign style” coat or, better still, a
discarded uniform follows, while patent leather button boots are
considered to give a nice, dressy appearance to the bareness of the
leg. Trousers are not general in any degree, although they are
affected among the upper classes and also in Court and military
circles. They are made quite loose and are put on over the native
pyjamas. In spite of the popularity which foreign dress has achieved,
it is always discarded in the privacy of the family. While nothing
affords Habib Ullah so much pleasure as showing himself in
European costume in public, nothing will induce him to wear Western
clothes once the doors of his palace have closed upon him and he
can recline at his ease amid well-placed cushions. His disapproval of
ostentatious habiliment was revealed at the Nauroz festival in 1903,
when he ordained that all good Mahommedans of the upper classes
should eschew braid, gold lace and embroidered shoes. He also
enjoined them to wear trousers and to keep the feet and ankles bare.
Hindus were ordered to wear yellow turbans and to encircle the waist
with a cord as a mark of distinction and humility.
The attire adopted for ordinary purposes differs in a very
considerable degree from that worn by a Court attendant. Regulation
Court costume comprises a black cloth coat, vest and trousers,
circular astrakhan hat, and white collar with a black necktie. Any one
who wishes to attend at the palace or to be present at a Durbar,
must wear this dress, which is cut to a special pattern. Military
officers wear their uniform. On State occasions the Amir himself is
resplendent in a scarlet coat, richly embroidered with gold lace, white
cloth trousers and white gloves. For headgear he has an astrakhan
hat decorated with a large diamond star,—the costume being
completed by a gold belt with jewelled buckle, sword and gold
shoulder-straps surmounted by a diamond insignia. In semi-state
dress Habib Ullah puts himself into a black uniform, faced with
several revers of braid and having deep, astrakhan cuffs, black cloth
trousers braided, and patent leather knee-boots. The sleeves, cap,
sword and shoulder-straps are the same as in full dress. At other
times the Amir wears the ordinary garb of an English gentleman and
greatly dislikes any exaggerated display of jewellery, believing that
simplicity is not only desirable but in accord with the tenets of the
Mahommedan religion. In furtherance of that view he has restricted
the wearing of jewellery among men to signet rings and prohibited
altogether the gaudy silk handkerchiefs, which it had been the
fashion to display about the shoulders. It is difficult for the Afghans to
subdue their passion for ostentation. Friday, a day which
corresponds with our Sunday, is the great festival of the Afghan. This
weekly holiday commences with a visit to the baths and a brief call at
the mosque, after which the entire family, arrayed in its best,
proceeds to take the air. There are many gardens of a sort in Kabul;
and each is thronged by people, who sit about the pathways
bartering for bunches of fruit and trays of sweetmeats, or loll with
rapt attention around the perch of some singing-bird. Every man of
consequence is attended by slaves bearing his pipe, the cage of his
pet songster, sweetmeats and fruit, the party coming to a halt in
some secluded spot where, lying at ease, receiving and returning the
salutations of his friends, he listens to the notes of his favourite bird.

afghan women
The indoor costume of an Afghan woman is no less picturesque
than that of her lord and master. Even to a plain and awkward
woman it imparts some appearance of grace. The piran extends
from the throat to just above the ankles, with sleeves that reach to
the wrist. It is of cloth of gold, velvet, silk, cashmere or calico, and in
shape not unlike our own Princess robe. Beneath this are the tom-
bons, very similar to the garment worn by men.[43] These may be of
cloth of gold, silk, cashmere or calico; they are finished off at the
ankles by a fringe of diamonds, gold or silver. A round cap, worked
all over with gold thread, so that it looks like gold cloth, is fitted
closely to the back of the head. The hair, parted in the centre, is
done up in tiny braids, which are caught in a black silk embroidered
bag, worn underneath the gold cap, but hanging down the back to
below the waist. Married women wear a fringe of hair, often curled,
on either side of the face. Descending from the top of the head to the
hem of the piran, leaving the face uncovered, is the gracefully-
draped chadar—a large wrapping of finest muslin, filmy gauze, or
delicately tinted chiffon. Black hair is in vogue among the belles of
the harem; if their locks reveal any shade of fairness or show
indications of turning grey the vain creatures, adopting the custom of
their Western sisters, at once dye them. Like all their sex, too, they
delight in jewellery and conspicuous ornaments, and a considerable
portion of their savings is expended upon the purchase of necklaces,
ear-rings and bracelets. All who can afford it wear flowers just above
the right ear, while they also indulge in the use of cosmetics. Paint
and powder, rouge for the lips and the blackening pencil for
eyebrows and eyelashes are the adventitious aids to whatever
natural charms they may possess.
Proud of their prepossessing qualities, the women of Afghanistan
have exploited their charms so much that it was left to Habib Ullah to
impose a check upon the increasing attractiveness of the street
costume of the feminine portion of his subjects. One day, in the
spring of 1903, to the unspeakable dismay of many pretty women
and of all young girls, he issued orders, changing the white burka,
which, although covering the head and figure and leaving a latticed
insertion before the face, was in a measure attractive. Thereafter
these white street robes were to be dyed kharki for Mahommedan
women, red or mustard-yellow for Hindu women and slate colour for
other women. Disobedience of this law was threatened with a fine of
fifty rupees, while its requirements had to be fulfilled within fourteen
days. Unhappily, by this change an attractive feature in the life of the
city has disappeared, the lamentable hues enforced upon the poor
ladies by the Amir’s edict emphasising the dirt and discomfort of the
Kabul streets.
In Afghanistan, as in all Mahommedan countries, the women lead
a very secluded life, seldom venturing into the streets. The
conditions of their married life are unfortunate, since the religion of
the Afghan permits him to possess four wives, while no restrictions
are imposed upon the number of concubines that he may support.
This law in regard to wives is broken at will; and, while plurality of
wives may be conducive to the satisfaction of the husband, it is
unnecessary to say that the practice is not in favour among the
women, who, in this matter, incline their hearts after the customs of
the West. Moreover, women are not the sole companions of their
husbands, for in Afghanistan, as in most Oriental countries, the
small, but comely, boy is the more frequent intimate of their masters.
At Court and in the households of the several princes this
characteristic feature of the East may be observed, the existence of
these boys being accepted by the priests, who themselves indulge in
this most peculiar vice.
a saint’s tomb

In spite of their position, women do contrive to play an important


part in the life of the country and, in a measure, help to keep alive
many of the old superstitions of the people, while their passionate
credulity no doubt exercises an influence over the feelings of their
husbands. Their strongest superstition perhaps attaches to the
potency of the frog as a love charm. Women, especially in the harem
of the Amir where jealousy is supreme, resort constantly to this
enchantment to improve their positions. The mode of procedure is as
follows: two frogs are tied back to back. A black heart is then painted
upon the bull frog, while the head of the cow is similarly ornamented.
The pair are then baked alive and the remains reduced to powder,
which, sprinkled upon some dear friend, is supposed to cause her to
lose the favour of her husband and to give place to the rival. This
spell is employed so frequently even among the lowest classes that
there is probably no household in which recourse to it is not made
every few days. In the harem of the palace the chief queen keeps a
slave boy whose sole duty it is to provide the frogs necessary for the
preparation. It is the invariable experience of native ladies, when
calling upon the queen, to find that they have been surreptitiously
powdered with it at the hands of some discreet attendant.
Another legend, implicitly accepted by the women of Afghanistan,
is associated with the Lata Bund Davan or Rag Bound Pass. It
ordains that they will have healthy children, and gain favour in the
eyes of their lords, if they tie a piece of cloth to the bushes in the
Rag Bound Pass. Certain prescribed prayers, of course, accompany
the ceremony, the summit of the pass presenting an extraordinary
aspect from the fluttering rags, and streamers of cotton, calico and
cloth which have been secured there.
Among men a bullet which has been through a human body is
valued very highly, the supernatural powers of such a charm finding
immediate acceptance with the Amir. Whenever they are extracted
from any patient in the Kabul hospitals, Habib Ullah secures
possession of the coveted relic to the great grief of its owner who,
equally with him, supports the view that such a bullet acts as a
preservative of life. Unfortunately, complaint is fruitless; the man who
would be bold enough to seek the restoration of his property might
find himself condemned to imprisonment or execution.
There is little doubt that the gross superstition prevailing in the
country is the direct effect of its religious bigotry. Afghanistan, if
Turkey be excepted, is the most powerful Mahommedan country in
the world, and religion exercises a deciding voice in its affairs. The
real rulers of the people are the priests, whether the wise men who
have made the pilgrimage to Mecca, or merely the wandering fakirs
whose fanatical tendencies are so easily aroused. The great division
of the State lies between the two religious sects, the Sunni and the
Shiah Mahommedans. In the main, Afghans are Sunni; while the
Persians, the Hazaras, the Kizzilbashes of Kabul and the Turis of the
Kurram border, are Shiahs. The Kafirs of Kafiristan are pagan.
Between these two sects there exists an envenomed feud which is
by no means confined to Afghanistan, similar contempt, and an
equal undying hatred against the other, distinguishing the partisans
of either sect wherever they may meet. In Afghanistan Habib Ullah is
the leader of the Sunnis, but his power is purely nominal; the real
leader is Nasr Ullah Khan. The Amir of Kabul recently requested the
priesthood to pronounce formally upon the question as to what
amount of tolerance should be shown to the Shiahs in Afghanistan.
The decision formulated was that the Sunni religion was the one true
Faith which should be recognised by his Highness as “King of Islam.”
Accordingly all ceremonial observances of the Shiahs in Kabul have
been stopped and similar action is likely to be taken elsewhere. It is
seen, however, that the services of the Hindu colony cannot be
dispensed with, as its leading members have a good deal to say in
matters of finance and trade, while the Kizzilbashes (of Persian
origin) are also a thrifty community in Kabul. It has therefore been
ordered that their places of worship are to be 5 feet lower than the
Sunni mosques, and existing buildings are to be altered accordingly.
Since the Shiahs are not numerous enough to give any political
trouble they will probably conform to the orders issued, which
naturally met with the immediate approval of the Sunnis.
Ramasan, the period corresponding with our Lent, is very strictly
observed. It continues throughout the Moslem world for one lunar
month and in Kabul the Amir, his Court and his subjects deny
themselves most strictly. Gun-fire at dawn—from which time no one
is allowed to eat, to drink, or to smoke—gives the signal. It
terminates at sunset, when just previous to evening gun-fire the
activity round the provision stalls is tremendous, the spectacle of a
vast concourse simultaneously preparing to eat anywhere and
everywhere—in the palace, in the mansions of the wealthy, in the
hovels of the poor, in the crowded street—no matter what any may
be doing, as the signal breaks, being very singular. Between gun-fire
at dusk and gun-fire at dawn two meals are partaken, after which the
wise make day into night, retiring to their couches to wait for the hour
when they prepare to feed again. The termination of the fast is
celebrated by the firing of guns, general feasting and rejoicing, while
the following day is observed as the Id—the great festival of the
Mahommedan calendar. On this day the Amir and his Court proceed
in full state to the Idgah Mosque, when prayers are celebrated by
Nasr Ullah in person, the service being followed by a public Durbar
held in the Salaam Khana where Habib Ullah meets his people.
Four days are annually set apart for religious celebrations in
Afghanistan. These comprise two Id festivals, one immediately
following Ramasan, the other two months and ten days later; the
third, the Barat festival, takes place forty-five days before Ramasan.
The fourth event is Nauroz or New Year which falls invariably upon
March 21. Abdur Rahman created a fifth festival, observed upon
28th of Asad, in remembrance of the day when confirmation of his
title “The Light of the Nation and Religion” was received from all the
centres of Afghanistan.
Priestly influence in Afghanistan is anything but beneficial. The
priests impose upon the credulity of the people, concealing their
actual worthlessness by a continuous assumption of godliness which
they do not really practise. Their power is opposed to foreign
development, since any raising of the veil about the borders of
Afghanistan would deal a grievous blow to their position. Habib Ullah
is completely subjugated to their will, and his brother, Nasr Ullah
Khan, imbibes his anti-foreign prejudices from their bigoted
teachings. At once a curse and a power in the land, they are the
most enduring menace to our influence which the country contains.
As a religion Mahommedanism exacts constant adoration of the
qualities of God. The word Allah in a variety of intonations, or the
phrase “God knows,” recur without cessation to the lips of every
devout follower of the Prophet. All correspondence of an official or
private character also addresses itself in the first place to the
Supreme Deity—letters beginning with the phrase “In the name of
God” and closing with the farewell salutation, “With the will of God,”
or “In the hands of God.” This peculiarity quite fails to arouse
sentiments of very great depth among the great mass of the
Afghans, although the western areas frequently develop a spirit of
ghazidom, under pressure of which feeling and excitement become
intense.
Religion is allied with the practice of medicine and the pursuit of
learning in Afghanistan, although in respect of education no settled
procedure has been adopted. Upon occasion Abdur Rahman gave
expression to his intention of founding a native university in Kabul,
and Habib Ullah in 1904 actually imported from India five
Mahommedan graduates from Lahore College for the purpose of
founding a college for the education of the sons of Afghan nobles.
The plan raised the hostility of the priests and was abandoned. At
present the Amir contemplates the erection of a military academy.
Unhappily the roads round Kabul are paved with good intentions,
and the educational system of Afghanistan has made no advance
upon the native principle of oral teaching. There are no schools or
colleges under European supervision similar to those which exist in
other Eastern countries, and the young idea is only trained to read
Persian, to quote extensively from the Koran, to write, to shoot and
to ride. Nothing further is desired by the priests, since it is their aim
to maintain their authority unimpaired by extraneous suggestion.

the bala hissar, kabul

The priests exert in a measure a two-fold power. In the villages of


the countryside it is the local mullah who drives into the dull wits of
his audience the rudiments of reading, writing, and religion. At the
same time, in addition to teaching the countryside he professes to
heal it, although attempts have been made from time to time to
establish in Kabul European control in medical matters. But the
Court is suspicious; and, while Abdur Rahman supported in theory
the introduction of improved medical knowledge, enlisting in March
1889 Mr. J. A. Gray as his private surgeon, he was in practice
opposed to its acceptance. Nevertheless, under the supervision of
various distinguished people attempts have been made to instruct
native doctors in the art of vaccination and in simple dispensing;
while, in 1894, Miss Lillias Hamilton opened an hospital in Kabul. At
their instigation, too, military hospitals, placed in the charge of native
druggists who were familiarised with Western ideas, were started.
Popular prejudices prevail so strongly in the capital, that no great
success has attended these efforts, and the medical arrangements
of Afghanistan have remained under the control of the native
professors of the healing art, save for those spasmodic interruptions
which have occurred when more competent authorities were
summoned to Kabul from India by the Amir.
Miss Lillias Hamilton spent three years at the Court of Abdur
Rahman, the cause of her becoming medical attendant to the Amir
being somewhat curious. Abdur Rahman, observing the good effect
that association with English gentlemen had on the men folk of his
country, conceived the brilliant idea of providing an example for
Afghan women by obtaining the presence of an English lady. On the
announcement being made that a lady was required merely to be
entertained as a visitor for six months at the Amir’s Court Miss
Hamilton applied for the post, and was accepted. Her appointment
as physician was due to the fact that the Amir fell ill during her visit,
and wisely availed himself of the aid of the only qualified medical
practitioner in the country. Miss Lillias Hamilton always described the
late Amir as a man of simple mind, who was nevertheless possessed
of a progressive spirit. On being asked why he entertained a friendly
feeling towards Great Britain, the Amir said:
“If I were to tell you that it is because I love the British you
would not believe me, so I will say that it is because it suits
my policy. Russia is my geographical enemy, who would seize
my country if she could, because it is on her route to a sunny
sea and a fertile country from which she could get supplies,
but I have nothing to fear from Great Britain.”
This charming and well-known physician relates several
characteristic anecdotes of the late monarch, of which one is
reproduced here. After an eclipse of the sun Abdur Rahman said to
Miss Hamilton:
“You think yourself a clever woman, but you could not
explain that phenomenon so simply that a child could
understand it.”
Miss Hamilton assured him that she could, and proceeded to do
so with the aid of a candle and an orange. In the evening when,
according to his custom, Abdur Rahman held a reception, he told his
people that they were all very stupid and that he was sure not one of
them could explain the eclipse. Many wild suggestions were made,
until the Amir attempted to give the demonstration that Miss
Hamilton had shown him. Since she kindly came to his assistance it
went off so successfully that the company were deeply impressed
with the Amir’s wisdom.
Multitudes of ailing people flocked to Miss Hamilton for advice,
some of them sleeping outside her hospital all night in order to be
attended to the first thing in the morning. This lady doctor was also
the first to introduce the Western system of vaccination into
Afghanistan, where almost the greatest scourge is small-pox, and
where the Amir does not allow conscientious objectors!
As one foreign physician has left Kabul and another has taken his
place, the newcomer has found that the hospital buildings of his
predecessor have become in the interval the premises of a school, a
depôt for military stores, or have fallen altogether into ruin. The
establishment which has served longest as an hospital was built for
that purpose by Nasr Ullah Khan in compliment to Mrs. Daly, who
was so long associated with Miss Hamilton as medical adviser to the
harem. It contained 100 beds. This building is now a magazine for
artillery stores, while a second, which filled a similar purpose under
Dr. Gray, is now a school. During the eight years in which Mrs. Daly
was engaged in medical work in Afghanistan she held the
appointment of private physician to Abdur Rahman’s queen, Bibi
Halima, besides filling the post of medical adviser to the Kabul
Government. Mrs. Daly has stated that between three hundred to
five hundred patients daily visited her, and that, while very interested
in her work, she was sorely harassed by the unceasing espionage of
which she was the very conscious victim. The high opinion which the
Government of Afghanistan formed of Mrs. Daly’s services is aptly
illustrated by a testimonial from Habib Ullah, which was presented to
her in the autumn of 1902. It ran:
In the Name of God.
I myself certify that Mrs. Kate Daly ranks above all people
in her zeal for the work and in her attendance to patients. I am
pleased with her services, and the treatment of my two
daughters; of the workmen in the factories that were so
seriously injured, and of my subjects in general whom she
treats from day to day.
Habib Ullah,
Amir of Afghanistan.
September 20, 1902.
In the following year, 1903, the European residents of Kabul
subscribed through a committee of three to an expression of
gratitude to Mrs. Daly in the following terms:
Kabul, November 20, 1903.
The European residents of Kabul have much pleasure in
presenting this testimonial to Mrs. Kate Daly, as an
expression of gratitude for the medical services rendered us
and admiration of the successful medical and surgical work
she has carried out during the past eight years, particularly
during the epidemics of cholera, small-pox, etc.; when her
devotion to her work, self-denial, and untiring energy won her
the respect of all here. She carries with her our sincere
wishes for her future welfare and success.
Frank A. Martin, Engineer to the Afghan Government.
G. Fleischer, Manager of Arms Department H. M. The Amir’s
Workshops.
Ernest T. Thornton, Manager of Tanneries, Kabul.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like