Essential MATLAB for Scientists and Engineers

Programming, Math, etc. · course

Voir tous les documents en programmation

Butterworth-Heinemann, an Imprint of Elsevier, Inc.

84 Theobald’s Road, London WC1X 8RR, UK

Radarweg 29, PO Box 211, 1000 AE Amsterdam, The Netherlands

Linacre House, Jordan Hill, Oxford OX2 8DP, UK

30 Corporate Drive, Suite 400, Burlington, MA 01803, USA

525 B Street, Suite 1900, San Diego, CA 92101-4495, USA

Copyright © 2002 Elsevier Inc. All rights reserved

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) (0) 1865 843830; fax (+44) (0) 1865 853333; email:

[email protected]. Alternatively you can submit your request online by visiting

the Elsevier web site at http://elsevier.com/locate/permissions, and selecting Obtaining

permission to use Elsevier material

Essential MATLAB for Scientists and Engineers

by Brian Hahn

ISBN 978-0-7506-5240-3

iv

Part I Essentials

1 Getting going

Objective

1.1 Introduction

1.2 Using MATLAB

1.3 Website

Summary

.....................................................................................

......................................................................................................

.......................................................................................................................

..............................................................................................................

........................................................................................................

...................................................................................................................

.......................................................................................................................

2 MATLAB fundamentals

Objectives

2.1 The MATLAB desktop

2.2 Programs

2.3 Variables and the workspace

2.4 Arrays: vectors and matrices

2.5 Vertical motion under gravity

2.6 Operators, expressions and statements

2.7 Output

2.8 Repeating with for

2.9 Decisions

2.10 Complex numbers

2.11 More on input and output

2.12 Odds (cid:146)n ends

2.13 Programming style

Summary

.....................................................................................

......................................................................................................................

.............................................................................................

.................................................................................................................

..................................................................................

...................................................................................

...................................................................................

..................................................................

......................................................................................................................

...................................................................................................

.................................................................................................................

.................................................................................................

......................................................................................

.........................................................................................................

................................................................................................

.......................................................................................................................

3 Developing algorithms

Objective

3.1 Structure plans

3.2 Structured programming with functions

Summary

......................................................................................

.......................................................................................................................

........................................................................................................

...................................................................

.......................................................................................................................

4 MATLAB functions

Objective

4.1 Projectile motion

4.2 Some common functions

Summary

.............................................................................................

.......................................................................................................................

......................................................................................................

.........................................................................................

.......................................................................................................................

5 Logical vectors

Objectives

5.1 Examples

5.2 Logical operators

5.3 Subscripting with logical vectors

5.4 Logical functions

5.5 Logical vectors instead of elseif ladders

Summary

...................................................................................................

......................................................................................................................

.................................................................................................................

.....................................................................................................

.............................................................................

......................................................................................................

..................................................................

.......................................................................................................................

6 Matrices

..............................................................................................................

......................................................................................................................

............................................................................................................

.....................................................................................................

.............................................................................................

.......................................................................................................................

Objectives

6.1 Some basics

6.2 Matrix operations

6.3 Other matrix functions

Summary

7 Introduction to graphics

Objective

7.1 Basic 2-D graphs

....................................................................................

.......................................................................................................................

.....................................................................................................

I

3

3

3

3

9

9

10

10

11

11

15

17

21

22

31

33

39

45

46

48

50

51

58

58

58

60

60

63

63

63

65

69

71

71

Publicité

72

75

78

79

81

83

86

86

86

98

100

100

102

102

102

7.2 3-D plots

Summary

..................................................................................................................

.......................................................................................................................

8 Loops

..................................................................................................................

......................................................................................................................

................................................................................

..........................................................................

.......................................................................................................................

Objectives

8.1 Determinate repetition with for

8.2 Indeterminate repetition with while

Summary

9 Errors and pitfalls

Objective

9.1 Syntax errors

9.2 Pitfalls and surprises

9.3 Errors in logic

9.4 Rounding error

9.5 Trapping and generating errors

Summary

..............................................................................................

.......................................................................................................................

...........................................................................................................

...............................................................................................

..........................................................................................................

........................................................................................................

...............................................................................

.......................................................................................................................

10 Function M-files

Objective

10.1 Some examples

10.2 Basic rules

10.3 Function handles

10.4 Command/function duality

10.5 Function name resolution

10.6 Debugging M-files

10.7 Recursion

Summary

...............................................................................................

.......................................................................................................................

.....................................................................................................

.............................................................................................................

...................................................................................................

.....................................................................................

......................................................................................

.................................................................................................

..............................................................................................................

.......................................................................................................................

Part II More Advanced Topics and Applications

11 Vectors as arrays: working with subscripts

.................................

..................................................

.......................................................................................................................

.................................................................................................

...............................................................

...................................................................................................................

.......................................................................................................................

Objective

11.1 Update processes

11.2 Frequencies, bar charts and histograms

11.3 Sorting

Summary

12 Arrays of characters: strings

Objective

12.1 Basic concepts

12.2 Two-dimensional strings

12.3 eval and text macros

Summary

..........................................................................

.......................................................................................................................

......................................................................................................

........................................................................................

.............................................................................................

.......................................................................................................................

13 Advanced data structures

Objectives

13.1 Structures

13.2 Cell arrays

13.3 Classes and objects

Summary

...............................................................................

......................................................................................................................

..............................................................................................................

.............................................................................................................

..............................................................................................

.......................................................................................................................

14 More graphics

Objectives

14.1 Handle Graphics

14.2 Editing plots

14.3 Animation

14.4 Colour etc.

..................................................................................................

......................................................................................................................

....................................................................................................

...........................................................................................................

..............................................................................................................

.............................................................................................................

110

120

124

124

124

126

132

136

136

136

138

139

139

140

140

142

142

142

144

149

150

151

151

153

154

II

159

159

159

164

166

168

170

170

170

173

174

176

178

Publicité

178

178

180

182

183

184

184

184

189

190

193

14.5 Lighting and camera

14.6 Saving, printing and exporting graphs

Summary

..............................................................................................

...................................................................

.......................................................................................................................

15 Graphical User Interfaces (GUIs)

Objectives

15.1 Basic structure of a GUI

15.2 A first example: getting the time

15.3 Newton again

15.4 Axes on a GUI

15.5 Adding colour to a button

Summary

....................................................................

......................................................................................................................

........................................................................................

............................................................................

........................................................................................................

.......................................................................................................

......................................................................................

.......................................................................................................................

16 Importing and exporting data

Objectives

16.1 The load and save commands

16.2 The Import Wizard

16.3 Low-level file I/O functions

16.4 Other import/export functions

Summary

.........................................................................

......................................................................................................................

..............................................................................

.................................................................................................

....................................................................................

................................................................................

.......................................................................................................................

17 Simulation

Objective

17.1 Random number generation

17.2 Spinning coins

17.3 Rolling dice

17.4 Bacteria division

17.5 A random walk

17.6 Traffic flow

17.7 Normal (Gaussian) random numbers

Summary

.........................................................................................................

.......................................................................................................................

..................................................................................

.......................................................................................................

............................................................................................................

....................................................................................................

.......................................................................................................

.............................................................................................................

....................................................................

.......................................................................................................................

18 More matrices

Objectives

18.1 Leslie matrices: population growth

18.2 Markov processes

18.3 Linear equations

18.4 Sparse matrices

Summary

...................................................................................................

......................................................................................................................

........................................................................

.................................................................................................

....................................................................................................

....................................................................................................

.......................................................................................................................

19 Introduction to numerical methods

Objective

19.1 Equations

19.2 Integration

19.3 Numerical differentiation

19.4 First-order differential equations

19.5 Linear ordinary differential equations (LODEs)

19.6 Runge(cid:150)Kutta methods

19.7 A GUI ODE solver: Driver

19.8 A partial differential equation

19.9 Other numerical methods

Summary

................................................................

.......................................................................................................................

..............................................................................................................

.............................................................................................................

........................................................................................

............................................................................

.....................................................

............................................................................................

......................................................................................

.................................................................................

......................................................................................

.......................................................................................................................

A Syntax quick reference

A.1 Expressions

A.2 Function M-files

A.3 Graphics

.....................................................................................

............................................................................................................

.......................................................................................................

..................................................................................................................

195

196

197

198

198

198

199

202

204

205

206

207

207

207

208

209

212

213

214

214

214

215

216

216

216

218

220

220

224

224

224

227

229

233

235

236

236

236

240

242

243

Publicité

247

247

251

260

262

263

267

267

267

267

A.4 if and switch

A.5 for and while

A.6 Input/output

A.7 load/save

A.8 Vectors and matrices

............................................................................................................

............................................................................................................

.............................................................................................................

.................................................................................................................

..............................................................................................

B Operators

...........................................................................................................

C Command and function quick reference

C.1 General purpose commands

C.2 Logical functions

C.3 Language constructs and debugging

C.4 Matrices and matrix manipulation

C.5 Mathematical functions

C.6 Matrix functions

C.7 Data analysis

C.8 Polynomial functions

C.9 Function functions

C.10 Sparse matrix functions

C.11 Character string functions

C.12 File I/O functions

C.13 Graphics

.........................................................

..................................................................................

.....................................................................................................

......................................................................

...........................................................................

...........................................................................................

.......................................................................................................

..........................................................................................................

...............................................................................................

...................................................................................................

........................................................................................

.....................................................................................

...................................................................................................

...............................................................................................................

D ASCII character codes

......................................................................................

E Solutions to selected exercises

.......................................................................

Index

.......................................................................................................................

268

268

269

270

270

271

272

273

273

274

274

275

276

276

276

276

276

277

277

277

279

280

291

Part I

Essentials

1

Getting going

Objective

The objective of this chapter is to enable you to

use some simple MATLAB commands from the Command Window.

1.1 Introduction

MATLAB is a powerful computing system for handling the calculations involved in scientific and engi-

neering problems. The name MATLAB stands for MATrix LABoratory, because the system was designed

to make matrix computations particularly easy. If you don’t know what a matrix is, don’t worry—we

will look at them in detail later. For the moment we can forget about them.

This book assumes that you have never used a computer before to do the sort of scientific calculations

that MATLAB handles. You will however need to be able to find your way around a computer keyboard

and the operating system running on your computer (e.g. Windows or UNIX). The only other computer-

related skill you will need is some very basic text editing.

One of the many things you will like about MATLAB (and which 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 the answers immediately. The problems

solved in this way can be very simple, like finding a square root, or they can be much more complicated,

like finding the solution of a system of differential equations. The point is that you have to enter only

one or two commands, and you get the answers at once. MATLAB does most of the work for you.

In the rest of this Chapter we will look at some simple examples for you to try out. Don’t bother about

understanding exactly what is happening. The understanding will come in later chapters when we look

at the details.

1.2 Using MATLAB

In order to use MATLAB it must either be installed on your computer, or you must have access to a

network where it is available. Throughout this book the latest version of MATLAB at the time of writing

is assumed—Version 6.1 (Release 12.1).

3

4 Essential MATLAB for Scientists and Engineers

Figure 1.1 The MATLAB desktop

To start MATLAB from Windows, double-click the MATLAB icon on your Windows desktop. To

start it from a UNIX platform, type matlab at the operating system prompt. When MATLAB starts,

the MATLAB desktop opens as shown in Figure 1.1. The window in the desktop that concerns us for

this chapter is the Command Window, where the special (cid:2) prompt appears. This prompt means that

MATLAB is waiting for a command. You can quit MATLAB at any time with one of the following:

• Click on the close box in the top right corner of the MATLAB desktop.

Select Exit MATLAB from the desktop File menu.

• Enter quit or exit at the Command Window prompt.

Once you have started MATLAB try the following exercises in the Command Window. If necessary,

make the Command Window active by clicking anywhere inside its border.

1. First let’s see if MATLAB is any good at arithmetic.

(a) Type 2+3 after the (cid:2) prompt, followed by Enter, i.e. press the Enter key, indicated by <Enter>

below:

(cid:2) 2+3 <Enter>

Commands are only carried out when you press Enter.

(b) If MATLAB got that right, try 2*3, i.e.

(cid:2) 2*3 <Enter>

What about 1/2 and 2^3? Can you figure out what the symbols *, / and ^ mean?

• You can edit a MATLAB command before pressing Enter by using various combinations

Getting going 5

of the Backspace, Left-arrow, Right-arrow and Del keys.

• The line with the (cid:2) prompt is called the command line.

• You can select (and edit) previous commands you have entered using Up-arrow and Down-

arrow. But remember to press Enter to get the command carried out. This helpful feature

is called command line editing.

• MATLAB has a useful editing feature called smart recall. Just type the first few characters

of the command you want to recall, e.g. type the characters 2* and press the Up-arrow

key—this recalls the most recent command starting with 2*.

(c) How do you think MATLAB would handle 0/1 and 1/0? Try it.

MATLAB is sensible about errors. It warns you in case you didn’t realize you were dividing by

zero, but still gives the answer Inf. If you insist on using ∞ in a calculation, type the symbol

Inf (short for infinity), e.g. try 13+Inf and 29/Inf.

(d) Another special value that you may meet is NaN, which stands for Not-a-Number. It is the

answer to calculations like 0/0.

2. Now for some algebra.

(a) Enter the command (in programming jargon a statement) a = 2, i.e. the MATLAB command

line should look like this:

(cid:2) a = 2 <Enter>

a is called 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 fol-

lowed on a new line by a = a * 10. Do you agree with the final value of a?

Publicité

(b) Now enter the statement

b = 3; <Enter>

Can you see the effect of the semi-colon (;)? It prevents the value of b from being displayed.

However, b still has the value 3 as you can see simply by entering its name without a semi-colon

at the prompt.

(c) Assign any values you like to two variables x and y. Now see if you can in a single statement

assign the sum of x and y to a third variable z.

3. MATLAB has most of the usual mathematical functions that you will find on your calculator, like

sin, cos, log (meaning the natural logarithm), as well as a lot more.

(a) 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 MATLAB’s very many built-in functions.

(b) Trigonometric functions like sin(x) expect the argument x to be in radians. Multiply degrees

by π/180 to get radians. For example, use MATLAB to calculate sin(90◦). The answer should

be 1, i.e. sin(90*pi/180).

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

4. MATLAB has a lot of general functions. Try date and calendar for starters.

5. MATLAB also has a number of commands, such as clc (for clear command window). help is

another command 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 commands tend to change the

environment in some way, e.g. by clearing the screen, or saving some statements to disk.

6 Essential MATLAB for Scientists and Engineers

6. Variables such as a and b above are called scalars; they are single-valued. MATLAB also handles

vectors (generally referred to in MATLAB as arrays), which are the key to many powerful features

of the language. The easiest way of defining a vector where the elements (components) increase by

the same amount is with a statement like

(cid:2) x = 0 : 10;

Enter it. That’s a colon (:) between the 0 and the 10. There’s no need to leave a space on either

side of it, but it makes it more readable. Enter x to check that x is a vector now.

(a) The really cool thing about MATLAB is that other vectors can now be defined in terms of our

vector x. Try

(cid:2) y = 2 * x

and

(cid:2) z = sin(x)

(no semi-colons).

(b) All you have to do to draw the graph of sin(x) is to enter the command

(cid:2) plot(x, sin(x))

(or simply plot(x, z) if you defined z correctly). The graph appears in a separate figure

window (see Figure 1.2). You can select the Command Window or figure windows by clicking

anywhere inside them, or you can use the Windows pull-down menus in any of these windows.

(c) The graph looks rather crude, because more points need to be plotted between 0 and 10. To fix

this, make the vector x go up in steps of 0.1 instead of 1 like this:

(cid:2) x = 0 : 0.1 : 10;

When there are three numbers separated by two colons in this way, the middle number is the

increment. Now enter plot(x, sin(x)) to get a much neater graph.

You can put a grid on the graph to make it easier to read with

(cid:2) plot(x, sin(x)), grid

(d) If you want to see more cycles of the sine graph just use command-line editing to change

sin(x) to sin(2*x).

(e) Try drawing the graph of tan(x) over the same domain. You may find aspects of your graph

surprising. A more accurate version is presented in Chapter 5.

(f) Another useful Command Window editing feature is tab completion: type the first few letters

of a MATLAB name and then press the Tab key. If the name is unique, it is automatically

completed. If the name is not unique, press the Tab a second time to see all the possibilities.

Try this feature out, e.g. by typing ta at the command line followed by Tab twice.

7. If you’re into linear equations, you can solve two simultaneous equations very easily, e.g.

x + 2y = 4,

2x − y = 3.

Getting going 7

Figure 1.2 A figure window

All you have to do is type the following commands (exactly as they are)

(cid:2) a = [1 2; 2 -1];

(cid:2) b = [4; 3];

(cid:2) x = a\b

which result in

x =

2

1

i.e. x = 2, y = 1.

8. If you want a spectacular sample of what MATLAB has to offer, try demo at the command line.

Alternatively, double-click Demos in the Launch Pad. (If you can’t see Demos, click on the + next

to the MATLAB item in the Launch Pad to expand it.)

For a listing of demonstration programs by category try help demos.

8 Essential MATLAB for Scientists and Engineers

9. MATLAB has a very useful ‘help’ system, which we look at in more detail in Chapter 2. For the

moment type help at the command line to see all the categories on which you can get help. E.g.

type help elfun to see all MATLAB’s elementary mathematical functions.

lookfor enables you to search for a particular string in the help text of functions, e.g.

lookfor eigenvalue displays all the functions relating to eigenvalues.

10. MATLAB has all sorts of other goodies. For example, you can generate magic squares, e.g.

magic(10), where the rows, columns and the main diagonal all 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

entries in the square are heights above sea level of points on a map, and draws the contour lines.

contour(magic(22)) looks rather nice.

11. If you want to see the famous Mexican hat shown in Figure 1.3, enter the following four lines (be

careful not to make any typing errors):

(cid:2) [x y ] = meshgrid(-8 : 0.5 : 8);

(cid:2) r = sqrt(x.^2 + y.^2) + eps;

(cid:2) z = sin(r) ./ r;

(cid:2) mesh(z);

Try surf(z) to generate a faceted (tiled) view of the surface.

surfc(z) or meshc(z) draws a 2-D contour plot under the surface.

The command

(cid:2)surf(z), shading flat

produces a rather nice picture by removing the grid lines.

12. If your PC has a speaker you could try

load handel

sound(y,Fs)

for a snatch of Handel’s Hallelujah Chorus.

1

0.8

0.6

0.4

0.2

0

−0.2

−0.4

35

30

25

20

15

10

5

35

30

25

20

15

10

0

0

5

Figure 1.3 The Mexican hat

For some different sounds you can try loading chirp, gong, laughter, splat and train. You

have to run sound(y,Fs) for each one.

13. If you want to see a view of the Earth from space, try

Getting going 9

load earth

image(X); colormap(map)

axis image

14. Finally, if you’re really bored, try why. Why not?

1.3 Website

Source code for most of the examples and solutions to exercises in this book can be downloaded from

its website at www.bh.com/companions/essentialmatlab

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.

help and lookfor provide help.

plot draws an x-y graph in a figure window.

grid draws grid lines on a graph.

Exercise

Publicité

1.1 Give values to variables a and b on the command line, e....