**Basics Of MATLAB And Beyond**

Basics Of MATLAB And Beyond

(Parte **1** de 3)

and Beyond c© 2000 by CRC Press LLC

CHAPMAN & HALL/CRC Andrew Knight and Beyond MATLAB

Boca Raton London New York Washington, D.C.

Library of Congress Cataloging-in-Publication Data

Knight, Andrew (Andrew James), 1961— Basics of MATLAB and beyond / Andrew Knight.

p. cm. Includes index. (alk. paper)

ISBNO-8493-2039-9

1. Engitteering mathematics-Data prccessing. 2. MATLAB.I. Title. TA345.K63 1999

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

Neither this book nor any part may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, microtihning, and recording, or by any information storage or retrieval system, without prior permission in writing from the publisher.

The consent of CRC Press LLC does not extend to copying for general distribution, for promotion, for creating new works, or for resale. Specific permission must be obtained in writing from CRC Press LLC for such copying.

Direct all inquiries to CRC Press LLC, 2000 N.W. Corporate Blvd., Boca Raton, Plorida 33431.

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

Visit tbe CRC Press Web site at w.crcpress.com

No claim to original U.S. Government works International Standard Bcok Number 0-8493-2039-9

Library of Congress Card Number 9-31210 Printed in the United States of America34561890

Printed on acid-free paper MATLAB is a registered trademark of The MathWorks, Inc.

Preface

This book arose from notes written for matlab© training courses run within the Australian Defence Science and Technology Organisation. The book is in two parts. Each part was originally a two-day course, designed assuming that students were seated at a computer with matlab running.

Part 1 is an introductory course suitable for those with no experience at all with matlab. It is written in a self contained way; if you go through the notes, all the new commands and ideas are explained as they are introduced.

Part 2 is a more advanced course suitable for those who are already familiar with the basics of matlab. It covers a variety of topics, some of which you may not be interested in; if so, you should be able to skip that section without detriment to other sections.

You can get the m-ﬁles that accompany this book from the “Download” section of the CRC Press web site (w.crcpress.com). The ﬁles are available in zip or gzipped tar format, and can be extracted using WinZip on a PC, or by using gunzip and tar on unix. You will need to put them in a directory where matlab will be able to ﬁnd them. You can either use the cd command to move matlab’s working directory to the directory you extract the ﬁles to, or add that directory to matlab’s search path. (You can display matlab’s current working directory by matlab is a registered trademark of The MathWorks, Inc. For product information, please contact:

The MathWorks, Inc. 24 Prime Park Way Natick, MA 01760-1500 USA

E-mail: info@mathworks.com Web: w.mathworks.com c© 2000 by CRC Press LLC typing pwd (print working directory) in the command window.) On a PC or Macintosh, you can add directories to matlab’s path by clicking on the path browser button at the top of the matlab command window (it is the button with two folders on it to the left of the question mark button). In the path browser, select the menu “Path→Add to path”, then select the directory containing the extracted ﬁles using the browse button (on PCs it is the one with three dots on it), then check the “add to back” option before pressing “OK”. Then click “File→Save Path” before you exit the path browser. If you are using another platform you can use the path command from within matlab (type help path for instructions). You can install this path each time you start matlab by putting an appropriate path command in a ﬁle called startup.m in a directory called matlab situated immediately below your home directory.

Many of the graphical examples in this book assume that the ﬁgure window is empty. To ensure an empty ﬁgure window issue the command:

clf which stands for “clear ﬁgure”. If you ﬁnd that the ﬁgure window is obscured by your command window, try shrinking both windows. Or you can type:

shg

(show graphic) to bring the graphics window to the front. The companion software implements an even shorter abbreviation; type to bring the graphics window to the front

If, on a PC or Macintosh, the ﬁgure window is at the front of the screen, or if it has the current focus, just start typing and matlab will switch to the command window and accept your typing.

Words appearing in this book in typewriter font, for example, type, represent matlab commands that you can type in, or output produced by matlab.

Andrew Knight c© 2000 by CRC Press LLC

About the Author

The author completed a Ph.D. in plasma physics at the Flinders University of South Australia in the days before matlab. Consequently, he knows how much time can be saved when you don’t have to write your own matrix inversion or polynomial evaluation routines in fortran. His ﬁrst exposure to matlab was at the Centre for Plasma Physics Research at the Swiss Federal Institute of Technology (Ecole Polytechnique Federale) in Lausanne, Switzerland, where he continued his research in plasma physics. On his return to Australia to take up a position with the Maritime Operations Division of the Defence Science and Technology Organisation, he was given responsibility for research in the ﬂow noise problem of towed sonar arrays. His current research interests include sonar signal processing and information displays. He has been largely responsible for the growth in the use of matlab in his division, and has conducted training courses in matlab.

c© 2000 by CRC Press LLC

Contents

I Basics of MATLAB

1 First Steps in MATLAB 1.1 Starting MATLAB 1.2 First Steps 1.3 Matrices 1.4 Variables 1.5 The Colon Operator 1.6 Linspace 1.7 Plotting Vectors

2 Typing into MATLAB 2.1 Command Line Editing 2.2 Smart Recall 2.3 Long Lines 2.4 Copying and Pasting

3 Matrices 3.1 Typing Matrices 3.2 Concatenating Matrices 3.3 Useful Matrix Generators 3.4 Subscripting 3.5 End as a subscript 3.6 Deleting Rows or Columns 3.7 Matrix Arithmetic 3.8 Transpose

4 Basic Graphics 4.1 Plotting Many Lines 4.2 Adding Plots 4.3 Plotting Matrices 4.4 Clearing the Figure Window 4.5 Subplots c© 2000 by CRC Press LLC

5 More Matrix Algebra 6 Basic Data Analysis

7 Graphics of Functions of Two Variables 7.1 Basic Plots 7.2 Colour Maps 7.3 Colour Bar 7.4 Good and Bad Colour Maps 7.5 Extracting Logical Domains 7.6 Nonrectangular Surface Domains

9 Data Files 9.1 MATLAB Format 9.2 ASCII Format 9.3 Other Formats

10 Directories 1 Startup 12 Using MATLAB on Diﬀerent Platforms 13 Log Scales 14 Curve Fitting—Matrix Division 15 Missing Data 16 Polar Plots 17 Fourier Transform 18 Power Spectrum 19 Sounds in MATLAB c© 2000 by CRC Press LLC

20 Time-Frequency Analysis 21 Line Animation 2 SPTool

23 Handle Graphics 23.1 Custom Plotting Functions 23.2 Set and Get 23.3 Graphical Object Hierarchy

I Beyond the Basics

25 Sparse Arrays 25.1 Example: Airfoil 25.2 Example: Communication Network

26 Text Strings 26.1 String Matrices 26.2 Comparing Strings 26.3 String Manipulations 26.4 Converting Numbers to Strings 26.5 Using Strings as Commands

27 Cell Arrays

28 Structures 28.1 Example: Meteorological Database 28.2 Example: Capturing the List of Variables

29 Multidimensional Arrays 29.1 Generating Multidimensional Grids 29.2 Operations with Multidimensional Arrays 29.3 RGB Images 29.4 Example: Sonar 29.5 Multidimensional Cell Arrays 29.6 Multidimensional Structures

30 Saving and Loading Data 30.1 MATLAB Format 30.2 Other Formats c© 2000 by CRC Press LLC

31 Handle Graphics 31.1 Get and Set 31.2 Default Object Properties 31.3 Current Objects

32 Axes Eﬀects 32.1 The Axis Command 32.2 Tick Marks and Labels 32.3 Subplots 32.4 Double Axes 32.5 Axes Labels

3 Text in Graphics 3.1 Symbols and Greek Letters 3.2 Symbols in Tick Labels 3.3 Global Object Placement

34 Graphical User Interfaces 34.1 Callbacks 34.2 UIControls 34.3 Exclusive Radio Buttons 34.4 Variables in GUIs 34.5 The Tag Property 34.6 UIMenus 34.7 Fast Drawing 34.8 Guide 34.9 Other Aids

35 Printing Graphics 35.1 Print Size: Orient 35.2 Print Size: WYSIWYG 35.3 Including Figures in Other Applications

36 Irregular Grids 36.1 Interpolation over a Rectangular Grid 36.2 Triangular Gridding

37 Three-dimensional Modelling 37.1 Patches 37.2 Light Objects

c© 2000 by CRC Press LLC

39 Answers to Exercises (Part I) 40 Answers to Exercises (Part I) c© 2000 by CRC Press LLC

Basics of MATLAB

1 First Steps in MATLAB

1.1 Starting MATLAB matlab is a software package that lets you do mathematics and computation, analyse data, develop algorithms, do simulation and modelling, and produce graphical displays and graphical user interfaces.

To run matlab on a PC double-click on the matlab icon. To run matlab on a unix system, type matlab at the prompt.

You get matlab to do things for you by typing in commands. matlab prompts you with two greater-than signs (>>) when it is ready to accept a command from you.

To end a matlab session type quit or exit at the matlab prompt. You can type help at the matlab prompt, or pull down the Help menu on a PC. When starting matlab you should see a message:

To get started, type one of these commands: helpwin, helpdesk, or demo >>

The various forms of help available are helpwin Opens a matlab help GUI helpdesk Opens a hypertext help browser demo Starts the matlab demonstration

The complete documentation for matlab can be accessed from the hypertext helpdesk. For example, clicking the link Full Documentation c© 2000 by CRC Press LLC

Set → Getting Started with MATLAB will download a portable document format (PDF) version of the Getting Started with MATLAB manual.

You can learn how to use any matlab command by typing help followed by the name of the command, for example, help sin.

You can also use the lookfor command, which searches the help entries for all matlab commands for a particular word. For example, if you want to know which matlab functions to use for spectral analysis, you could type lookfor spectrum. matlab responds with the names of the commands that have the searched word in the ﬁrst line of the help entry. You can search the entire help entry for all matlab commands by typing lookfor -all keyword.

1.2 First Steps To get matlab to work out 1 + 1, type the following at the prompt:

1+1 matlab responds with

The answer to the typed command is given the name ans. In fact ans is now a variable that you can use again. For example you can type

ans*ans ans = 4 matlab has updated the value of ans to be 4.

The spacing of operators in formulas does not matter. The following formulas both give the same answer:

The order of operations is made clearer to readers of your matlab code if you type carefully:

c© 2000 by CRC Press LLC

1.3 Matrices

The basic object that matlab deals with is a matrix. A matrix is an array of numbers. For example the following are matrices:

stands for 1 × 106—and the (3,2)-element is pi = π =3 .14159 |

The size of a matrix is the number of rows by the number of columns. The ﬁrst matrix is a 3×3 matrix. The (2,3)-element is one million—1e6 The second matrix is a row-vector, the third matrix is a column-vector containing the number i, which is a pre-deﬁned matlab variable equal to the square root of −1. The last matrix is a 1 × 1 matrix, also called a scalar.

Variables in matlab are named objects that are assigned using the equals sign = . They are limited to 31 characters and can contain upper and lowercase letters, any number of ‘_’ characters, and numerals. They may not start with a numeral. matlab is case sensitive: A and a are diﬀerent variables. The following are valid matlab variable assignments:

a=1 speed = 1500 BeamFormerOutput_Type1 = v*Q*v’ name = ’John Smith’

These are invalid assignments:

2for1 = ’yes’ first one = 1

To assign a variable without getting an echo from matlab end the assignment with a semi-colon ;. Try typing the following:

a=2 b=3 ; c = a+b; d = c/2; d who whos clear who c© 2000 by CRC Press LLC

1.5 The Colon Operator

To generate a vector of equally-spaced elements matlab provides the colon operator. Try the following commands:

The syntax x:y means roughly “generate the ordered set of numbers from x to y with increment 1 between them.” The syntax x:d:y means roughly “generate the ordered set of numbers from x to y with increment d between them.”

1.6 Linspace

To generate a vector of evenly spaced points between two end points, you can use the function linspace(start,stop,npoints):

generates 10 evenly spaced points from 0 to 1. Typing linspace(start, stop) will generate a vector of 100 points.

1.7 Plotting Vectors

Whereas other computer languages, such as Fortran, work on numbers one at a time, an advantage of matlab is that it handles the matrix as a single unit. Let us consider an example that shows why this is useful. Imagine you want to plot the function y = sinx for x between 0 and 2π. A Fortran code to do this might look like this:

DIMENSION X(100),Y(100) PI = 4*ATAN(1) DO 100 I = 1,100 X(I) = 2*PI*I/100 Y(I) = SIN(X(I)) 100 CONTINUE PLOT(X,Y)

Here we assume that we have access to a Fortran plotting package in which PLOT(X,Y) makes sense. In matlab we can get our plot by typing:

c© 2000 by CRC Press LLC

x = 0:.1:2*pi; y = sin(x); plot(x,y)

The ﬁrst line uses the colon operator to generate a vector x of numbers running between 0 and 2π with increment 0.1. The second line calculates the sine of this array of numbers, and calls the result y. The third line produces a plot of y against x. Go ahead and produce the plot. You should get a separate window displaying this plot. We have done in three lines of matlab what it took us seven lines to do using the Fortran program above.

2 Typing into MATLAB

2.1 Command Line Editing

If you make a mistake when entering a matlab command, you do not have to type the whole line again. The arrow keys can be used to save much typing:

↑ ctrl-p Recall previous line ↓ ctrl-n Recall next line ← ctrl-b Move back one character → ctrl-f Move forward one character ctrl-→ ctrl-r Move right one word ctrl-← ctrl-l Move left one word home ctrl-a Move to beginning of line end ctrl-e Move to end of line esc ctrl-u Clear line del ctrl-d Delete character at cursor backspace ctrl-h Delete character before cursor ctrl-k Delete (kill) to end of line

If you ﬁnish editing in the middle of a line, you do not have to put the cursor at the end of the line before pressing the return key; you can press return when the cursor is anywhere on the command line.

2.2 Smart Recall

(Parte **1** de 3)