text:
Главная Essential MATLAB for Engineers and Scientists

Essential MATLAB for Engineers and Scientists

,
Essential MATLAB for Engineers and Scientists, Seventh Edition,provides a concise, balanced overview of MATLAB's functionality, covering both fundamentals and applications. The essentials are illustrated throughout, featuring complete coverage of the software's windows and menus. Program design and algorithm development are presented, along with many examples from a wide range of familiar scientific and engineering areas. This edition has been updated to include the latest MATLAB versions through 2018b. This is an ideal book for a first course on MATLAB, but is also ideal for an engineering problem-solving course using MATLAB.

Updated to include all the newer features through MATLAB R2018b
Includes new chapter on useful toolboxes
Provides additional examples on engineering applications
Год:
2019
Издание:
Paperback
Издательство:
Язык:
english
Страниц:
428 / 406
ISBN 10:
0081029977
ISBN 13:
9780081029978
File:
PDF, 11.26 MB

Most frequently terms

You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
1

Year:
2016
Language:
english
File:
PDF, 1.24 MB
2

Target: Alex Cross

Year:
2018
Language:
english
File:
EPUB, 2.64 MB
Essential MATLAB
for Engineers and Scientists

Essential MATLAB
for Engineers and Scientists
Seventh Edition

Brian D. 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
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: permissions@elsevier.com. 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.”
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 L; ibrary.
ISBN: 978-0-08-102997-8
For information on all Academic Press publications

Publisher: Katey Birtcher
Acquisition Editor: Steve Merken
Editorial Project Manager: Katerina Zaliva
Production Project Manager: Nilesh Kumar Shah
Designer: Matthew Limbert
Typeset by VTeX

Preface

The main reason for a seventh edition of Essential MATLAB for Engineers and
Scientists is to keep up with MATLAB, now in its latest version (9.5 Version
R2018b). Like the previous editions, this one presents MATLAB as a problemsolving 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
seventh edition adopts an informal, tutorial style for its “teach-yourself” approach, which invites readers to experiment with MATLAB as a way of discovering 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 may be unfamiliar with matrices, ideas and constructs are developed gradually, as the context requires. The primary audience
for Essential MATLAB is scientists and engineers, and for that reason certain examples require some first-year college math, particularly in Part 2. 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 patient, 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 programming 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 keeping 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
are treated thoroughly here, unlike in other texts that deal with them only su-

xv

xvi Preface

perficially. For the curious, helpful syntax and function quick references can be
found in the appendices.
Essential MATLAB is meant to be used in conjunction with the MATLAB software. 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 commanded to do. Learning any tool is possible only through hands-on experience. 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 seventh edition of Essential MATLAB for Engineers
and Scientists to them.
Daniel T. Valentine

1
PA R T

Essentials

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. Because this book is a tutorial, you are encouraged to use MATLAB extensively
while you go through the text.

CHAPTER 1

Introduction
THE OBJECTIVES OF THIS CHAPTER ARE:
■

■
■
■
■

To enable you to use some simple MATLAB commands from the Command Window.
To examine various MATLAB desktop and editing features.
To learn some of the new features of the MATLAB R2018b Desktop.
To learn to write scripts in the Editor and Run them from the Editor.
To learn some of the new features associated with the tabs (in particular,
the PUBLISH and APPS features).

MATLAB is a powerful technical computing system for handling scientific and
engineering calculations. The name MATLAB stands for Matrix Laboratory, because the system was designed to make matrix computations particularly easy.
A matrix is an array of numbers organized in m rows and n columns. An example is the following m × n = 2 × 3 array:

1 3 5
A=
2 4 6
Any one of the elements in a matrix can be accessed by using the row and
column indices that identify its location. The elements in this example are accessed as follows: A(1, 1) = 1, A(1, 2) = 3, A(1, 3) = 5, A(2, 1) = 2, A(2, 2) = 4,
A(2, 3) = 6. The first index identifies the row number counted from top to bottom; the second index is the column number counted from left to right. This is
the convention used in MATLAB to locate information in a matrix. A computer
is useful because it can do numerous computations quickly, so operating on
large numerical data sets listed in tables or matrices (or arrays) of rows and
columns is quite efficient.
This book assumes that you are an engineer, a scientist or an undergraduate
student majoring in a STEM (science, technology, engineering and mathematics) field. Hence, it is assumed that students and practitioners in STEM have
been introduced to matrices in their mathematics courses prior to entering a
college or university. On the other hand this book assumes that you have never
used MATLAB to solve engineering or scientific problems and are interested in
Essential MATLAB for Engineers and Scientists. https://doi.org/10.1016/B978-0-08-102997-8.00007-5

CONTENTS
Using MATLAB .
Arithmetic ............
Variables ..............
Mathematical
functions ..............
Functions and
commands ...........
Vectors ................
Linear equations....
Tutorials and demos

5
6
7
8
8
9
11
12

The desktop ..... 13
Using the Editor and
running a script .....
Help, Publish and
View ....................
Symbolics in live
scripts .................
APPS ...................

14
16
19
20
22

Sample program 24
Cut and paste ........ 24
Saving a program:
Script ﬁles ............ 26
Current directory ...... 27
Running a script from
the Current Folder
browser .................. 28

A program in action 28

Summary ........ 29
Exercises ........ 30
Supplementary
material .......... 30

3

4 CHAPTER 1: Introduction

discovering the technical computing capabilities of this tool. Hence, it is also
assumed that you can find your way around the keyboard and know your operating system (e.g., Windows, UNIX or MAC-OS). Some experience using a
computer is expected, e.g., doing word processing, doing basic text editing, etc.
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 the process of writing a collection
of instructions that performs a specific task when executed by a computer. In
this book you are introduced to programming by using some of the capabilities
of MATLAB to do technical computing.
With experience, you will be able to design, develop and implement computational 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 problems of interest. In other words, you can, with significant experience, customize
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 5

FIGURE 1.1
MATLAB desktop illustrating the Home task bar (version 2018b).

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 R2018b).
To start from Windows, double-click the MATLAB icon on your Windows desktop. 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 matlab
at the prompt. The MATLAB desktop opens as shown in Fig. 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
desktop.
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 Command Window. If necessary, make the Command Window active by placing
the cursor in the Command Window and left-clicking the mouse button anywhere inside its border.

6 CHAPTER 1: Introduction

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

1.1 Using MATLAB 7

■

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
characters 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-aNumber. 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 a. (Note that this
value is displayed immediately after the statement is executed.) Now try entering 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>
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.

8 CHAPTER 1: Introduction

1.1.3 Mathematical functions
MATLAB has all of the usual mathematical functions found on a scientificelectronic calculator, like sin, cos, and log (meaning the natural logarithm).
See Appendix C 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
MATLAB to calculate sin(90◦ ). The answer should be 1 (sin(90*pi/180)).
The exponential function ex 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 (the
workspace is where the local variables defined on command lines are stored;
see the Workspace pane on the right side of the default desktop); >> clear pi
clears the locally defined variable pi. In other words, if you decide 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 commands 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.

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
commands is that functions usually return with a value (e.g., the date), while

1.1 Using MATLAB 9

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>
The symbol between the 0 and the 10 is a colon (:). 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
>> z = sin(x) <Enter>
(no semicolons). Note that the first command line creates a vector y by multiplying 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 corresponding 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 commands:
>> x = 0 : 0.1 : 10; <Enter>
>> y = sin(x); <Enter>
>> plot(x,y), grid <Enter>

10 CHAPTER 1: Introduction

FIGURE 1.2
Figure window.

The graph appears in a separate figure window. To draw the graph of the sine
function illustrated in Fig. 1.2 replace the last line above with
>> plot(x,y,’-rs’,’LineWidth’,2,’MarkerEdgeColor’,’k’,’MarkerSize’,5),grid
<Enter>
>> 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 number 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

1.1 Using MATLAB 11

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

12 CHAPTER 1: Introduction

x =
2
1

i.e., x = 2, y = 1.
Built-in solve function. Type the following commands (exactly as they are):
>> syms x y; [x,y] = solve(x+2*y-4, 2*x - y-3) <Enter >
>> whos <Enter >
>> x = double(x), y=double(y) <Enter >
>> whos <Enter >
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 commands (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 command demo on the command line. After entering this command the Help documentation is opened at MATLAB Examples (see Fig. 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 topics 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. Click on “View more MATLAB examples” and scroll down to
produce motion pictures as a way to analyze various unsteady problems. New
features are continually added to MATLAB; all new features are reported on the
MathWorks website. MathWorks is the company that sells and supports the
continued development of enhancements for MATLAB and SIMULINK and a
variety of toolboxes that they offer to the science, engineering, technology and
mathematics communities.

1.2 The desktop 13

FIGURE 1.3
The Help documentation on MATLAB Examples.

1.2 THE DESKTOP
A very useful feature of MATLAB R2018a is the fact that when you first open
it, it creates the folder named MATLAB (if it does not already exist) in your
Documents folder. The first time it does this, there are no items in the folder
and, hence, the Current Folder panel will be empty. This new folder in your
Documents is the default working folder where all the files you create are saved.
The location of this folder is given in the first toolbar above the Command
Window. The location is C:\Users\Clara\Documents\MATLAB. This format of the
location was determined by pointing and left-clicking the mouse in the line
just above the Command Window.
Let us examine the Desktop from the top down. On the left side of the top line
you should see the name of the version of MATLAB running. In this case it is
MATLAB R2018a. On the right side of the top line are three buttons. They are
the underscore button, which allows you to minimize the size of the Desktop window, the rectangle button, which allows you to maximize the size
of the Desktop, and the × button, which allows you to close MATLAB (see
Fig. 1.4).
On the next line of the Desktop there are three tabs on the left side. The first
tap is most forward in the figure and, hence, the Home toolbar is displayed
(the tabs and the toolbars associated with the tabs are the main new features
of this release of MATLAB). If you are already familiar with a previous release
of MATLAB, you will find that these new features enhance significantly the use
of MATLAB. In addition, all previously developed tools operate exactly as they

14 CHAPTER 1: Introduction

FIGURE 1.4
New Desktop Toolbar on MATLAB 2018a.

FIGURE 1.5
Editor opened in default location; it is in the center of the Desktop.

did in previous releases of MATLAB. The other two tabs are PLOTS and APPS.
These features allow you to access tools within MATLAB by pointing and clicking and, hence, enhance the utilization of tools and toolboxes available within
MATLAB. In addition, the APPS environment allows the user to create their
own applications (or APPS).

1.2.1 Using the Editor and running a script
Point and click on the New Script icon on the left most side of the Home
toolbar. Doing this opens the editor in the center of the Desktop as shown in
Fig. 1.5. Note that three new tabs appear and that the tab that is visible is the
Editor tab that is connected with the Editor. The other two tabs are Publish
and View. The latter are useful when creating notebooks or other documents
connected with your technical computing work. The application of these tools
will be illustrated by an example later in this text.
Let us first consider using the Editor. Type into the Editor the following script:

1.2 The desktop 15

% Example of one of the matrix inversion methods available in MATLAB
clear;clc
% Let us consider the following arbitrarily selected matrix:
A =magic(3)
% Let us evaluate its inverse as follows:
AI = inv(A)
% Let us check that it is an inverse:
IPredicted = A * AI
% This is the exact unitary matrix:
IM = eye(3)
% The is the difference between the exact and predict unitary
% matrix:
difference = IPredicted - IM
for m = 1:3
for n = 1:3
if difference(m,n) < eps;
IPredicted(m,n) = IM(m,n);
end
end
end
IPredicted
IPredicted == IM

Then click on the Run button just under the tab named View. The first time
the script is executed you are asked to name the file. The name used in this
example is ExA1_1.m. If all lines are typed correctly (except the lines beginning
with the symbol ’%’, because they are comments that have nothing to do with
the sequence of commands in the script except that they help the reader understand what the script does), what shows up in the Command Window is as
follows:
A =
8

1

6

3

5

7

4

9

2

AI =
0.1472

-0.1444

-0.0611

0.0222

0.0639
0.1056

-0.0194

0.1889

-0.1028
-0.0000

IPredicted =
1.0000

0

-0.0000

1.0000

0

0.0000

0

1.0000

IM =

16 CHAPTER 1: Introduction

1
0
0
difference
1.0e-15
0
-0.0278
0.0694
IPredicted
1
0
0
ans =
1
1
1

0
1
0
=

0
0
1

*
0
0
0
=
0
1
0

0
0
1

1
1
1

1
1
1

-0.1110
0
0

The IPredicted matrix is supposed to be the identity matrix, IM. The matrix
IPredicted was determined by multiplying the matrix A by its numerically
computed inverse, AI. The last print out of IPredicted is a modification of
the original matrix; it was changed to the elements of the IM matrix if the
difference between a predicted and an actual element of IM was less than
eps = 2.2204e − 16. Since the result is identical to the identity matrix, this
shows that the inverse was computed correctly (at least to within the computational error of the computing environment, i.e., 0 < eps). This conclusion
is a result of the fact that the ans in the above example produced the logical
result of 1 (or true) for all entries in the adjusted IPredicted matrix as logically
compared with the corresponding entries in IM.
At this point in the exercise the Desktop looks like Fig. 1.6. The name of the
file is ExA1_1.m. It appears in the Current Folder and it also appears in the
Command History. Note that the Workspace is populated with the variables
created by this script.
This concludes the introduction of the most important tools needed for most
of the exercises in Essential MATLAB (i.e., in this text). In the next section we
examine an example of some of the other new features of MATLAB R2018a.

1.2.2 Help, Publish and View
Publish is an easy way to create notebooks or other documents in html format.
The conversion of the information typed into an M-file is published into a document that looks like the new Help environment. To open the help documents
go to the top of the Desktop to the question mark. Left click on the question
mark ?. The Help window opens up. Left click on the topic “MATLAB” to open
up the window illustrated in Fig. 1.7. This also illustrates the new format of

1.2 The desktop 17

FIGURE 1.6
Sample script created and executed in the first example of this section.

FIGURE 1.7
Illustration of one of the pages in the online documentation for MATLAB.

the search able documentation available within MATLAB R2018a. We want to
compare this documentation with the kind you can PUBLISH yourself. To illustrate how easy it is to create documents like the MATLAB documents, let us
consider the following simple example.
Click the New Script button to open up the editor (or type edit after the
command prompt in the Command Window followed by tapping the enter
key). The Editor tab is in the most forward position on the main taskbar.

18 CHAPTER 1: Introduction

Place the cursor on PUBLISH and left click on the mouse. This brings the
PUBLISH toolbar forward. Left click Section with Title. Replace SECTION TITLE
with PUBLISHING example. Next, replace DESCRIPTIVE TEXT with
%%
% This is an example to illustrate how easy it is to create a document
% in the PUBLISH environment.
%
% (1) This is an illustration of a formula created with a LaTeX command:
%

Next, click on  Inline LaTeX located in the “Insert Inline Markup” group. This
leads to the addition of the equation $x^2+e^{\pi i}$. Following this equation
add the text shown in the final script file shown below that ends with “clicked:”.
This is followed by a blank line and a command script; this command script
is included to illustrate how MATLAB commands can be incorporated into
published documents.
%%
% This is an example to illustrate how easy it is to create a document
% in the PUBLISH environment.
%
% (1) This is an illustration of a formula created with a LaTeX command:
%
%%
% $x^2+e^{\pi i}$
%
% (2) This is an illustration of how you can incorporate a MATLAB script
% in the document that is run when the Publish button below and to the
% right of View is clicked:

% Earth picture
image(X); colormap(map);
axis image

The final step is to left-click on Publish, which is just to the right and below
View. The first window to appear is the one asking you to save the M-file. The
name used in this example is ExamplePub1.m. After it appears in the Current
Folder it is executed. A folder named html is automatically created and it contains the html document just created. The document is illustrated in Fig. 1.8.
Finally, the VIEW tab brings up a toolbar that allows you to change the configuration of the Editor window. From the authors point of view, the default
Editor environment is fine as is especially for users who are beginning to use
MATLAB for technical computing. Customizing your working environment is

1.2 The desktop 19

FIGURE 1.8
Sample document created in the Publish environment.

certainly possible in MATLAB. However, it is useful to learn how to deal with
the default environment before deciding what needs to be changed to help
satisfy your own requirements for using MATLAB.

1.2.3

Symbolics in live scripts

The Symbolic Math Toolbox is a useful tool to help you do symbolic mathematical analysis. It is convenient and the results are more presentable if we
use this toolbox within a Live-Script environment. The portions of this type of
file in which code is entered is essentially the same as what would be typed
in the Work Space or in an ordinary script file. However, the display is much
more presentable than the output displayed in the Work Space window of the
Desktop. This will be evident by the examples reported in this section.
In the first set of examples we show how to differentiate a function and, subsequently, integrate a function using the Symbolic Tools. First let us open a
Live-Editor file by clicking on the Live Editor icon below Home in the Home
tool bar. We get the Live Editor in the center of the desktop as shown in Fig. 1.9.
The gray box at the top of the file to be created is where the MATLAB scripts are
typed into this editor.

20 CHAPTER 1: Introduction

FIGURE 1.9
The Live Editor window.

The simple examples in Fig. 1.10 illustrate the application of Symbolic Tools
to do calculus. The examples in Fig. 1.11 illustrates the power of tools within
MATLAB to study the shapes of functions that you may encounter in your work.
One is the sech2 (x) function which plays an important role in nonlinear wave
theory. The second is the complete elliptic integral of the first kind, viz.,
 π/2
1

K(m) =
dθ
0
1 − m2 sin2 θ
where m = π/4. This integral plays an important role in potential theory. This
function was selected as an example because the second author encountered
it in his work. The purpose of showing this is to illustrate how easy it is to
explore some of the features of relatively complicated functions that arise in
computational analysis of engineering problems. As an exercise, open up the
help documents to find other functions, tutorials, and examples. The help documentation has improved tremendously over the years since MATLAB was first
introduced.

1.2.4 APPS
Press the APPS tab to the left of the EDITOR tab to see the applications that
came with your MATLAB suite of tools. There are a number of other APPS
available from MathWorks. In addition, there is a capability for you to create
your own APPS. Hence, if there is anything that we learn from our first experiences with MATLAB is that there is a lot to learn (a lifelong experience of
learning) because of the wealth of technology incorporated in this technical
computing environment. The fact that you can develop your own toolboxes,

1.2 The desktop 21

FIGURE 1.10
Simple examples of symbolic analysis of calculus problems.

FIGURE 1.11
Simple examples of symbolic analysis of various important functions that arise in STEM fields.

22 CHAPTER 1: Introduction

FIGURE 1.12
The Mexican hat.

arrangement, color backgrounds, fonts, graphical user interfaces and so on)
provides real opportunities and useful experience in creating designs, creating
useful tools and documenting your work.

MATLAB has other good things. For example, you can generate a 10-by-10 (or
10 × 10) magic square by executing the command magic(10), where the rows,
columns, and main diagonal add up to the same value. Try it. In general, an
n × n magic square has a row and column sum of n(n2 + 1)/2.
You can even get a contour plot of the elements of a magic square. MATLAB
pretends that the elements in the square are heights above sea level of points
on a map, and draws the contour lines. contour(magic(32)) looks interesting.
If you want to see the famous Mexican hat (Fig. 1.12), enter the following four
lines (be careful not to make any typing errors):
>> [x y ] = meshgrid(-8 : 0.5 : 8); <Enter>
>> r = sqrt(x.^2 + y.^2) + eps; <Enter>
>> z = sin(r) ./ r; <Enter>
>> mesh(z); <Enter>
generates a faceted (tiled) view of the surface. surfc(z) or meshc(z)
draws a 2D contour plot under the surface. The command
surf(z)

1.2 The desktop 23

produces a nice picture by removing the grid lines.
The following animation is an extension of the Mexican hat graphic in
Fig. 1.12. It uses a for loop that repeats the calculation from n = −3 to n = 3
in increments of 0.05. It begins with a for n = −3:0.05:3 command and ends
with an end command and is one of the most important constructs in programming. The execution of the commands between the for and end statements
repeat 121 times in this example. The pause(0.05) puts a time delay of 0.05 seconds in the for loop to slow the animation down, so the picture changes every
0.05 seconds until the end of the computation.
>> [x y]=meshgrid(-8:0.5:8); <Enter>
>> r=sqrt( x.^2+y.^2)+eps; <Enter>
>> for n=-3:0.05:3; <Enter>
>> z=sin(r.*n)./r; <Enter>
>> surf(z), view(-37, 38), axis([0,40,0,40,-4,4]); <Enter>
>> pause(0.05) <Enter>
>> end <Enter>
You can examine sound with MATLAB in any number of ways. One way is to
listen to the signal. If your PC has a speaker, try
>> sound(y,Fs) <Enter>
for a snatch of Handel’s Hallelujah Chorus. For different sounds try loading
and train. You have to run sound(y,Fs) for each
one.

chirp, gong, laughter, splat,

If you want to see a view of the Earth from space, try
>> image(X); colormap(map) <Enter>
>> axis image <Enter>
To enter the matrix presented at the beginning of this chapter into MATLAB,
use the following command:
>> A = [1 3 5; 2 4 6] <Enter>
On the next line after the command prompt, type A(2,3) to pluck the number
from the second row, third column.

24 CHAPTER 1: Introduction

There are a few humorous functions in MATLAB. Try why (why not?) Then
try why(2) twice. To see the MATLAB code that does this, type the following
command:
>> edit why <Enter>
Once you have looked at this file, close it via the pull-down menu by clicking
at the top of the Editor desktop window and then Close Editor; do not
save the file, in case you accidently typed something and modified it.

File

The edit command will be used soon to illustrate the creation of an M-file like
why.m (the name of the file executed by the command why). You will create an
M-file after we go over some of the basic features of the MATLAB desktop. More
details on creating programs in the MATLAB environment will be explained in
Chapter 2.

1.3

SAMPLE PROGRAM

In Section 1.1 we saw some simple examples of how to use MATLAB by entering single commands or statements at the MATLAB prompt. However, you
might want to solve problems which MATLAB can’t do in one line, like finding the roots of a quadratic equation (and taking all the special cases into
account). A collection of statements to solve such a problem is called a program.
In this section we look at the mechanics of writing and running two short programs, without bothering too much about how they work—explanations will

1.3.1 Cut and paste
Suppose you want to draw the graph of e−0.2x sin(x) over the domain 0 to 6π ,
as shown in Fig. 1.13. The Windows environment lends itself to nifty cut and
paste editing, which you would do well to master. Proceed as follows.
From the MATLAB desktop select File -> New -> Script, or click the new file
button on the desktop toolbar (you could also type edit in the Command
Window followed by Enter). This action opens an Untitled window in the Editor/Debugger. You can regard this for the time being as a ‘scratch pad’ in which
to write programs. Now type the following two lines in the Editor, exactly as
they appear here:
x = 0 : pi/20 : 6 * pi;
plot(x, exp(-0.2*x) .* sin(x), ’k’),grid

Incidentally, that is a dot (full stop, period) in front of the second * in the
second line—a more detailed explanation later! The additional argument ’k’

1.3 Sample program 25

FIGURE 1.13
e−0.2x sin(x).

for plot will draw a black graph, just to be different. Change ’k’ to ’r’ to
generate a red graph if you prefer.
Next, move the mouse pointer (which now looks like a very thin capital I) to
the left of the x in the first line. Keep the left mouse button down while moving
the mouse pointer to the end of the second line. This process is called dragging.
Both lines should be highlighted at this stage, probably in blue, to indicate
that they have been selected.
Select the Edit menu in the Editor window, and click on Copy (or just use
the keyboard shortcut Ctrl+C). This action copies the highlighted text to the
Windows clipboard, assuming that your operating system is Windows.
Now go back to the Command Window. Make sure the cursor is positioned
at the  prompt (click there if necessary). Select the Edit menu, and click
on Paste (or use the Ctrl+V shortcut). The contents of the clipboard will be
copied into the Command Window. To execute the two lines in the program,
press Enter. The graph should appear in a figure window.
This process, from highlighting (selecting) text in the Editor, to copying it into
the Command Window, is called ‘cut and paste’ (more correctly ‘copy and
paste’ here, since the original text is copied from the Editor, rather than being
cut from it). It’s well worth practicing until you have it right.
If you need to correct the program, go back to the Editor, click at the position of the error (this moves the insertion point to the right place), make the
correction, and cut and paste again. Alternatively, you can use command-line
editing to correct mistakes. As yet another alternative, you can paste from the
Command History window (which incidentally goes back over many previous

26 CHAPTER 1: Introduction

sessions). To select multiple lines in the Command History window keep Ctrl
down while you click.
If you prefer, you can enter multiple lines directly in the Command Window.
To prevent the whole group from running until you have entered the last line
use Shift+Enter after each line until the last. Then press Enter to run all the
lines.
As another example, suppose you have $1000 saved in the bank. Interest is compounded at the rate of 9 per cent per year. What will your bank balance be after one year? Now, if you want to write a MATLAB program to find your new balance, you must be able to do the problem yourself in principle. Even with a relatively simple problem like this, it often helps first to write down a rough structure plan: 1. 2. 3. 4. Get the data (initial balance and interest rate) into MATLAB. Calculate the interest (9 per cent of$1000, i.e., $90). Add the interest to the balance ($90 + $1000, i.e.,$1090).
Display the new balance.

Go back to the Editor. To clear out any previous text, select it as usual by dragging (or use Ctrl+A), and press the Del key. By the way, to de-select highlighted
text, click anywhere outside the selection area. Enter the following program,
and then cut and paste it to the Command Window.
balance = 1000;
rate = 0.09;
interest = rate * balance;
balance = balance + interest;
disp( ’New balance:’ );
disp( balance );

When you press Enter to run it, you should get the following output in the
Command Window:
New balance:
1090

1.3.2 Saving a program: Script ﬁles
We have seen how to cut and paste between the Editor and the Command
Window in order to write and run MATLAB programs. Obviously you need to
save the program if you want to use it again later.
To save the contents of the Editor, select File -> Save from the Editor menubar.
A Save file as: dialogue box appears. Select a folder and enter a file name,

1.3 Sample program 27

which must have the extension .m, in the File name: box, e.g., junk.m. Click
on Save. The Editor window now has the title junk.m. If you make subsequent
changes to junk.m in the Editor, an asterisk appears next to its name at the top
of the Editor until you save the changes.
A MATLAB program saved from the Editor (or any ASCII text editor) with the
extension .m is called a script file, or simply a script. (MATLAB function files
also have the extension .m. We therefore refer to both script and function files
generally as M-files.) The special significance of a script file is that, if you enter
its name at the command-line prompt, MATLAB carries out each statement in
the script file as if it were entered at the prompt.
The rules for script file names are the same as those for MATLAB variable names
(see the next Chapter 2, Section 2.1).
As an example, save the compound interest program above in a script file under
the name compint.m. Then simply enter the name
compint

at the prompt in the Command Window (as soon as you hit Enter). The statements in compint.m will be carried out exactly as if you had pasted them into
the Command Window. You have effectively created a new MATLAB command, viz., compint.
A script file may be listed in the Command Window with the command type,
e.g.,
type compint

(the extension .m may be omitted).
Script files provide a useful way of managing large programs which you do
not necessarily want to paste into the Command Window every time you run
them.

Current directory
When you run a script, you have to make sure that MATLAB’s current folder
(indicated in the toolbar just above the Current Folder) is set to the folder (or
directory) in which the script is saved. To change the current folder type the
path for the new current folder in the toolbar, or select a folder from the dropdown list of previous working folders, or click on the browse button (it is the
first folder with the green arrow that is to the left of the field that indicates the
location of the Current Folder). Select a new location for saving and executing
files (e.g., if you create files for different courses, you may wish to save your
work in folders with the names or numbers of the courses that you are taking).

28 CHAPTER 1: Introduction

You can change the current folder from the command line with cd command,
e.g.,
cd \mystuff

The command cd by itself returns the name of the current directory or current
folder (as it is now called in the latest versions of MATLAB).

Running a script from the Current Folder browser
A handy way to run a script is as follows. Select the file in the Current Directory
browser. Right-click it. The context menu appears (context menus are a general
feature of the desktop). Select Run from the context menu. The results appear
in the Command Window. If you want to edit the script, select Open from the

1.3.3 A program in action
We will now discuss in detail how the compound interest program works.
The MATLAB system is technically called an interpreter (as opposed to a compiler). This means that each statement presented to the command line is translated (interpreted) into language the computer understands better, and then
immediately carried out.
A fundamental concept in MATLAB is how numbers are stored in the computer’s random access memory (RAM). If a MATLAB statement needs to store a
number, space in the RAM is set aside for it. You can think of this part of the
memory as a bank of boxes or memory locations, each of which can hold only
one number at a time. These memory locations are referred to by symbolic
names in MATLAB statements. So the statement
balance = 1000

allocates the number 1000 to the memory location named balance. Since the
contents of balance may be changed during a session it is called a variable.
The statements in our program are therefore interpreted by MATLAB as follows:
1. Put the number 1000 into variable balance.
2. Put the number 0.09 into variable rate.
3. Multiply the contents of rate by the contents of balance and put the
4. Add the contents of balance to the contents of interest and put the
5. Display (in the Command Window) the message given in single quotes.
6. Display the contents of balance.

Summary 29

It hardly seems necessary to stress this, but these interpreted statements are
carried out in order from the top down. When the program has finished running,
the variables used will have the following values:
balance

: 1090

interest : 90
rate

: 0.09

Note that the original value of balance (1000) is lost.
Try the following exercises:
1. Run the program as it stands.
2. Change the first statement in the program to read
balance = 2000;

Make sure that you understand what happens now when the program
runs.
3. Leave out the line
balance = balance + interest;

and re-run. Can you explain what happens?
4. Try to rewrite the program so that the original value of balance is not lost.
A number of questions have probably occurred to you by now, such as
■
■
■
■

What names may be used for variables?
How can numbers be represented?
What happens if a statement won’t fit on one line?
How can we organize the output more neatly?

These questions will be answered in the next chapter. However, before we write
any more complete programs there are some additional basic concepts which
need to be introduced. These concepts are introduced in the next chapter.

SUMMARY
■

■

■
■

MATLAB is a matrix-based computer system designed to assist in scientific
and engineering problem solving.
To use MATLAB, you enter commands and statements on the command
line in the Command Window. They are carried out immediately.
quit or exit terminates MATLAB.
clc clears the Command Window.

30 CHAPTER 1: Introduction

■

help

■

plot
grid

■

and lookfor provide help.
draws an x-y graph in a figure window.
draws grid lines on a graph.

EXERCISES
1.1 Give values to variables a and b on the command line, e.g., a = 3 and
b = 5. Write some statements to find the sum, difference, product and
quotient of a and b.
1.2 In Section 1.2.5 of the text a script is given for an animation of the
Mexican hat problem. Type this into the editor, save it and execute it.
Once you finish debugging it and it executes successfully try modifying
it. (a) Change the maximum value of n from 3 to 4 and execute the
script. (b) Change the time delay in the pause function from 0.05 to
0.1. (c) Change the z=sin(r.*n)./r; command line to z=cos(r.*n);
and execute the script.
1.3 Assign a value to the variable x on the command line, e.g., x = 4 * pi^2.
What is the square root of x? What is the cosine of the square root of x?
1.4 Assign a value to the variable y on the command line as follows: y = -1.
What is the square root of y? Show that the answer is
ans =
0 + 1.0000i

Yes, MATLAB deals with complex numbers (not just real numbers).
Hence the symbol i should not be used as an index or as a variable
name. By default, it is equal to the square root
√ of −1. (Also, when necessary, j is used in MATLAB as a symbol for −1. Hence, it also should
not be used as an index or as a variable name.) Give an example of how
you have used complex numbers in your studies of mathematics and
the sciences up to this point in your education.
Solutions to many of the exercises are in Appendix D.

APPENDIX 1.A SUPPLEMENTARY MATERIAL
Supplementary material related to this chapter can be found online at https://
doi.org/10.1016/B978-0-08-102997-8.00007-5.

CHAPTER 2

MATLAB Fundamentals
THE OBJECTIVE OF THIS CHAPTER IS TO INTRODUCE SOME
OF THE FUNDAMENTALS OF MATLAB PROGRAMMING, INCLUDING:
Variables, operators, and expressions
Arrays (including vectors and matrices)
Basic input and output
Repetition (for)
Decisions (if)

■
■
■
■
■

The tools introduced in this chapter are sufficient to begin solving numerous
scientific and engineering problems you may encounter in your course work
and in your profession. The last part of this chapter and the next chapter
describe an approach to designing reasonably good programs to initiate the
building of tools for your own toolbox.

2.1 VARIABLES
Variables are fundamental to programming. In a sense, the art of programming
is this:
Getting the right values in the right variables at the right time
A variable name (like the variable balance that we used in Chapter 1) must
comply with the following two rules:
■

■

It may consist only of the letters a–z, the digits 0–9, and the underscore ( _ ).

The name may be as long as you like, but MATLAB only remembers the first 63
characters (to check this on your version, execute the command namelengthmax in the Command Window of the MATLAB desktop). Examples of valid
Essential MATLAB for Engineers and Scientists. https://doi.org/10.1016/B978-0-08-102997-8.00008-7

CONTENTS
Variables ......... 31
Case sensitivity ..... 32

The workspace . 32
used constants to
the workspace....... 33

Arrays: Vectors
and matrices.... 34
Initializing vectors:
Explicit lists ..........
Initializing vectors:
The colon operator .
The linspace and
logspace functions .
Transposing vectors
Subscripts ............
Matrices...............
Capturing output ...
Structure plan .......

34
35
36
37
37
38
39
39

Vertical motion
under gravity.... 40
Operators,
expressions, and
statements ...... 42
Numbers ..............
Data types ............
Arithmetic
operators .............
Operator
precedence ...........
The colon operator .
The transpose
operator ...............
Arithmetic
operations on
arrays ..................

43
43
44
44
45
46
46

31

32 CHAPTER 2: MATLAB Fundamentals

Expressions ..........
Statements ...........
Statements,
commands, and
functions ..............
Formula
vectorization .........

47
48
49

variable names are r2d2 and pay_day. Examples of invalid names (why?) are
pay-day, 2a, name$, and _2a. A variable is created simply by assigning a value to it at the command line or in a program—for example, 49 a = 98 Output ............ 52 The disp statement 52 The format command ............. 54 Scale factors ......... 55 If you attempt to refer to a nonexistent variable you will get the error message in red Repeating with for ................. 55 Square roots with Newton’s method ... Factorials! ............ Limit of a sequence The basic for construct.............. for in a single line.. More general for ... Avoid for loops by vectorizing! ........... 56 57 58 The official MATLAB documentation refers to all variables as arrays, whether they are single-valued (scalars) or multi-valued (vectors or matrices). In other words, a scalar is a 1-by-1 array—an array with a single row and a single column which, of course, is an array of one item. 58 60 60 2.1.1 Case sensitivity 60 Decisions ........ 63 The one-line if statement............. The if-else construct.............. The one-line if-else statement.. elseif .................. Logical operators... Multiple ifs versus elseif .................. Nested ifs ........... Vectorizing ifs?..... The switch statement............. Undefined function or variable ’...’. 63 65 66 66 68 68 70 71 MATLAB is case-sensitive, which means it distinguishes between upper- and lowercase letters. Thus, balance, BALANCE and BaLance are three different variables. Many programmers write variable names in lowercase except for the first letter of the second and subsequent words, if the name consists of more than one word run together. This style is known as camel caps, the uppercase letters looking like a camel’s humps (with a bit of imagination). Examples are camelCaps, milleniumBug, dayOfTheWeek. Some programmers prefer to separate words with underscores. Command and function names are also case-sensitive. You must not use capitals when running built-in functions and commands! 2.2 THE WORKSPACE 71 Complex numbers ......... 71 Summary ........ 73 Exercises ........ 75 Supplementary material .......... 81 Another fundamental concept in MATLAB is the workspace. Enter the command clear and then rerun the compound interest program (see Section 1.3.2). Now enter the command who. You should see a list of variables as follows: Your variables are: balance interest rate All the variables you create during a session remain in the workspace until you clear them. You can use or change their values at any stage during the session. 2.2 The workspace 33 The command who lists the names of all the variables in your workspace. The function ans returns the value of the last expression evaluated but not assigned to a variable. The command whos lists the size of each variable as well: Name Size balance interest rate 1x1 1x1 1x1 Bytes 8 8 8 Class double double double Each variable here occupies eight bytes of storage. A byte is the amount of computer memory required for one character (if you are interested, one byte is the same as eight bits). These variables each have a size of “1 by 1,” because they are scalars, as opposed to vectors or matrices (although as mentioned above, MATLAB regards them all as 1-by-1 arrays). The Class double means that the variable holds numeric values as double-precision floating-point (see Section 2.5). The command clear removes all variables from the workspace. A particular variable can be removed from the workspace (e.g., clear rate). More than one variable can also be cleared (e.g., clear rate balance). Separate the variable names with spaces, not commas. When you run a program, any variables created by it remain in the workspace after it runs. This means that existing variables with the same names are overwritten. The Workspace browser on the desktop provides a handy visual representation of the workspace. You can view and even change the values of workspace variables with the Array Editor. To activate the Array Editor click on a variable in the Workspace browser or right-click to get the more general context menu. From the context menu you can draw graphs of workspace variables in various ways. 2.2.1 Adding commonly used constants to the workspace If you often use the same physical or mathematical constants in your MATLAB sessions, you can save them in an M-file and run the file at the start of a session. For example, the following statements can be saved in myconst.m: g = 9.81; avo = 6.023e23; e = exp(1); pi_4 = pi / 4; log10e = log10( e ); bar_to_kP = 101.325; % acceleration due to gravity % Avogadro’s number % base of natural log % atmospheres to kiloPascals 34 CHAPTER 2: MATLAB Fundamentals If you run myconst at the start of a session, these six variables will be part of the workspace and will be available for the rest of the session or until you clear them. This approach to using MATLAB is like a notepad (it is one of many ways). As your experience grows, you will discover many more utilities and capabilities associated with MATLAB’s computational and analytical environment. 2.3 ARRAYS: VECTORS AND MATRICES As mentioned in Chapter 1, the name MATLAB stands for Matrix Laboratory because MATLAB has been designed to work with matrices. A matrix is a rectangular object (e.g., a table) consisting of rows and columns. We will postpone most of the details of proper matrices and how MATLAB works with them until Chapter 6. A vector is a special type of matrix, having only one row or one column. Vectors are called lists or arrays in other programming languages. If you haven’t come across vectors officially yet, don’t worry—just think of them as lists of numbers. MATLAB handles vectors and matrices in the same way, but since vectors are easier to think about than matrices, we will look at them first. This will enhance your understanding and appreciation of many aspects of MATLAB. As mentioned above, MATLAB refers to scalars, vectors, and matrices generally as arrays. We will also use the term array generally, with vector and matrix referring to the one-dimensional (1D) and two-dimensional (2D) array forms. 2.3.1 Initializing vectors: Explicit lists As a start, try the accompanying short exercises on the command line. These are all examples of the explicit list method of initializing vectors. (You won’t need reminding about the command prompt  or the need to <Enter> any more, so they will no longer appear unless the context absolutely demands it.) Exercises 2.1 Enter a statement like x = [1 3 0 -1 5] Can you see that you have created a vector (list) with ﬁve elements ? (Make sure to leave out the semicolon so that you can see the list. Also, make sure you hit Enter to execute the command.) 2.2 Enter the command disp(x) to see how MATLAB displays a vector. 2.3 Enter the command whos (or look in the Workspace browser). Under the heading Size you will see that x is 1 by 5, which means 1 row and 5 columns. You will also see that the total number of elements is 5. 2.3 Arrays: Vectors and matrices 35 2.4 You can use commas instead of spaces between vector elements if you like. Try this: a = [5,6,7] 2.5 Don’t forget the commas (or spaces) between elements; otherwise, you could end up with something quite different: x = [130 - 15] What do you think this gives? Take the space between the minus sign and 15 to see how the assignment of x changes. 2.6 You can use one vector in a list for another one. Type in the following: a = [1 2 3] b = [4 5] c = [a -b] 2.7 Can you work out what c will look like before displaying it? And what about this? a = [1 3 7]; a = [a 0 -1]; 2.8 Enter the following x = [ ] Note in the Workspace browser that the size of x is given as 0 by 0 because x is empty . This means x is deﬁned and can be used where an array is appropriate without causing an error; however, it has no size or value. Making x empty is not the same as saying x = 0 (in the latter case x has size 1 by 1) or clear x (which removes x from the workspace, making it undeﬁned). An empty array may be used to remove elements from an array (see Section 2.3.5). Remember the following important rules: ■ ■ Elements in the list must be enclosed in square brackets, not parentheses. Elements in the list must be separated either by spaces or by commas. 2.3.2 Initializing vectors: The colon operator A vector can also be generated (initialized) with the colon operator, as we saw in Chapter 1. Enter the following statements: x = 1:10 (elements are the integers 1, 2, . . . , 10) 36 CHAPTER 2: MATLAB Fundamentals x = 1:0.5:4 (elements are the values 1, 1.5, . . . , 4 in increments of 0.5. Note that if the colons separate three values, the middle value is the increment); x = 10:-1:1 (elements are the integers 10, 9, . . . , 1, since the increment is negative); x = 1:2:6 (elements are 1, 3, 5; note that when the increment is positive but not equal to 1, the last element is not allowed to exceed the value after the second colon); x = 0:-2:-5 (elements are 0, −2, −4; note that when the increment is negative but not equal to −1, the last element is not allowed to be less than the value after the second colon); x = 1:0 (a complicated way of generating an empty vector!). 2.3.3 The linspace and logspace functions The function linspace can be used to initialize a vector of equally spaced values: linspace(0, pi/2, 10) creates a vector of 10 equally spaced points from 0 to π/2 (inclusive). The function logspace can be used to generate logarithmically spaced data. It is a logarithmic equivalent of linspace. To illustrate the application of logspace try the following: y = logspace(0, 2, 10) This generates the following set of numbers 10 numbers between 100 to 102 (inclusive): 1.0000, 1.6681, 2.7826, 4.6416, 7.7426, 12.9155, 21.5443, 35.9381, 59.9484, 100.0000. If the last number in this function call is omitted, the number of values of y computed is by default 50. What is the interval between the 2.3 Arrays: Vectors and matrices 37 numbers 1 and 100 in this example? To compute the distance between the points you can implement the following command: dy = diff(y) yy = y(1:end-1) + dy./2 plot(yy,dy) You will find that you get a straight line from the point (yy, dy) = (1.3341, 0.6681) to the point (79.9742, 40.0516). Thus, the logspace function produces a set of points with an interval between them that increases linearly with y. The variable yy was introduced for two reasons. The first was to generate a vector of the same length as dy. The second was to examine the increase in the interval with increase in y that is obtained with the implementation of logspace. 2.3.4 Transposing vectors All of the vectors examined so far are row vectors. Each has one row and several columns. To generate the column vectors that are often needed in mathematics, you need to transpose such vectors—that is, you need to interchange their rows and columns. This is done with the single quote, or apostrophe (’), which is the nearest MATLAB can get to the mathematical prime ( ) that is often used to indicate the transpose. Enter x = 1:5 and then enter x’ to display the transpose of x. Note that x itself remains a row vector. Alternatively, or you can create a column vector directly: y = [1 4 8 0 -1]’ 2.3.5 Subscripts We can refer to particular elements of a vector by means of subscripts. Try the following: 1. Enter r = rand(1,7). This gives you a row vector of seven random numbers. 2. Enter r(3). This will display the third element of r. The numeral 3 is the subscript. 3. Enter r(2:4). This should give you the second, third, and fourth elements. 4. What about r(1:2:7) and r([1 7 2 6])? 5. Use an empty vector to remove elements from a vector: r([1 7 2]) = [ ] This will remove elements 1, 7, and 2. 38 CHAPTER 2: MATLAB Fundamentals To summarize: ■ ■ ■ ■ A subscript is indicated by parentheses. A subscript may be a scalar or a vector. In MATLAB subscripts always start at 1. Fractional subscripts are not allowed. 2.3.6 Matrices A matrix may be thought of as a table consisting of rows and columns. You create a matrix just as you do a vector, except that a semicolon is used to indicate the end of a row. For example, the statement a = [1 2 3; 4 5 6] results in a = 1 4 2 5 3 6 A matrix may be transposed: With a initialized as above, the statement a’ results in ans = 1 2 3 4 5 6 A matrix can be constructed from column vectors of the same length. Thus, the statements x = 0:30:180; table = [x’ sin(x*pi/180)’] result in table = 0 30.0000 60.0000 90.0000 120.0000 150.0000 180.0000 0 0.5000 0.8660 1.0000 0.8660 0.5000 0.0000 2.3 Arrays: Vectors and matrices 39 2.3.7 Capturing output You can use cut and paste techniques to tidy up the output from MATLAB statements if this is necessary for some sort of presentation. Generate the table of angles and sines as shown above. Select all seven rows of numerical output in the Command Window, and copy the selected output to the Editor. You can then edit the output, for example, by inserting text headings above each column (this is easier than trying to get headings to line up over the columns with a disp statement). The edited output can in turn be pasted into a report or printed as is (the File menu has a number of printing options). Another way of capturing output is with the diary command. The command diary filename copies everything that subsequently appears in the Command Window to the text file filename. You can then edit the resulting file with any text editor (including the MATLAB Editor). Stop recording the session with diary off Note that diary appends material to an existing file—that is, it adds new information to the end of it. 2.3.8 Structure plan A structure plan is a top-down design of the steps required to solve a particular problem with a computer. It is typically written in what is called pseudocode—that is, statements in English, mathematics, and MATLAB describing in detail how to solve a problem. You don’t have to be an expert in any particular computer language to understand pseudo-code. A structure plan may be written at a number of levels, each of increasing complexity, as the logical structure of the program is developed. Suppose we want to write a script to convert a temperature on the Fahrenheit scale (where water freezes and boils at 32◦ and 212◦ , respectively) to the Celsius scale. A first-level structure plan might be a simple statement of the problem: 1. Initialize Fahrenheit temperature 2. Calculate and display Celsius temperature 3. Stop Step 1 is pretty straightforward. Step 2 needs elaborating, so the second-level plan could be something like this: 1. Initialize Fahrenheit temperature (F) 2. Calculate Celsius temperature (C) as follows: Subtract 32 from F and multiply by 5/9 40 CHAPTER 2: MATLAB Fundamentals 3. Display the value of C 4. Stop There are no hard and fast rules for writing structure plans. The essential point is to cultivate the mental discipline of getting the problem logic clear before attempting to write the program. The top-down approach of structure plans means that the overall structure of a program is clearly thought out before you have to worry about the details of syntax (coding). This reduces the number of errors enormously. A script to implement this is as follows: % Script file to convert temperatures from F to C % F = input(’ Temperature in degrees F: ’) C = (F - 32) * 5 / 9; disp([’ Temperature in degrees C = ’,num2str(C)]) % STOP Two checks of the tool were done. They were for F = 32, which gave C = 0, and F = 212, which gave C = 100. The results were found to be correct and hence this simple script is, as such, validated. The essence of any structure plan and, hence, any computer program can be summarized as follows: 1. Input: Declare and assign input variables. 2. Operations: Solve expressions that use the input variables. 3. Output: Display in graphs or tables the desired results. 2.4 VERTICAL MOTION UNDER GRAVITY If a stone is thrown vertically upward with an initial speed u, its vertical displacement s after an elapsed time t is given by the formula s = ut − gt 2 /2, where g is the acceleration due to gravity. Air resistance is ignored. We would like to compute the value of s over a period of about 12.3 seconds at intervals of 0.1 seconds, and plot the distance–time graph over this period, as shown in Fig. 2.1. The structure plan for this problem is as follows: 1. % Assign the data (g, u, and t) to MATLAB variables 2. % Calculate the value of s according to the formula 3. % Plot the graph of s against t 4. % Stop 2.4 Vertical motion under gravity 41 FIGURE 2.1 Distance-time graph of a stone thrown vertically upward. This plan may seem trivial and a waste of time to write down. Yet you would be surprised how many beginners, preferring to rush straight to the computer, start with step 2 instead of step 1. It is well worth developing the mental discipline of structure-planning your program first. You can even use cut and paste to plan as follows: 1. Type the structure plan into the Editor (each line preceded by % as shown above). 2. Paste a second copy of the plan directly below the first. 3. Translate each line in the second copy into a MATLAB statement or statements (add % comments as in the example below). 4. Finally, paste all the translated MATLAB statements into the Command Window and run them (or you can just click on the green triangle in the toolbar of the Editor to execute your script). 5. If necessary, go back to the Editor to make corrections and repaste the corrected statements to the Command Window (or save the program in the Editor as an M-file and execute it). You might like to try this as an exercise before looking at the final program, which is as follows: % g % u % t Vertical motion under gravity = 9.81; % acceleration due to gravity = 60; % initial velocity in meters/sec = 0 : 0.01 : 12.3; % time in seconds 42 CHAPTER 2: MATLAB Fundamentals s = u * t - g / 2 * t .^ 2; % vertical displacement % in meters plot(t, s,’k’,’LineWidth’,3) title( ’Vertical motion under gravity’ ) xlabel( ’time’ ), ylabel( ’vertical displacement’ ) grid The graphical output is shown in Fig. 2.1. Note the following points: ■ ■ ■ ■ ■ ■ ■ Anything in a line following the symbol % is ignored by MATLAB and may be used as a comment (description). The statement t = 0 : 0.1 : 12.3 sets up a vector. The formula for s is evaluated for every element of the vector t, making another vector. The expression t.^2 squares each element in t. This is called an array operation and is different from squaring the vector itself, which is a matrix operation, as we will see later. More than one statement can be entered on the same line if the statements are separated by commas. A statement or group of statements can be continued to the next line with an ellipsis of three or more dots (...). The statement disp([t’ s’]) first transposes the row vectors t and s into two columns and constructs a matrix from them, which is then displayed. You might want to save the program under a helpful name, like throw.m, if you think you might come back to it. In that case, it would be worth keeping the structure plan as part of the file; just insert % symbols in front of each line. This way, the plan reminds you what the program does when you look at it again after some months. Note that you can use the context menu in the Editor to Comment/Uncomment a block of selected text. After you block selected text, right-click to see the context menu. To comment the text, scroll down to Comment, point, and click. 2.5 OPERATORS, EXPRESSIONS, AND STATEMENTS Any program worth its salt actually does something. What it basically does is evaluate expressions, such as u*t - g/2*t.^2 and execute (carry out) statements, such as balance = balance + interest 2.5 Operators, expressions, and statements 43 MATLAB is described as an expression based language because it interprets and evaluates typed expressions. Expressions are constructed from a variety of things, such as numbers, variables, and operators. First we need to look at numbers. 2.5.1 Numbers Numbers can be represented in MATLAB in the usual decimal form (fixed point) with an optional decimal point, 1.2345 -123 .0001 They may also be represented in scientific notation. For example, 1.2345 × 109 may be represented in MATLAB as 1.2345e9. This is also called floating-point notation. The number has two parts: the mantissa, which may have an optional decimal point (1.2345 in this example) and the exponent (9), which must be an integer (signed or unsigned). Mantissa and exponent must be separated by the letter e (or E). The mantissa is multiplied by the power of 10 indicated by the exponent. Note that the following is not scientific notation: 1.2345*10^9. It is actually an expression involving two arithmetic operations (* and ^) and therefore more time consuming. Use scientific notation if the numbers are very small or very large, since there’s less chance of making a mistake (e.g., represent 0.000000001 as 1e-9). On computers using standard floating-point arithmetic, numbers are represented to approximately 16 significant decimal digits. The relative accuracy of numbers is given by the function eps, which is defined as the distance between 1.0 and the next largest floating-point number. Enter eps to see its value on your computer. The range of numbers is roughly ±10−308 to ±10308 . Precise values for your computer are returned by the MATLAB functions realmin and realmax. As an exercise, enter the following numbers at the command prompt in scientific notation (answers follow in parentheses): 1.234 × 105 , (1.234e+05, 2.5.2 −8.765 × 10−4 , 10−15 , −1012 −8.765e−04, 1e−15, −1e+12) Data types MATLAB has more than a dozen fundamental data types (or classes). The default numeric data type is double precision; all MATLAB computations are in double precision. More information on data types can be found in the Help index. 44 CHAPTER 2: MATLAB Fundamentals Table 2.1 Arithmetic operations between two scalars. Operation Algebraic form MATLAB Addition a+b a + b Subtraction a−b a - b Multiplication a×b a * b Right division a/b a / b Left division b/a a \ b Power ab a ^ b Table 2.2 Precedence of arithmetic operations. Precedence Operator 1 Parentheses (round brackets) 2 Power, left to right 3 Multiplication and division, left to right 4 Addition and subtraction, left to right MATLAB also supports signed and unsigned integer types and single-precision floating-point, by means of functions such as int8, uint8, single, and the like. However, before mathematical operations can be performed on such types, they must be converted to double precision using the double function. 2.5.3 Arithmetic operators The evaluation of expressions is achieved by means of arithmetic operators. The arithmetic operations on two scalar constants or variables are shown in Table 2.1. Operators operate on operands (a and b in the table). Left division seems a little curious: Divide the right operand by the left operand. For scalar operands the expressions 1/3 and 3\1 have the same numerical value (a colleague of mine speaks of the latter as “3 under 1”). However, matrix left division has an entirely different meaning, as we will see later. 2.5.4 Operator precedence Several operations may be combined in one expression—for example, g * t ^ 2. MATLAB has strict precedence rules for which operations are performed first in such cases. The precedence rules for the operators in Table 2.1 are shown in Table 2.2. Note that parentheses have the highest precedence. Note also the difference between parentheses and square brackets. The former are used to alter the precedence of operators and to denote subscripts, while the latter are used to create vectors. 2.5 Operators, expressions, and statements 45 When operators in an expression have the same precedence, the operations are carried out from left to right. So a / b * c is evaluated as (a / b) * c and not as a / (b * c). Exercises 2.1 Evaluate the following MATLAB expressions yourself before checking the answers in MATLAB: 1 + 2 * 3 4 / 2 * 2 1 + 2 / 4 1 + 2 \ 4 2 * 2 ^ 3 2 * 3 \ 3 2 ^ (1 + 2)/3 1/2e-1 2.2 Use MATLAB to evaluate the following expressions. Answers are in parentheses. 1 (0.1667) (a) 2×3 (b) 22×3 (64) (c) 1.5 × 10−4 + 2.5 × 10−2 (0.0252; use scientiﬁc or ﬂoating-point notation) 2.5.5 The colon operator The colon operator has a lower precedence than the plus operator, as the following shows: 1+1:5 The addition is carried out first and a vector with elements 2, . . . , 5 is then initialized. You may be surprised at the following: 1+[1:5] Were you? The value 1 is added to each element of the vector 1:5. In this context, the addition is called an array operation because it operates on each element of the vector (array). Array operations are discussed below. See Appendix A for a complete list of MATLAB operators and their precedences. 46 CHAPTER 2: MATLAB Fundamentals Table 2.3 Arithmetic operators that operate element-by-element on arrays. Operator Description .* Multiplication ./ Right division .\ Left division .ˆ Power 2.5.6 The transpose operator The transpose operator has the highest precedence. Try 1:5’ The 5 is transposed first (into itself since it is a scalar!), and then a row vector is formed. Use square brackets if you want to transpose the whole vector: [1:5]’ 2.5.7 Arithmetic operations on arrays Enter the following statements at the command line: a = [2 4 5]; b = [6 2 2]; a .* b a ./ b MATLAB has four additional arithmetic operators, as shown in Table 2.3 that work on corresponding elements of arrays with equal dimensions. They are sometimes called array or element-by-element operations because they are performed element by element. For example, a .* b results in the following vector (sometimes called the array product): [a(1)*b(1) a(2)*b(2) a(3)*b(3)] that is, [12 8 10]. You will have seen that a ./ b gives element-by-element division. Now try The ith element of the first vector is raised to the power of the ith element of the second vector. The period (dot) is necessary for the array operations of multiplication, division, and exponentiation because these operations are defined differently for matrices; they are then called matrix operations (see Chapter 6). With a and b as defined above, try a + b and a - b. [2 3 4] .^ [4 3 1]. 2.5 Operators, expressions, and statements 47 For addition and subtraction, array operations and matrix operations are the same, so we don’t need the period to distinguish them. When array operations are applied to two vectors, both vectors must be the same size! Array operations also apply between a scalar and a nonscalar. Check this with and a .^ 2. This property is called scalar expansion. Multiplication and division operations between scalars and nonscalars can be written with or without the period (i.e., if a is a vector, 3 .* a is the same as 3 * a). 3 .* a A common application of element-by-element multiplication is finding the scalar product (also called the dot product) of two vectors x and y, which is defined as  xi yi x·y= i The MATLAB function sum(z) finds the sum of the elements of the vector z, so the statement sum(a .* b) will find the scalar product of a and b (30 for a and b defined above). Exercises Use MATLAB array operations to do the following: 2.1 Add 1 to each element of the vector [2 3 -1]. 2.2 Multiply each element of the vector [1 4 8] by 3. 2.3 Find the array product of the two vectors [1 2 [0 -2 3]) 2.4 Square each element of the vector [2 3 1]. 2.5.8 3] and [0 -1 1]. (Answer: Expressions An expression is a formula consisting of variables, numbers, operators, and function names. It is evaluated when you enter it at the MATLAB prompt. For example, evaluate 2π as follows: 2 * pi MATLAB’s response is ans = 6.2832 Note that MATLAB uses the function ans (which stands for answer) to return the last expression to be evaluated but not assigned to a variable. 48 CHAPTER 2: MATLAB Fundamentals If an expression is terminated with a semicolon (;), its value is not displayed, although it is still returned by ans. 2.5.9 Statements MATLAB statements are frequently of the form variable = expression as in s = u * t - g / 2 * t .^ 2; This is an example of an assignment statement because the value of the expression on the right is assigned to the variable (s) on the left. Assignment always works in this direction. Note that the object on the left-hand side of the assignment must be a variable name. A common mistake is to get the statement the wrong way around, as in a + b = c Basically any line that you enter in the Command Window or in a program, which MATLAB accepts, is a statement, so a statement can be an assignment, a command, or simply an expression, such as x = 29; clear pi/2 % assignment % command % expression This naming convention is in keeping with most programming languages and serves to emphasize the different types of statements that are found in programming. However, the MATLAB documentation tends to refer to all of these as “functions.” As we have seen, a semicolon at the end of an assignment or expression suppresses any output. This is useful for suppressing irritating output of intermediate results (or large matrices). A statement that is too long to fit on one line may be continued to the next line with an ellipsis of at least three dots: x = 3 * 4 - 8 .... / 2 ^ 2; Statements on the same line may be separated by commas (output not suppressed) or semicolons (output suppressed): 2.5 Operators, expressions, and statements 49 a = 2; b = 3, c = 4; Note that the commas and semicolons are not technically part of the statements; they are separators. Statements may involve array operations, in which case the variable on the left-hand side may become a vector or a matrix. 2.5.10 Statements, commands, and functions The distinction between MATLAB statements, commands, and functions can be a little fuzzy, since all can be entered on the command line. However, it is helpful to think of commands as changing the general environment in some way, for example, load, save, and clear. Statements do the sort of thing we usually associate with programming, such as evaluating expressions and carrying out assignments, making decisions (if), and repeating (for). Functions return with calculated values or perform some operation on data, such as sin and plot. 2.5.11 Formula vectorization With array operations, you can easily evaluate a formula repeatedly for a large set of data. This is one of MATLAB’s most useful and powerful features, and you should always look for ways to exploit it. Let us again consider, as an example, the calculation of compound interest. An amount of money A invested over a period of years n with an annual interest rate r grows to an amount A(1 + r)n . Suppose we want to calculate final balances for investments of$750, $1000,$3000, $5000, and$11,999 over 10 years
with an interest rate of 9%. The following program (comp.m) uses array operations on a vector of initial investments to do this:
format bank
A = [750 1000 3000 5000 11999];
r = 0.09;
n = 10;
B = A * (1 + r) ^ n;
disp( [A’ B’] )

The output is
750.00
1000.00
3000.00
5000.00
11999.00

1775.52
2367.36
7102.09
11836.82
28406.00

50 CHAPTER 2: MATLAB Fundamentals

Note the following:
■

■

■

■

In the statement B = A * (1 + r) ^ n, the expression (1 + r) ^ n is
evaluated first because exponentiation has a higher precedence than multiplication.
Each element of the vector A is then multiplied by the scalar (1 + r) ^ n
(scalar expansion).
The operator * may be used instead of .* because the multiplication is
between a scalar and a nonscalar (although .* would not cause an error
because a scalar is a special case of an array).
A table is displayed whose columns are given by the transposes of A and B.

This process is called formula vectorization. The operation in the statement described in bullet item 1 is such that every element in the vector B is determined
by operating on every element of vector A all at once, by interpreting once a
single command line.
See if you can adjust the program comp.m to find the balances for a single
amount A ($1000) over 1, 5, 10, 15, and 20 years. (Hint: use a vector for n: [1 5 10 15 20].) Exercises 2.1 Evaluate the following expressions yourself (before you use MATLAB to check). The numerical answers are in parentheses. (a) 2 / 2 * 3 (3) (b) 2 / 3 ˆ 2 (2/9) (c) (2 / 3) ˆ 2 (4/9) (d) 2 + 3 * 4 - 4 (10) (e) 2 ˆ 2 * 3 / 4 + 3 (6) (f) 2 ˆ (2 * 3) / (4 + 3) (64/7) (g) 2 * 3 + 4 (10) (h) 2 ˆ 3 ˆ 2 (64) (i) - 4 ˆ 2 (-16; ˆ has higher precedence than -) 2.2 Use MATLAB to evaluate the following expressions. The answers are in parentheses. √ 2 (1.4142; use sqrt or ˆ0.5) (a) 3+4 (b) (0.6364; use brackets) 5+6 (c) Find the sum of 5 and 3 divided by their product (0.5333) 2 (d) 23 (512) (e) Find the square of 2π (39.4784; use pi) 2 (19.7392) (f) 2π√ (g) 1/ 2π (0.3989) 1 (h) (0.2821) √ 2 π 2.5 Operators, expressions, and statements 51 (i) (j) Find the cube root of the product of 2.3 and 4.5 (2.1793) 2 1 − 3+2 (0.2) 2 1 + 3−2 (k) 1000(1 + 0.15/12)60 (2107.2—for example,$1000 deposited for 5 years
at 15% per year, with the interest compounded monthly)
(l) (0.0000123 + 5.678 × 10−3 ) × 0.4567 × 10−4 (2.5988 × 10−7 ; use scientiﬁc notation—for example, 1.23e-5 . . . ; do not use ˆ)
2.3 Try to avoid using unnecessary parentheses in an expression. Can you spot the
errors in the following expression? (Test your corrected version with MATLAB.)
(2(3+4)/(5*(6+1))^2

Note that the MATLAB Editor has two useful ways of dealing with the problem
of “unbalanced delimiters” (which you should know about if you have been
working through Help!):
■

When you type a closing delimiter, that is, a right ), ], or }, its matching
opening delimiter is brieﬂy highlighted. So if you don’t see the highlighting when you type a right delimiter, you immediately know you’ve
got one too many.

2.4 Set up a vector n with elements 1, 2, 3, 4, 5. Use MATLAB array operations on
it to set up the following four vectors, each with ﬁve elements:
(a) 2, 4, 6, 8, 10
(b) 1/2, 1, 3/2, 2, 5/2
(c) 1, 1/2, 1/3, 1/4, 1/5
(d) 1, 1/22 , 1/32 , 1/42 , 1/52
2.5 Suppose vectors a and b are deﬁned as follows:
a = [2 -1 5 0];
b = [3 2 -1 4];

Evaluate by hand the vector c in the following statements. Check your answers with MATLAB.
(a) c = a - b;
(b) c = b + a - 3;
(c) c = 2 * a + a .ˆ b;
(d) c = b ./ a;
(e) c = b . a;
(f) c = a .ˆ b;
(g) c = 2.ˆb+a;
(h) c = 2*b/3.*a;
(i) c = b*2.*a;
2.6 Water freezes at 32◦ and boils at 212◦ on the Fahrenheit scale. If C and F are
Celsius and Fahrenheit temperatures, the formula
F = 9C/5 + 32

52 CHAPTER 2: MATLAB Fundamentals

converts from one to the other. Use the MATLAB command line to convert
Celsius 37◦ (normal human temperature) to Fahrenheit (98.6◦ ).
2.7 Engineers often have to convert from one unit of measurement to another,
which can be tricky sometimes. You need to think through the process carefully. For example, convert 5 acres to hectares, given that an acre is 4840
square yards, a yard is 36 inches, an inch is 2.54 centimeters, and a hectare
is 10,000 square meters. The best approach is to develop a formula to convert
x acres to hectares. You can do this as follows.
■
■

■

One square yard = (36 × 2.54)2 cm2
So one acre = 4840 × (36 × 2.54)2 cm2
= 0.4047 × 108 cm2
= 0.4047 hectares
So x acres = 0.4047 × x hectares

Once you have found the formula (but not before), MATLAB can do the rest:
x = 5;

% acres

h = 0.4047 * x;
disp( h )

% hectares

2.8 Develop formulae for the following conversions, and use some MATLAB statements to ﬁnd the answers (in parentheses).
(a) Convert 22 yards (an imperial cricket pitch) to meters. (20.117 meters)
(b) One pound (weight) = 454 grams. Convert 75 kilograms to pounds.
(165.20 pounds)
(c) Convert 49 meters/second (terminal velocity for a falling human-shaped
object) to kilometers per hour. (176.4 kilometers per hour)
(d) One atmosphere pressure = 14.7 pounds per square inch (psi) =
101.325 kilo Pascals (kPa). Convert 40 psi to kPa. (275.71 kPa)
(e) One calorie = 4.184 joules. Convert 6.25 kilojoules to calories. (1.494 kilocalories)

2.6 OUTPUT
There are two straightforward ways of getting output from MATLAB:
■

■

Entering a variable name, assignment, or expression on the command
line, without a semicolon
Using the disp statement (e.g., disp( x ))

2.6.1 The disp statement
The general form of disp for a numeric variable is
disp( variable )

2.6 Output 53

When you use disp, the variable name is not displayed, and you don’t get a
line feed before the value is displayed, as you do when you enter a variable
name on the command line without a semicolon. disp generally gives a neater
display.
You can also use disp to display a message enclosed in apostrophes (called a
string). Apostrophes that are part of the message must be repeated:
disp( ’Pilate said, ’’What is truth?’’’ );

To display a message and a value on the same line, use the following trick:
x = 2;
disp( [’The answer is ’, num2str(x)] );

The output should be

Square brackets create a vector, as we have seen. If we want to display a string,
we create it; that is, we type a message between apostrophes. This we have
done already in the above example by defining the string ’The answer is ’.
Note that the last space before the second apostrophe is part of the string. All
the components of a MATLAB array must be either numbers or strings (unless
you use a cell array—see Chapter 10), so we convert the number x to its string
representation with the function num2str; read this as “number to string.”
You can display more than one number on a line as follows:
disp( [x y z] )

The square brackets create a vector with three elements, which are all displayed.
The command more on enables paging of output. This is very useful when displaying large matrices, for example, rand(100000,7) (see help more for details).
If you forget to switch on more before displaying a huge matrix, you can always
stop the display with Ctrl+C.
input and output capabilities in MATLAB. You can begin your search for information by clicking the question mark at the top of the desktop to open the
help documents. Then search for fopen, a utility which allows you to open a
file. Scroll to the bottom of the page in the help manual on this topic and
find the following list of functions: fclose, feof, ferror, fprintf, fread,
fscanf, fseek, ftell, fwrite. Click on fprintf, which is a formatted output

54 CHAPTER 2: MATLAB Fundamentals

utility that is popular if you are a C-language programmer. Search for input in
examples in this text. Of course, the simplest input of data is the assignment
of values to variables in a program of commands.

2.6.2 The format command
The term format refers to how something is laid out: in this case MATLAB output. The default format in MATLAB has the following basic output rules:
■

■

It always attempts to display integers (whole numbers) exactly. However,
if the integer is too large, it is displayed in scientific notation with five
significant digits—1234567890 is displayed as 1.2346e+009 (i.e., 1.2346×
109 ). Check this by first entering 123456789 at the command line and
then 1234567890.
Numbers with decimal parts are displayed with four significant digits. If
the value x is in the range 0.001 < x ≤ 1000, it is displayed in fixed-point
form; otherwise, scientific (floating-point) notation is used, in which
case the mantissa is between 1 and 9.9999 ( e.g., 1000.1 is displayed
as 1.0001e+003). Check this by entering the following numbers at the
prompt (on separate lines): 0.0011, 0.0009, 1/3, 5/3, 2999/3, 3001/3.

You can change from the default with variations on the format command,
as follows. If you want values displayed in scientific notation (floating-point
form) whatever their size, enter the command
format short e

All output from subsequent disp statements will be in scientific notation, with
five significant digits, until the next format command is issued. Enter this command and check it with the following values: 0.0123456, 1.23456, 123.456
(all on separate lines).
If you want more accurate output, you can use format long e. This also
gives scientific notation but with 15 significant digits. Try it out on 1/7. Use
format long to get fixed-point notation with 15 significant digits. Try 100/7
and pi. If you’re not sure of the order of magnitude of your output you can try
format short g or format long g. The g stands for “general.” MATLAB decides
in each case whether to use fixed or floating point.
Use format bank for financial calculations; you get fixed point with two decimal digits (for cents). Try it on 10000/7. Suppress irritating line feeds with
format compact, which gives a more compact display. format loose reverts to
a more airy display. Use format hex to get hexadecimal display.
Use format rat to display a number as a rational approximation (ratio of two
integers). For example, pi is displayed as 355/113, a pleasant change from the

2.7 Repeating with for 55

tired old 22/7. Note that even this is an approximation! Try out format rat on
√
2 and e (exp(1)).
The symbols +, −, and a space are displayed for positive, negative, and zero
elements of a vector or matrix after the command format +. In certain applications this is a convenient way of displaying matrices. The command format
by itself reverts to the default format. You can always try help format if you’re
confused!

2.6.3

Scale factors

Enter the following commands (MATLAB’s response is also shown).
 format compact
 x = [1e3 1 1e-4]
x =
1.0e+003 *
1.0000

0.0010

0.0000

With format short (the default) and format long, a common scale factor is
applied to the whole vector if its elements are very large or very small or differ
greatly in magnitude. In this example, the common scale factor is 1000, so the
elements displayed must all be multiplied by it to get their proper value—for
example, for the second element 1.0e+003 * 0.0010 gives 1. Taking a factor
of 1000 out of the third element (1e-4) leaves 1e-7, which is represented by
0.0000 since only four decimal digits are displayed.
If you don’t want a scale factor, try format bank or format short e:
x
x =
1000.00

1.00

0.00

1.0000e+000

1.0000e-004

 format short e
x
x =
1.0000e+003

2.7 REPEATING WITH for
So far we have seen how to get data into a program (i.e., provide input), how
to do arithmetic, and how to get some results (i.e., get output). In this section
we look at a new feature: repetition. This is implemented by the extremely

56 CHAPTER 2: MATLAB Fundamentals

powerful for construct. We will first look at some examples of its use, followed
by explanations.
For starters, enter the following group of statements on the command line.
Enter the command format compact first to make the output neater:
for i = 1:5, disp(i), end

Now change it slightly to
for i = 1:3, disp(i), end

for i = 1:0, disp(i), end

Can you see what’s happening? The disp statement is repeated five times, three
times, and not at all.

2.7.1 Square roots with Newton’s method
The square root x of any positive number a may be found using only the arithmetic operations of addition, subtraction, and division with Newton’s method.
This is an iterative (repetitive) procedure that refines an initial guess.
To introduce in a rather elementary way the notion of structured programming
(to be described in more detail in Chapter 3), let us consider the structure plan
of the algorithm to find a square root and a program with sample output for
a = 2.
Here is the structure plan:
1. Initialize a
2. Initialize x to a/2
3. Repeat 6 times (say) the following:
Replace x by (x + a/x)/2
Display x
4. Stop
Here is the program:
a = 2;
x = a/2;
disp([’The approach to sqrt(a) for a = ’, num2str(a)])

2.7 Repeating with for 57

for i = 1:6
x = (x + a / x) / 2;
disp( x )
end
disp( ’Matlab’’s value: ’ )
disp( sqrt(2) )

Here is the output (after selecting format long):
The approach to sqrt(a) for a = 2
1.50000000000000
1.41666666666667
1.41421568627451
1.41421356237469
1.41421356237310
1.41421356237310
Matlab’s value:
1.41421356237310

√
The value of x converges to a limit rather quickly in this case, a. Note that it
is identical to the value returned by MATLAB’s sqrt function. Most computers
and calculators use a similar method internally to compute square roots and
other standard mathematical functions.
The general form of Newton’s method is presented in Chapter 17.

2.7.2

Factorials!

Run the following program to generate a list of n and n! (“n factorial,” or
“n shriek”), where
n! = 1 × 2 × 3 × . . . × (n − 1) × n

(2.1)

n = 10;
fact = 1;
for k = 1:n
fact = k * fact;
disp( [k fact] )
end

Experiment to find the largest value of n for which MATLAB can find the n factorial. (You had better leave out the disp statement! Or you can move it from
above the end command to below it.)

58 CHAPTER 2: MATLAB Fundamentals

2.7.3 Limit of a sequence
for loops are ideal for computing successive members of a sequence (as in
Newton’s method). The following example also highlights a problem that
sometimes occurs when computing a limit. Consider the sequence

xn =

an
, n = 1, 2, 3 . . .
n!

where a is any constant and n! is the factorial function defined above. The
question is this: What is the limit of this sequence as n gets indefinitely large?
Let’s take the case a = 10. If we try to compute xn directly, we can get into
trouble, because n! grows very rapidly as n increases, and numerical overflow
can occur. However, the situation is neatly transformed if we spot that xn is
related to xn−1 as follows:
xn =

axn−1
.
n

There are no numerical problems now.
The following program computes xn for a = 10 and increasing values of n.
a = 10;
x = 1;
k = 20;

% number of terms

for n = 1:k
x = a * x / n;
disp( [n x] )
end

2.7.4 The basic for construct
In general the most common form of the for loop (for use in a program, not
on the command line) is
for index = j:k
statements;
end

or
for index = j:m:k
statements;
end

2.7 Repeating with for 59

Note the following points carefully:
■
■

■

j :k is a vector with elements j, j + 1, j + 2, . . . , k.
j :m:k is a vector with elements j, j + m, j + 2m, . . . , such that the last
element does not exceed k if m > 0 or is not less than k if m < 0.
index must be a variable. Each time through the loop it will contain the
next element of the vector j :k or j :m:k, and statements (there may be
one or more) are carried out for each of these values.
If the for construct has the form
for k = first:increment:last

The number of times the loop is executed may be calculated from the
following equation:

floor

last − first

increment

+1

where the MATLAB function floor(x) rounds x down toward −∞. T