MATLAB For Engineers - Pearson

Transcription

MATLAB for Engineers 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

MATLAB for EngineersThird EditionHOLLY MOORESalt Lake Community CollegeSalt Lake City, UtahBoston Columbus Indianapolis New YorkSan Francisco Upper Saddle River AmsterdamCape Town Dubai London Madrid MilanMunich Paris Montreal Toronto DelhiMexico City Sao Paulo Sydney Hong KongSeoul Singapore Taipei Tokyo 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Vice President and Editorial Director, Engineering/Computer Science: Marcia J. HortonExecutive Editor: Holly StarkEditorial Assistant: William OpaluchMarketing Manager: Tim GalliganProduction Manager: Pat BrownArt Director: Jayne ConteCover Designer: Bruce KenselaarMedia Editor: Daniel SandinFull-Service Project Management: Pavithra Jayapaul, TexTech InternationalComposition: TexTech InternationalPrinter/Binder: Edwards BrothersCover Printer: Lehigh-Phoenix Color/HagerstownCredits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriatepage within text.MATLAB and Simulink are registered trademarks of The Mathworks, Inc., 3 Apple Hill Drive, Natick MA 01760-2098.Copyright 2012 Pearson Education, Inc., publishing as Prentice Hall, One Lake Street, Upper Saddle River, New Jersey 07458.All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission shouldbe obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or byany means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, pleasesubmit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458.Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks. Where those designationsappear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.Library of Congress Cataloging–in–Publication DataMoore, Holly.MATLAB for engineers / Holly Moore. — 3rd ed.p. cm.Includes index.ISBN-13: 978-0-13-210325-1ISBN-10: 0-13-210325-71. Engineering mathematics—Data processing. 2. MATLAB . I. Title.TA345.M585 2011620.001'51—dc23201102273910 9 8 7 6 5 4 3 2 1ISBN 10: 0-13-210325-7ISBN 13: 978-0-13-210325-1 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

ContentsABOUT THIS BOOKDEDICATION AND ACKNOWLEDGMENTSXIXV1 ABOUT MATLAB 1.11.21.31.41What Is MATLAB ? 1Student Edition of MATLAB 2How Is MATLAB Used in Industry? 3Problem Solving in Engineering and Science52 MATLAB ENVIRONMENT2.1 Getting Started 92.2 MATLAB Windows 112.3 Solving Problems with MATLAB 2.4 Saving Your Work 42Summary 52MATLAB Summary 54Key Terms 55Problems 559183 BUILT-IN MATLAB FUNCTIONSIntroduction 633.1 Using Built-In Functions 633.2 Using the Help Feature 653.3 Elementary Math Functions 683.4 Trigonometric Functions 763.5 Data Analysis Functions 803.6 Random Numbers 1003.7 Complex Numbers 1043.8 Computational Limitations 1083.9 Special Values and Miscellaneous Functions63109v 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

viContents3.10 Summary 111MATLAB Summary 112Key Terms 113Problems 1144 MANIPULATING MATLAB MATRICES1214.1 Manipulating Matrices 1214.2 Problems with Two Variables 1284.3 Special Matrices 135Summary 141MATLAB Summary 142Key Terms 142Problems 1425 PLOTTING149Introduction 1495.1 Two-Dimensional Plots 1495.2 Subplots 1665.3 Other Types of Two-Dimensional Plots 1685.4 Three-Dimensional Plotting 1835.5 Editing Plots from the Menu Bar 1895.6 Creating Plots from the Workspace Window 1915.7 Saving Your Plots 192Summary 193MATLAB Summary 193Problems 1956 USER-DEFINED FUNCTIONS205Introduction 2056.1 Creating Function M-Files 2056.2 Creating Your Own Toolbox of Functions 2246.3 Anonymous Functions and Function Handles 2266.4 Function Functions 2276.5 Subfunctions 228Summary 231MATLAB Summary 232Key Terms 233Problems 2337 USER-CONTROLLED INPUT AND OUTPUTIntroduction 2407.1 User-Defined Input 2407.2 Output Options 2447.3 Graphical Input 254 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.240

Contents7.4 More Cell Mode Features 2557.5 Reading and Writing Data from Files7.6 Debugging Your Code 263Summary 266MATLAB Summary 267Key Terms 268Problems 2682608 LOGICAL FUNCTIONS AND SELECTION STRUCTURES273Introduction 2738.1 Relational and Logical Operators 2748.2 Flowcharts and Pseudocode 2768.3 Logical Functions 2778.4 Selection Structures 2848.5 Debugging 300Summary 301MATLAB Summary 301Key Terms 302Problems 3029 REPETITION STRUCTURESIntroduction 3119.1 For Loops 3129.2 While Loops 3209.3 Break and Continue 3289.4 Midpoint Break Loops 3299.5 Nested Loops 3339.6 Improving the Efficiency of LoopsSummary 336Key Terms 337Problems 33731133410 MATRIX ALGEBRA343Introduction 34310.1 Matrix Operations and Functions 34310.2 Solutions of Systems of Linear Equations10.3 Special Matrices 379Summary 381MATLAB Summary 383Key Terms 384Problems 38411 OTHER KINDS OF ARRAYSIntroduction 39111.1 Data Types 39211.2 Multidimensional Arrays363391401 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.vii

viiiContents11.3 Character Arrays 40311.4 Cell Arrays 40811.5 Structure Arrays 409Summary 417MATLAB Summary 417Key Terms 418Problems 41812 SYMBOLIC MATHEMATICSIntroduction 42412.1 Symbolic Algebra 42512.2 Solving Expressions and Equations 43512.3 Symbolic Plotting 44612.4 Calculus 45412.5 Differential Equations 46812.6 Converting Symbolic Expressions to MATLAB FunctionsSummary 471MATLAB Summary 473Problems 47442447013 NUMERICAL TECHNIQUES48413.1 Interpolation 48413.2 Curve Fitting 49413.3 Using the Interactive Fitting Tools 50513.4 Differences and Numerical Differentiation 51213.5 Numerical Integration 52013.6 Solving Differential Equations Numerically 526Summary 533MATLAB Summary 535Key Terms 536Problems 53614 ADVANCED GRAPHICSIntroduction 54514.1 Images 54514.2 Handle Graphics 56114.3 Animation 56514.4 Other Visualization Techniques 57114.5 Introduction to Volume Visualization 573Summary 576MATLAB Summary 577Key Terms 578Problems 579 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.545

Contents15 CREATING GRAPHICAL USER INTERFACES581Introduction 58115.1 A Simple GUI with One User Interaction 58215.2 A Graphical User Interface with Multiple UserInteractions—Ready Aim Fire 59015.3 An Improved Ready Aim Fire Program 59315.4 A Much Better Ready Aim Fire Program 59415.5 Built-In GUI Templates 598Summary 602Key Terms 602Problems 60216 SIMULINK —A BRIEF INTRODUCTION604Introduction 60416.1 Applications 60416.2 Getting Started 60516.3 Solving Differential Equations with Simulink 613Summary 618Key Terms 619Problems 619APPENDIX A SPECIAL CHARACTERS, COMMANDS, ANDFUNCTIONS623APPENDIX B SCALING TECHNIQUES638APPENDIX C THE READY AIM FIRE GUI641INDEX646 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.ix

2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

About This BookThis book grew out of my experience teaching MATLAB and other computinglanguages to freshmen engineering students at Salt Lake Community College.I was frustrated by the lack of a text that “started at the beginning.” Although therewere many comprehensive reference books, they assumed a level of both mathematical and computer sophistication that my students did not possess. Also, becauseMATLAB was originally adopted by practitioners in the fields of signal processingand electrical engineering, most of these texts provided examples primarily fromthose areas, an approach that didn’t fit with a general engineering curriculum.This text starts with basic algebra and shows how MATLAB can be used to solveengineering problems from a wide range of disciplines. The examples are drawnfrom concepts introduced in early chemistry and physics classes and freshman andsophomore engineering classes. A standard problem-solving methodology is usedconsistently.The text assumes that the student has a basic understanding of college algebraand has been introduced to trigonometric concepts; students who are mathematicallymore advanced generally progress through the material more rapidly. Although thetext is not intended to teach subjects such as statistics or matrix algebra, when theMATLAB techniques related to these subjects are introduced, a brief background isincluded. In addition, sections describing MATLAB techniques for solving problemsby means of calculus and differential equations are introduced near the end of appropriate chapters. These sections can be assigned for additional study to students with amore advanced mathematics background, or they may be useful as reference materialas students progress through an engineering curriculum.The book is intended to be a “hands-on” manual. My students have been mostsuccessful when they read the book while sitting beside a computer and typing in theexamples as they go. Numerous examples are embedded in the text, with more complicated numbered examples included in each chapter to reinforce the conceptsintroduced. Practice exercises are included in each chapter to give students animmediate opportunity to use their new skills, and complete solutions are availableonline at: www.pearsonhighered.com/moore.The material is grouped into three sections. The first, An Introduction to BasicMATLAB Skills, gets the student started and contains the following chapters: Chapter 1 shows how MATLAB is used in engineering and introduces a standard problem-solving methodology. Chapter 2 introduces the MATLAB environment and the skills required toperform basic computations. This chapter also introduces M-files, and the concept of organizing code into cells. Doing so early in the text makes it easier forstudents to save their work and develop a consistent programming strategy. Chapter 3 details the wide variety of problems that can be solved with built-inMATLAB functions. Background material on many of the functions is providedto help the student understand how they might be used. For example, the difference between Gaussian random numbers and uniform random numbers isdescribed, and examples of each are presented.xi 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

xiiAbout This Book Chapter 4 demonstrates the power of formulating problems by using matricesin MATLAB and expanding on the techniques employed to define thosematrices. The meshgrid function is introduced in this chapter and is used tosolve problems with two variables. The difficult concept of meshing variables isrevisited in Chapter 5 when surface plots are introduced. Chapter 5 describes the wide variety of both two-dimensional and threedimensional plotting techniques available in MATLAB . Creating plots viaMATLAB commands, either from the command window or from within anM-file, is emphasized. However, the extremely valuable techniques of interactively editing plots and creating plots directly from the workspace window arealso introduced.MATLAB is a powerful programming language that includes the basicconstructs common to most programming languages. Because it is a scriptinglanguage, creating programs and debugging them in MATLAB is often easierthan in traditional programming languages such as C . This makes MATLAB a valuable tool for introductory programming classes. The second section ofthe text, Programming in MATLAB , introduces students to programming andconsists of the following chapters: Chapter 6 describes how to create and use user-defined functions. This chapteralso teaches students how to create a “toolbox” of functions to use in their ownprogramming projects. Chapter 7 introduces functions that interact with the program user, includinguser-defined input, formatted output, and graphical input techniques. The useof MATLAB ’s debugging tools is also introduced. Chapter 8 describes logical functions such as find and demonstrates how theyvary from the if and if/else structures. The switch case structure is also introduced. The use of logical functions over control structures is emphasized,partly because students (and teachers) who have previous programmingexperience often overlook the advantages of using MATLAB ’s built-in matrix functionality. Chapter 9 introduces repetition structures, including for loops, while loops, andmidpoint break loops which utilize the break command. Numerous examplesare included because students find these concepts particularly challenging.Chapters 1 through 9 should be taught sequentially, but the chapters inSection 3, Advanced MATLAB Concepts, do not depend upon each other. Any orall of these chapters could be used in an introductory course or could serve as reference material for self-study. Most of the material is appropriate for freshmen. Atwo-credit course might include Chapters 1 through 9 plus Chapter 10, while athree-credit course might include Chapters 1 through 14, but eliminate Sections 12.4,12.5, 13.4, 13.5, and 13.6, which describe differentiation techniques, integrationtechniques, and solution techniques for differential equations. Chapters 15 and16 will be interesting to more advanced students, and might be included in acourse delivered to sophomore or junior students instead of to freshmen. Theskills developed in these will be especially useful as students become moreinvolved in solving engineering problems: Chapter 10 discusses problem solving with matrix algebra, including dot products, cross products, and the solution of linear systems of equations. Althoughmatrix algebra is widely used in all engineering fields, it finds early applicationin the statics and dynamics classes taken by most engineering majors. 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

About This Book xiii Chapter 11 is an introduction to the wide variety of data types available inMATLAB . This chapter is especially useful for electrical engineering and computer engineering students. Chapter 12 introduces MATLAB ’s symbolic mathematics package, built onthe MuPad engine. Students will find this material especially valuable in mathematics classes. My students tell me that the package is one of the most valuable sets of techniques introduced in the course. It is something they startusing immediately. Chapter 13 presents numerical techniques used in a wide variety of applications, especially curve fitting and statistics. Students value these techniqueswhen they take laboratory classes such as chemistry or physics or when they takethe labs associated with engineering classes such as heat transfer, fluid dynamics, or strengths of materials. Chapter 14 examines graphical techniques used to visualize data. These techniques are especially useful for analyzing the results of numerical analysis calculations, including results from structural analysis, fluid dynamics, and heattransfer codes. Chapter 15 introduces MATLAB ’s graphical user interface capability, using theGUIDE application. Creating their own GUI’s gives students insight into how thegraphical user interfaces they use daily on other computer platforms are created. Chapter 16 introduces Simulink , which is a simulation package built on top ofthe MATLAB platform. Simulink uses a graphical user interface that allowsprogrammers to build models of dynamic systems. Simulink has found significant acceptance in the field of Electrical Engineering but has wide applicationacross the engineering spectrum.Appendix A lists all of the functions and special symbols (or characters) introduced in the text. Appendix B describes strategies for scaling data, so that theresulting plots are linear. Appendix C includes the complete MATLAB code tocreate the Ready Aim Fire graphical user interface described in Chapter 15. Aninstructor web -site includes the following material: M-files containing solutions to practice exercisesM-files containing solutions to example problemsM-files containing solutions to homework problemsPowerPoint slides for each chapterAll of the figures used in the text, suitable for inclusion in your own PowerPointpresentations A series of lectures (including narration) suitable for use with online classes oras reviewsABOUT THE THIRD EDITIONNew versions of MATLAB are rolled out every 6 months, which makes keepingany text up-to-date a challenge. The major changes included in this edition are asfollows: All of the screen shots throughout the book were updated to reflect the 2011arelease. The introduction to cell mode was moved to Chapter 2 from Chapter 7. Thedescription of the cell mode publishing features was expanded and updated inChapter 7. 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

xivAbout This Book Information on debugging features was added to Chapters 7 and 8. Based on student and instructor feedback, Chapter 8 was significantly revisedand split into two chapters. The new Chapter 8 introduces MATLAB ’s logical functions such as find,and the more traditional selection structures if, if/else, and switch/case. The new Chapter 9 deals exclusively with repetition structures. The symbolic toolbox was changed significantly in the 2007b edition, whichrequired changes to the symbolic algebra materials in Chapter 12. Two additional chapters were added in an attempt to make the text useful to awider audience. Chapter 15 describes graphical user interfaces. Chapter 16 is an introduction to Simulink . Problems were added at the end of each chapter. Additional example problems were added. A number of new functions are introduced throughout the book, suggested tous by adopters of the text. 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Dedication andAcknowledgmentsThis project would not have been possible without the support of my family, whichendured reading multiple drafts of the text and ate a lot of frozen pizza while I concentrated on writing. Thanks to Mike, Heidi, Meagan, and David, and to my husband, Dr. Steven Purcell. I also benefited greatly from the suggestions for problemsrelated to electricity from Lee Brinton and Gene Riggs of the SLCC ElectricalEngineering Department. Their cheerful efforts to educate me on the mysteries ofelectricity are much appreciated. I’d also like to thank Dr. Ghassan Hamarneh forhis careful review of the second edition, which helped tremendously as I preparedthis latest manuscript.This book is dedicated to my father, Professor George Moore, who taught in theDepartment of Electrical Engineering at the South Dakota School of Mines andTechnology for almost 20 years. Professor Moore earned his college degree at the ageof 54 after a successful career as a pilot in the United States Air Force and was a livingreminder that you are never too old to learn. My mother, Jean Moore, encouragedboth him and her two daughters to explore outside the box. Her loving support madeit possible for both my sister and I to enjoy careers in engineering—something fewwomen attempted in the early 1970s. I hope that readers of this text will take a minuteto thank those people in their lives who’ve helped them make their dreams cometrue. Thanks Mom and Dad.xv 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

The fi rst, An Introduction to Basic MATLAB Skills, gets the student started and contains the following chapters: Chapter 1 shows how MATLAB is used in engineering and introduces a stand-ard problem-solving methodology. Chapter 2 introduces the MATLAB environment and the skills required to perform basic computations.