Docsity

A Practical Introduction to programming ST, Notas de estudo de Cultura

Pré-visualização parcial do texto

Baixe A Practical Introduction to programming ST e outras Notas de estudo em PDF para Cultura, somente na Docsity!

Matlab:

a Practical Introduction to

Programming and Problem Solving

This page intentionally left blank

Butterworth-Heinemann is an imprint of Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, USA Linacre House, Jordan Hill, Oxford OX2 8DP, UK

Copyright (^) © 2009, Elsevier, Inc. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopy, recording, or any information storage and retrieval system, without permission in writing from the publisher.

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

Library of Congress Cataloging-in-Publication Data Application submitted

British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library.

ISBN: 978-0-75-068762-

For information on all Butterworth-Heinemann publications visit our Web site at www.elsevierdirect.com

Printed in Canada 08 09 10 9 8 7 6 5 4 3 2 1

Attribution MATLAB®^ and Handle Graphics®^ are registered trademarks of The MathWorks, Inc.

This page intentionally left blank

vii

Preface .................................................................................................. xiii

  • Using MATLAB Part I Programming and Problem Solving
  • ChAPTer 1 Introduction to MaTLaB
    • 1.1 Getting into MaTLaB
    • 1.2 Variables and assignment Statements
      • 1.2.1 Initializing, Incrementing, and Decrementing............
      • 1.2.2 Variable Names
    • 1.3 expressions
      • 1.3.1 The Format function and ellipsis
      • 1.3.2 Operators
      • 1.3.3 Built-In functions and Help
      • 1.3.4 constants
      • 1.3.5 Types............................................................................
      • 1.3.6 random Numbers
    • 1.4 characters and encoding
    • 1.5 Vectors and Matrices
      • 1.5.1 creating row Vectors
      • 1.5.2 creating column Vectors
      • 1.5.3 creating Matrix Variables
      • 1.5.4 Dimensions
      • 1.5.5 Using functions with Vectors and Matrices.............
      • 1.5.6 empty Vectors
  • ChAPTer 2 Introduction to MaTLaB Programming
    • 2.1 algorithms
    • 2.2 MaTLaB Scripts
      • 2.2.1 Documentation
    • 2.3 Input and Output
      • 2.3.1 Input function viii Contents
      • 2.3.2 Output Statements: disp and fprintf
    • 2.4 Scripts with Input and Output
    • 2.5 Scripts to Produce and customize Simple Plots
      • 2.5.1 The Plot function
      • 2.5.2 Simple related Plot functions
    • 2.6 Introduction to file Input/Output ( Load and Save )
      • 2.6.1 Writing Data to a file..................................................
      • 2.6.2 appending Data to a Data file
      • 2.6.3 reading from a file
    • 2.7 User-Defined functions that return a Single Value..........
      • 2.7.1 function Definitions
      • 2.7.2 calling a function
        • Script 2.7.3 calling a User-Defined function from a
      • 2.7.4 Passing Multiple arguments
      • 2.7.5 functions with Local Variables..................................
  • ChAPTer 3 Selection Statements
    • 3.1 relational expressions
    • 3.2 The if Statement...................................................................
      • 3.2.1 representing Logical True and false........................
    • 3.3 The if-else Statement
    • 3.4 Nested if-else Statements
    • 3.5 The Switch Statement
    • 3.6 The Menu function
    • 3.7 The is functions in MaTLaB..............................................
  • ChAPTer 4 Looping
    • 4.1 The for Loop
      • 4.1.1 finding Sums and Products
      • 4.1.2 combining for Loops with if Statements
        • Variable in the action 4.1.3 for Loops that Do Not Use the Iterator
      • 4.1.4 Input in a for Loop
    • 4.2 Nested for Loops
      • 4.2.1 Nested Loops and Matrices
        • Statements 4.2.2 combining Nested for Loops and if
    • 4.3 Vectorizing
      • 4.3.1 Logical Vectors
      • 4.3.2 Vectors and Matrices as function arguments.............
    • 4.4 While Loops........................................................................ Contents ix
      • 4.4.1 Multiple conditions in a While Loop
      • 4.4.2 reading from a file in a While Loop
      • 4.4.3 Input in a While Loop
      • 4.4.4 counting in a While Loop
      • 4.4.5 error-checking User Input in a While Loop
  • ChAPTer 5 MaTLaB Programs
    • 5.1 More Types of User-Defined functions - One Value 5.1.1 functions that return More than - Without returning Values 5.1.2 functions that accomplish a Task - Printing 5.1.3 functions that return Values Versus
      • 5.1.4 Passing arguments to functions
    • 5.2 MaTLaB Program Organization
      • 5.2.1 Modular Programs.....................................................
      • 5.2.2 Subfunctions
    • 5.3 application: Menu-Driven Modular Program
    • 5.4 Variable Scope
      • 5.4.1 Persistent Variables
    • 5.5 Debugging Techniques
      • 5.5.1 Types of errors
      • 5.5.2 Tracing
      • 5.5.3 editor/Debugger........................................................
      • 5.5.4 function Stubs
  • ChAPTer 6 String Manipulation
    • 6.1 creating String Variables
      • 6.1.1 Strings as Vectors
    • 6.2 Operations on Strings
      • 6.2.1 concatenation
      • 6.2.2 creating customized Strings
      • 6.2.3 removing Whitespace characters
      • 6.2.4 changing case
      • 6.2.5 comparing Strings
        • Strings 6.2.6 finding, replacing, and Separating
      • 6.2.7 evaluating a String
    • 6.3 The is function for Strings
    • 6.4 converting between String and Number Types
  • ChAPTer 7 Data Structures: cell arrays and Structures x Contents
    • 7.1 cell arrays
      • 7.1.1 creating cell arrays
    • 7.2 Structures - Variables 7.2.1 creating and Modifying Structure
      • 7.2.2 Passing Structures to functions
      • 7.2.3 related Structure functions.....................................
      • 7.2.4 Vectors of Structures.................................................
      • 7.2.5 Nested Structures
      • 7.2.6 Vectors of Nested Structures
  • ChAPTer 8 advanced file Input and Output
    • 8.1 Lower Level file I/O functions.........................................
      • 8.1.1 Opening and closing a file
      • 8.1.2 reading from files
      • 8.1.3 Writing to files
      • 8.1.4 appending to files....................................................
    • 8.2 Writing and reading Spreadsheet files...........................
    • 8.3 Using MaT-files for Variables
      • 8.3.1 Writing Variables to a file
      • 8.3.2 appending Variables to a MaT-file
      • 8.3.3 reading from a MaT-file..........................................
  • ChAPTer 9 advanced functions
    • 9.1 anonymous functions
    • 9.2 Uses of function Handles..................................................
      • 9.2.1 function functions
    • 9.3 Variable Numbers of arguments
      • 9.3.1 Variable Number of Input arguments
      • 9.3.2 Variable Number of Output arguments
    • 9.4 Nested functions
    • 9.5 recursive functions...........................................................
  • Part II Applications
  • ChAPTer 10 MaTLaB Plots
    • 10.1 Plot functions................................................................... - 10.1.1 Matrix of Plots - 10.1.2 Plot Types
    • 10.2 animation
    • 10.3 Three-Dimensional Plots
    • 10.4 customizing Plots
    • 10.5 Graphics Properties Contents xi
    • 10.6 Plot applications
      • 10.6.1 Plotting from a function
      • 10.6.2 Plotting file Data
  • ChAPTer 11 Solving Systems of Linear algebraic equations
    • 11.1 Matrix Definitions
      • 11.1.1 Matrix Properties...................................................
      • 11.1.2 Square Matrices.....................................................
      • 11.1.3 Matrix Operations
      • 11.1.4 Matrix Multiplication
      • 11.1.5 Vector Operations
      • algebraic equations 11.2 Matrix Solutions to Systems of Linear
      • 11.2.1 Solving 2 ´ 2 Systems of equations
      • 11.2.2 Gauss, Gauss-Jordan elimination
      • 11.2.3 reduced row echelon form
        • an augmented Matrix........................................... 11.2.4 finding a Matrix Inverse by reducing
    • 11.3 Symbolic Mathematics.....................................................
      • 11.3.1 Symbolic Variables and expressions
      • 11.3.2 Simplification functions
      • 11.3.3 Displaying expressions
      • 11.3.4 Solving equations..................................................
  • ChAPTer 12 Basic Statistics, Searching, and Sorting
    • 12.1 Statistical functions
      • 12.1.1 Mean.......................................................................
      • 12.1.2 Variance and Standard Deviation
      • 12.1.3 Mode.......................................................................
      • 12.1.4 Median
    • 12.2 Set Operations
    • 12.3 Sorting
      • 12.3.1 Sorting Vectors of Structures
      • 12.3.2 Sorting Strings
    • 12.4 Indexing
      • 12.4.1 Indexing into Vectors of Structures
    • 12.5 Searching
      • 12.5.1 Sequential Search
      • 12.5.2 Binary Search
  • ChAPTer 13 Sights and Sounds
    • 13.1 Sound files
    • 13.2 Introduction to Handle Graphics xii Contents
      • 13.2.1 Graphics Objects and Their Properties
    • 13.3 Image Processing
    • 13.4 Introduction to Graphical User Interfaces
  • ChAPTer 14 advanced Mathematics
    • 14.1 fitting curves to Data
      • 14.1.1 Polynomials
      • 14.1.2 curve fitting..........................................................
      • 14.1.3 Interpolation and extrapolation
      • 14.1.4 Least Squares
    • 14.2 complex Numbers
      • 14.2.1 equality for complex Numbers
      • 14.2.2 adding and Subtracting complex Numbers
      • 14.2.3 Multiplying complex Numbers
      • 14.2.4 complex conjugate and absolute Value
        • Polynomials 14.2.5 complex equations represented as
      • 14.2.6 Polar form
      • 14.2.7 Plotting
    • 14.3 calculus: Integration and Differentiation
      • 14.3.1 Trapezoidal rule....................................................
      • 14.3.2 Differentiation........................................................
      • 14.3.3 calculus in Symbolic Math Toolbox
  • Index

xiii

Motivation

The purpose of this book is to teach basic programming concepts and skills

needed for basic problem solving, all using MATLAB® as the vehicle. MATLAB

is a powerful software package that has built-in functions to accomplish a

diverse range of tasks, from mathematical operations to three-dimensional

imaging. Additionally, MATLAB has a complete set of programming constructs

that allows users to customize programs to their own specifications.

There are many books that introduce MATLAB. There are two basic flavors

of these books: those that demonstrate the use of the built-in functions in

MATLAB, with a chapter or two on some programming concepts, and those that

cover only the programming constructs without mentioning many of the built-

in functions that make MATLAB efficient to use. Someone who learns just the

built-in functions will be well-prepared to use MATLAB, but would not under-

stand basic programming concepts. That person then would not be able to learn

a language such as C++ or Java without taking another introductory course, or

reading another book, on the programming concepts. Conversely, anyone who

learns only programming concepts first (using any language) would tend to

write highly inefficient code using control statements to solve problems, not

realizing that in many cases these are not necessary in MATLAB.

This book instead takes a hybrid approach, introducing both the programming

and the efficient uses. The challenge for students is that it is nearly impossi-

ble to predict whether they will in fact need to know programming concepts

later on or whether a software package such as MATLAB will suffice for their

careers. Therefore, the best approach for beginning students is to give them

both—the programming concepts and the efficient built-in functions. Since

MATLAB is very easy to use, it is a perfect platform for this approach to teaching

programming and problem solving.

Since programming concepts are critically important to this book, emphasis

is not placed on the time-saving features that evolve with every new MATLAB

release. For example, in current versions of MATLAB statistics on variables are

Preface

Preface xv

the easiest type of functions to understand, those that calculate and return one

single value, are demonstrated in Chapter 2. Later, functions that return no

values and functions that return multiple values are introduced in Chapter 5.

Finally, advanced function features are shown in Chapter 9.

advanced Programming Concepts

In addition to the basics, some advanced programming concepts such as string

manipulation, data structures, recursion, anonymous functions, and variable

number of arguments to functions are covered. Sorting, searching, and index-

ing are also addressed. All these are again approached systematically; for exam-

ple, cell arrays are covered before they are used in file input functions and as

labels on pie charts.

Problem-solving tools

In addition to the programming concepts, some basic mathematics necessary

for solving many problems will be introduced. These will include statistical

functions, solving sets of linear algebraic equations, and fitting curves to data.

The use of complex numbers and some calculus (integration and differentia-

tion) will also be introduced. The basic math will be explained and the built-in

functions in MATLAB to perform these tasks will be described.

Plots, imaging, and Guis

Simple two-dimensional plots are introduced very early in the book (Chapter

2) so that plot examples can be used throughout. Chapter 10 shows more plot

types, and demonstrates customizing plots and how the graphics properties

are handled in MATLAB. This chapter makes use of strings and cell arrays to

customize labels. Also, there is an introduction to image processing and the

basics necessary to understand programming Graphical User Interfaces (GUIs)

in Chapter 13.

Layout oF text

This text is divided into two parts: Part I covers the programming constructs

and demonstrates the programming versus efficient use of built-in functions

to solve problems. Part II covers some applications, including plotting, image

processing, and mathematics needed in basic problem solving. The first four

chapters cover the very basics in MATLAB and in programming, and are all

prerequisites for the rest of the book. After that, many chapters in the applica-

tions section can be introduced when desired, to produce a customized flow of

topics in the book. This is true to an extent, although the order of the chapters

has been chosen carefully to ensure that the coverage is systematic.

xvi PrefacePreface

Part i: ProGraMMinG anD ProBLeM soLvinG usinG MatLaB

Chapter 1: Introduction to MATLAB covers expressions, operators, characters,

variables, and assignment statements. Scalars, vectors, and matrices are

introduced, as are many built-in functions that manipulate them.

Chapter 2: Introduction to MATLAB Programming introduces the idea of

algorithms and scripts. This includes simple input and output, and comment-

ing. Scripts are then used to create and customize simple plots, and to do file

input and output. Finally, the concept of a user-defined function is introduced

with just the type of function that calculates and returns a single value.

Chapter 3: Selection Statements introduces relational expressions and their

use in if statements, with else and elseif clauses. The switch statement

also is demonstrated, as is the concept of choosing from a menu. Also,

functions that return logical true or false are introduced.

Chapter 4: Looping introduces the concepts of counted and conditional

loops. Many common applications such as summing, counting, and

error-checking are covered. Nested loops and combining loops and selec-

tion statements are systematically introduced. In this chapter, the idea of

vectorizing code is introduced, which essentially means rewriting code that

uses loops to more efficiently make use of built-in functions, and the fact

that operations can be done on vectors and matrices in MATLAB.

Concepts explained in the first four chapters are assumed throughout the rest

of the book.

Chapter 5: MATLAB Programs covers more on scripts and user-defined

functions. User-defined functions that return more than one value as

well as those that do not return anything are introduced. The concept

of a program in MATLAB that consists of a script that calls user-defined

functions is demonstrated with examples. A longer menu-driven program

is shown as a reference, but could be omitted. Subfunctions and scope of

variables are also introduced, as are some debugging techniques.

The concept of a program is used throughout the rest of the book.

Chapter 6: String Manipulation covers many built-in string manipulation

functions as well as converting between string and number types. Several

examples include using custom strings in plot labels and input prompts.

Chapter 7: Data Structures introduces two main data structures: cell arrays

and structures. Once basic structures are covered, more complicated data

structures such as nested structures and vectors of structures also are

introduced. Cell arrays are used in several applications in later chapters,

xviii PrefacePreface

Chapter 13: Sights and Sounds builds on some handle graphics material

from Chapter 10. It also briefly discusses sound files, and introduces image

processing. An introduction to programming GUIs is also given. Nested

functions are used in the GUI examples. A patch function example uses a

structure.

Chapter 14: Advanced Mathematics covers three basic topics: curve fitting,

complex numbers, and integration and differentiation in calculus.

Symbolic expressions are used in several sections in this chapter.

PeDaGoGiCaL Features

There are several pedagogical tools that are used throughout this book that are

intended to make it easier to learn.

First, the book takes a conversational tone with sections called “Quick

Question!” These are designed to stimulate thought about the material that

has just been covered. The question is posed, and then the answer is given.

It will be most beneficial if you think about the question before reading the

answer! In any case, they should not be skipped over because the answers often

contain very useful information.

“Practice!” problems are given throughout the chapters. These are very simple

problems that drill the material just covered.

When some problems are introduced, they are solved using both “The

Programming Concept” and “The Efficient Method.” This facilitates under-

standing the efficient ways of using MATLAB, and also the programming

concepts used in these efficient functions and operators.

The End of Chapter Summary contains, where applicable, several sections:

■ ■ Common Pitfalls : A list of common mistakes that are made, and how

to avoid them.

■ ■ Programming Style Guidelines : In order to encourage “good”

programs, which others can actually understand, the programming

chapters will have guidelines that will make programs easier to read and

understand and therefore easier to work with and to modify.

■ ■ Key Terms : A list of the key terms covered in the chapter, in sequence.

■ ■ MATLAB Functions and Commands : A list of the MATLAB built-in

functions and commands covered in the chapter, in the order covered.

Throughout the text, these are given in bold type.

■ ■ MATLAB Operators : A list of the MATLAB operators covered in the

chapter, in the order covered.

■ ■ Exercises : A comprehensive set of exercises, ranging from the rote to

more engaging applications.

Preface xix

aDDitionaL BooK resourCes

A companion web site with additional teaching resources is available for fac-

ulty using this book as a text for their course(s). Please visit www.textbooks.

elsevier.com/978075068762 1 to register for access to:

■■ Instructor solutions manual for end-of-chapter problems

■■ Electronic figures from the text for creation of lecture slides

■■ Downloadable M-files for all examples in the text

Other book-related resources will also be posted there from time to time.

aCKnowLeDGMents

I am indebted to many, many family members, colleagues, mentors, and

students.

Throughout the last 22 years of coordinating and teaching the basic computa-

tion courses for the College of Engineering at Boston University, I have been

blessed with many fabulous students as well as graduate teaching fellows and

undergraduate teaching assistants (TAs). There have been hundreds of TAs over

the years, too many to name individually, but I thank them all for their support.

In particular the following TAs have been very helpful in the last year reviewing

drafts of this text and suggesting examples: Edy Tan, Megan Smith, Brandon

Phillips, Carly Sherwood, Ashmita Randhawa, Mike Green, Kevin Ryan, and

Brian Hsu. Kevin Ryan created the script to produce the cover illustration.

A number of colleagues have been very encouraging throughout the years. In

particular, I would like to thank Tom Bifano for his support and for his GUI

example suggestions.

I would like to thank all the reviewers of the proposal and drafts of this book.

Their comments have been extremely helpful and I hope I have incorporated

their suggestions to their satisfaction. They include Mark Cawood, Clemson

University; Dieter Schmidt, University of Cincinnati; Matthew Verleger,

Purdue University; Peter Orono, Indiana University–Purdue University

Indianapolis; James Kang, California State Polytechnic University–Pomona;

David Rockstraw, New Mexico State University; and James Holloway,

University of Michigan.

Also, I thank those at Elsevier who helped to make this book possible including

Tim Pitts, Joseph Hayton, Publisher; Maria Alonso, Assistant Editor; Christie

Jozwiak, Production Manager; and Eric Decicco, Cover Designer/Illustrator.

Finally, thanks go to all my family. My parents encouraged me at an early age

to read and to write. Thanks also to my husband Ted de Winter of Boston