100% found this document useful (2 votes)
673 views779 pages

Advanced Mathematics With MATLAB-Thomas L.

Good Reference for Engineers

Uploaded by

adventure115
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (2 votes)
673 views779 pages

Advanced Mathematics With MATLAB-Thomas L.

Good Reference for Engineers

Uploaded by

adventure115
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 779
Advanced Engineering Mathematics with MATLAB SECOND EDITION Thomas L. Harman University of Houston/Clear Lake James B. Dabney Intermetrics Norman J. Richert Mathematical Reviews PB Brooks/Cole Thomson Thomson Learning. Australia * Canada * Mexico « Singapore » Spain « United Kingdom « United States een Production Service Greg Hubit Hookworks x Heather Woods Cover Design Laurte Albrecht Christina DeVeto and Print Buyer Jessica Reed a Typesetting ATLIS Graphics & Design it Shelley Gesrcks Printing and Binding R R Donnelley 1 Mary Veztlich Crawfordsville 2000 by Brooks/Cole jomson Learning learning logo is a trademark used herein under hcense i ation, contact Ie Road "A 93950 USA. com, : fed No pat of this work may be reproduced, transcnbed or used 1n any form or by any means—graphne, Shantcal, including photocopying, recording, taping, Web distribution, or information storage and/or s-without the prior written permission of the publisher to use material from this work, contact us by msonrights com 2218, bo-zaa Hered trademark of Waterloo Maple Software, Inc be obtamed from. forks, Inc Drive 21760 647-7000 Fax (508) 647-7001 bmathworks com . ‘mathworks com pes trademark of The MathWorks, Inc Further information about MATLAB and related y io States of America 4g 21 ongress Cataloging-in-Publication Data as L. Jongineering mathematics with MATLAB / Thomes L Harman, James ichert —2nd ed jographical references 7164-7 1g mathematics~Data processing 2 MATLAB. I. Dabney, James. forman, 2000 pean 99-046374 Contents 1 Introduction re 1.2 13 14 15 16 17 18 a1 22 as 24 Introduction to MATLAB MATLAB Commands for Display and Plotting Creating MATLAB Programs MATLAB Programming Languoge Problem Solwng and Programming (Optional) Reinforcement Exercises and Exploration Problems Annotated Bibography Answers Numbers and Vectors Properties of Real Numbers MATLAB Computer Numbers (Optional) Complex Numbers Vectors in Two Dimensions and Three Dimenstons 15 22 25 31 38 43 43 45 46 49 54 60 25 26 a7 28 29 210 ait 212 213 Vectors in. Higher Dimenstons MATLAB Vectors Propertees of Vectors Complex Vectors Vector Spaces Vector Spaces of Functions Reinforcement Exerctses and Exploration Problems Annotated Bibliography Answers Matrices 31 32 33 34 35 3.6 37 388 39 3.10 3.11 Basic Properties of Matrices MATLAB Matrix Operations Square and Symmetric Matrices Determinants and Matrix Inverses Orthogonal and Triangular Matrices Systems of Linear Equations MATLAB Matrix Functions Linear Transformations Reinforcement Exercises and Exploration Problems Annotated Bibliography Answers Eigenvalues and Eigenvectors 4 42 General Discussion of Exgenvalues Engenvalues and Ergenvectors 70 uW 1% 7 wb 88 93 98 99 101 102 107 109 11g 119 124 131 139 uq 154 154 157 158 162 = Contents 43° Matrax Exgenvalue Theorems 44 Complex Vectors and Matrices 45 MATLAB Commands for Engenvectors 4.6 Matrix Calculus 4.7 Swmilar and Diagonalizable Matrices 4.8 Special Matrices and Ther Exgenvalues (Optional) 4.9 Applications to Differential Equations 410 Reinforcement Exercises and Exploration Problems 4.11 Annotated Brblography 4.12 Answers Linear Differential Equations 5.1 Classification of Differential Equations 52 Linear Differential Equations 5.8 Higher-Order Differentral Equations 5.4 Second-Order Differential Equations 5.5 Partscular Solutions of Differential Equations 5.6 Systems of Differential Equations 5.7 MATLAB Solutions of Systems of Differential Equations 5.8 Homogeneous Systems unth Repeated Exgenvalues 5.9 Nonhomogeneous Systems of Differential Equations 5.10 Transforming Differential Equations 5.11 Reiforcement Exercises and Exploration Problems 5.12 Annotated Bibhography 5.13 Answers 1% 1% 1% 18° 19 19, 19 20, 201 203 208 208 21e 226 22 23% Contents = 6 Advanced Differential Equations 275 6.1 Functions and Differential Equations 276 6.2 Sequences and Serres 282 68 Taylor Seres 292 64 Numerical Methods for Differential Equations 297 65 Stff Differential Equations 309 6.6 Vector Equations 311 67 Boundary- Value Problems 317 68 Equations with Variable Coefficsents 322 6.9 Bessel and Legendre Equations 329 6.10 Retforcement Exercises and Exploration Problems 340 6.11 Annotated Bibhography 946 6.12 Answers 347 7 Approximation of Functions 349 %1 — Polynomual Interpolation 351 72 Interpolation by Spline Functions 954 73° Least-Squares Curve Fitting 956 74 Orthogonal Functions 861 7.5 Rewmforcement Exercises and Exploration Problems 366 7.6 Annotated Bubhography 368 77° Answers 369 8 Fourier Analysis 371 8&1 Fourver Serres S72 8&2 Properties of Fourrer Serres 391 = Contents 83 Fourter Transforms 39 8&4 Reinforcement Exercises and Exploration Problems 40 85 Annotated Bibliography At 86 Answers Mt 9 Laplace Transforms 41' 9.1 —Definstron and Properties of the Laplace Transform 4 92 Computation of Inverse Laplace Transforms 42 98 MATLAB and Laplace Transforms 43 94 Applications to Differential Equations 43 9.5 Application of Laplace Transforms to Linear Systems Mh 9.6 Relatronship of Fourrer and Laplace Transforms 45 9.% Summary of Laplace Transform Properties 45. 9.8 Reinforcement Exercises and Exploration Problems 45. 9.9 Annotated Bublography 45. 9.10 Answers 461 10 Discrete Systems 46: 10.1 Introduction to the Sequences and Discrete Functions 46. 10.2 Linear Difference Equations 461 10.3 Apprommation to Differential Equations 4M 10.4 Smoothing and Digital Filters 4% 10.5 Introduction to Z-transforms 48 10.6 MATLAB Commands for Discrete Systems 48. 10.7 Z-transform Solutron of Difference Equations 48t 10.8 Applications of Z-transforms to Linear Discrete Systems 491 Contents wi 10.9 Z-transforms and Frequency Response 4 10.10 Sutnmary of Z-transform Properties 4 10.11 Reinforcement Exercises and Exploration Problems 4 10.12 Annotated Bibliography 10.13 Answers 11 The Discrete Fourier Transform and the FFT 5 11.1 Frequency Analysis of Signals 5 11.2 Discrete and Fast Fourrer Transforms 5 11.3 MATLAB Fourier Commands 5 11.4 Practical Signal Analysts 5 11.5 Practical Signal Sampling and DFT Errors 5 11.6 Analysis of DFT for Computation (Optional) 5 11.7 Resforcement Exercises and Exploration Problems 5 11.8 Annotated Bibliography 5 11.9 Answers 5 12 Advanced Calculus Be 121 Functions of Several Variables be 122 Derwatives of a Multwarate Function be 123 Differentials and Linear Approximation bt 124 Two-Dimensional Taylor Serres ot 125 MATLAB Two-Dimenswonal Interpolation ot 12.6 MATLAB Differentiation aX 12.7 Extrema of Real- Valued Functions aX = Conten 13 14 128 Constrained Extrema and Lagrange Multaphers 12.9 Vector Functions and Curvilnear Coordinates 12.10 Reinforcement Exercises and Exploration Problems 12.11 Annotated Bibliography 12.12 Answers Vector Differential Operators 18.1 Vector and Scalar Fields 13.2 MATLAB Commands for Vector Differential Calculus 18.3 Directional Derwatives and the Gradient 184 The Divergence 13.5 The Curl 186 The Laplacian and Laplace’s Equation 13.7 Vector Field Theory 13.8 Phystcal Application and Interpretation 13.9 Curvilinear Coordinates 18.10 Reinforcement Exercises and Exploration Problems 13.11 Annotated Bibhography 13.12 Answers Vector Integral Calculus 14.1 Integration 14.2 Applications of Single Integrals 14.8 Double and Triple Integrals 14.4 Change of Variables in Double Integrals 145. Change of Variables in Trple Integrals 58 58. 59. 59. 59. 60: 60. 61. 61 61s 62. 62 62 68. 63 63 63E 641 Contents = 15 14.6 Applications of Multaple Integrals 14.7 MATLAB Commands for Integration 14.8 Lane Integrals 14.9. Surface Integrals 14.10 Theorems of Vector Integral Calculus 14.11 Apphcations of Vector Field Theory 14.12 Remnforcement Exeresses and Exploration Problems 14.18 Annotated Bibhography 14.14 Answers Partial Differential Equations 15.1 Introduction to Partial Differential Equations 15.2 Laplace’s Equation 15.8 The Heat Equation 15.4 The Wave Equation 15.5 Resforcement Exercises and Exploration Problems 15.6 Annotated Btbhography 15.7 Answers Index Index of MATLAB Commands 663 667 670 677 680 689 702 709 110 715 716 720 792 783 739 48 48 745 749 | Contents Preface This textbook presents mathematical techniques for applications in engi- neering, physics, and applied mathematics. The major topics are vector and matrix algebra, differential equations, Fourier and Laplace analysis, discrete systems and discrete Fourier transforms, advanced calculus, and partial differential equations. Our approach is to integrate analytical and computer solutions of problems that lead to better understanding of ad- vanced mathematical techniques. An important feature of the text is that there are many examples showing applications of mathematical principles using numerical and symbolic computer solutions. The following sections describe the organization of the book and the files available on our Web site, listed in Section 0.3. Since the approach taken in this book represents a change from the traditional presentation of technical mathematics, two additional sections are included: “To Stu- dents and Professionals” explains the use of the text for self study; “To Instructors” is also provided to help instructors use the book successfully as a course text at a technical school or university. We have chosen MATLAB as a programming language because it is widely used both in industry and education and it is especially popular in the engineering and applied mathematics communities. The basic MAT- LAB program performs a wide variety of numerical calculations and has an excellent graphics capability that is exploited in many examples in this text. Symbolic operations are possible with MATLAB’s Symbolic Math Toolbox, which is based on Maple symbolic computation software. The Brooks/Cole Web site includes MATLAB scripts (programs) for examples and solutions to selected problems as well as Maple scripts. Each chapter includes two sets of problems. One set is called Rein- forcement Exercises, and answers to selected of these exercises are given at the end of a chapter. The problems in the second set, called Explo- ration Problems, are generally more difficult, and they are intended to extend the knowledge presented in the chapters. Prerequisites are a background in calculus and basic physics. Linear algebra would be useful, but it is not necessary since the important vector and matrix operations are developed in the book. Although expertise in programming is not required, some programming experience in a high- level language is assumed. In any case, MATLAB is straightforward to learn and use as a programming language. BOOK ORGANIZATION © Chapter 1 introduces MATLAB and describes many of its capabilities. ‘Those readers familiar with MATLAB can cover this chapter very quickly, Chapter 2 discusses numbers and vectors, including real and complex numbers, as well as computer numbers. Vector spaces are also introduced. Chapter 3 treats matrices, matrix operations, and linear transformations. Eigenvalues and eigenvectors are the subjects of Chapter 4. Chapters 5 and 6 discuss differential equations. Chapter 5 is primar- ily concerned with linear differential equations with constant coefficients. Chapter 6 explains more advanced differential equations such as stiff equa- tions and those with variable coefficients, including Bessel’s and Legen- dre’s equations. e Chapter 7 presents various techniques to approximate functions and covers interpolation by polynomials, splines, and least-squares curve fit- ting. Chapter 8 introduces Fourier series and Fourier transforms. Chapter 9 presents the Laplace transform and its applications. Chapter 10 introduces discrete systems, difference equations, and Z- transform techniques. Chapter 11 uses the discrete Fourier transform (DFT) and the fast Fourier transform (FFT) algorithm to compute Fourier transforms. The chapter also describes the errors involved in practical sig- nal sampling. « Chapter 12 begins the study of the calculus of multivariate functions and vector functions. The topics are typically included in an applied advanced calculus course. Chapter 13 presents the vector differential operators of gradient, di- vergence, curl, and Laplacian. Chapter 14 covers the integral calculus mt Preface of multiple integrals, line integrals, and surface integrals and presents various applications of vector field theory. ¢ Chapter 15 introduces selected partial differential equations. Laplace's equation, the heat equation, and the wave equation are studied. e The index includes a listing of the MATLAB commands used in the book, CHAPTER ORGANIZATION Each chapter contains a preview, text, numerous examples, exercises and problems, a bibliography, and answers to selected Reinforcement Exer- cises, as listed below: « Premew: A subject overview provides motivation for the material cov- ered in the chapter. « Examples: Each chapter contains many examples to clarify the concepts and computational details. We consider the examples important reading that further explain or amplify the points being made in the textbook. For examples that use MATLAB, the script is included on the disk. Occa- sionally, a “What If?” discussion follows an example. These discussions are meant to stimulate thought and encourage a review of the pertinent material. « Reinforcement Exercises and Exploration Problems: The Reinforcement Exercises generally are straightforward problems that require application of the material in the chapter. Selected answers are provided. The Explo- ration Problems are intended to be more difficult than the Reinforcement Exercises. These problems were designed to extend the material covered in the chapter and to provide a greater challenge. The book does not contain answers to these problems. © Annotated Bibhography: Sources of additional information are listed with a brief description of the reference. Answers: The answers section includes results for some of the Rein- forcement Exercises. 02 Chapter Organization xiii SOFTWARE AND FILES FILES MATLAB is an acronym for MATrix LABoratory. It is produced and sup- ported by The MathWorks, Inc., of Natick, MA. The company provides technical assistance, technical notes, a periodic digest, and many MAT- LAB scripts at their FTP site (ftp.mathworks.com). More information is available at their Web site: http://www.mathworks.com. The Brooks/Cole Web site for this textbook (http://www.brooks cole.com/engineering/ee/hrd /advengmth) contains MATLAB scripts (pro- grams) for all the examples that use MATLAB as well as scripts for se- lected answers to Reinforcement Exercises that lend themselves to MAT- LAB solution. Warning: Execution of some of our scripts with your version of MAT- LAB may lead to error messages since MATLAB is being upgraded fre- quently. Usually the problem can be resolved by modifying the script appro- priately according to the instructions in the User's Manual for the version of MATLAB you are using. Also, the text file (README.TXT) on our Web site should be studied carefully before using the scropts. Our Web site has a directory that contains a subdirectory for each chapter (CHn n =1,2,...,15) . These disk directories are as follows: 1. CLFLCHn (n = 1,2,...,15) contain the MATLAB files for the MATLAB examples in the text. The prefix CLFL means Clear Lake Files with the name reflecting the fact that these files were created near Clear Lake in Houston where our university is located. 2. ANSCHn (n = 1,2,...,15) contain MATLAB files that are an- swers to selected Reinforcement Exercises that require MATLAB scripts or problems for which MATLAB scripts are helpful. ‘We attempted to design the examples in this book with the motto “The purpose of computing is insight, not numbers” in mind. This is the motto from R.W. Hamming’s book Numerical Methods for Scientists and Engineers, McGraw-Hill, Inc. Also, the MATLAB scripts are written with clarity as the primary goal. Therefore, it is intended that the reader modify and improve the scripts in some cases, particularly with respect to the efficiency of the program in solving a specific problem. © Preface MAPLE FILES —-Maple is a programming language with numerical, graphical, and symbolic capabilities. As such, it is an excellent complement to the numerical capa- bility of MATLAB. In fact, the MATLAB Symbolic Math Toolbox employs Maple for symbolic manipulation. A Maple supplement is included on the Brooks/Cole Engineering Web site. The supplement contains Maple script files for most of the examples in the textbook. For users of Maple, the scripts serve the same purpose as the MATLAB scripts. You may contact Waterloo Maple Software, Inc., of Waterloo, Ontario, Canada at their WWW address (http://www.maplesoft.com/) for more information about Maple. ANCILLARIES A Solutions Manual is available for instructors (ISBN 0534-37787-4). This manual contains answers to the Reinforcement Exercises in Chapters 2 through 15 that do not require MATLAB solutions. A CD-ROM is in- cluded with the Solutions Manual and it contains the MATLAB M-files for the examples in the textbook and answers to problems that require MATLAB solutions. In addition, on the CD you will find a Maple supple- ment that contains the script files for solutions to Reinforcement Exercises in the text. 5 [os ACKNOWLEDGMENTS FOR THE SECOND EDITION The authors would like to express their gratitude to all those who con- tributed to this textbook. We appreciate the helpful comments of our reviewers: Richard Arnold, University of Nebraska; Orlando R. Baiocchi, North Dakota State University; Jon Bredeson, Texas Tech University; Clark T. Merkel, North Dakota State University; Charles P. Neuman, Carnegie Mellon University; David Rogers, North Dakota State Univer- sity; Ariela Sofer, George Mason University; H. J. Trussell, North Carolina State University; and Zhimin Zhang, Texas Tech University. The material and the scripts were developed over several semesters with many helpful suggestions from the students in the engineering applications class at the University of Houston—Clear Lake. In particular, Katharine Brown gave a very complete review of the text. We would also like to thank our secre- tary, Jeanne Leslie, for her outstanding help in producing this textbook. 04 ANCILLARIES : v Norman Richert developed the IT pX typesetting macros. Those in- terested in further information about IATRX and TEX are encouraged to access the Web site of the THX Users Group at http://www tug.org/. T. L. Harman ([email protected]) N. Richert ([email protected]) J.B. Dabney (Jdabney@ow!net.rice.edu) um Preface To Students and Professionals Our book is intended to present mathematical principles, concrete exam- ples, and occasionally a MATLAB script (program) for plotting or calcu- lation, It can be used to review various subjects in applied mathematics; this section explains the use of examples and MATLAB scripts assuming you are using the textbook for review purposes, The next section entitled To Instructors describes the use of the text as a course text. USE OF EXAMPLES AND “WHAT IFS” We think that the most efficient learning comes from studying examples and then working problems with increasing levels of difficulty. Some exam- ples are followed by “What If?” questions that are intended to stimulate thinking about more intricate details of the concept being presented. xvii Consider Example 1.7 that requires the study of the function 2V3 at 5 x u(t) = =e sin (wt + 3): The text of the example discusses the mathematical properties of the function to determine the plotting parameters. Then, a MATLAB script is presented that plots the function. The “What If?” question that follows the example asks you to determine the zero crossings of the function using the zoom command. This extends the basic concept and the script. After an example, it is suggested that you complete some of the re- lated Reinforcement Exercises. Solutions to selected problems are given at the end of each chapter. Exploration Problems are also included in each chapter. These generally require more thought and effort than the Reinforcement Exercises. USE OF THE MATLAB FILES ON THE WEB SITE Although the book is structured so that basic mathematical principles can be studied without using MATLAB—many of the examples and the problems at the end of the chapters do not require MATLAB scripts—we have generally assumed that it will be used with the MATLAB (or Maple) software. MATLAB scripts, also called M-files, are provided on the Web site, for each of the examples and some of the Reinforcement Exercises that use MATLAB. This collection of MATLAB scripts can serve as a “library” of programs for mathematical applications. These scripts can be executed with the “echo” feature of MATLAB to see the effect of each instruction. Once the example in the text is reproduced and understood, you could execute the script with different input values or other changes to compare the results. You are encouraged to use and modify the MATLAB scripts pro- vided in the book. We feel that computer work is a necessary part of the study of applied mathematics today, both as an aid to learning and as a technique useful in applications. The appropriate modifications might include adding additional comments that personalize the scripts. To in- crease efficiency, vectorized code could replace loops in some scripts. The ultimate goal should be to extend the application of the program to solve more sophisticated problems, perhaps those suggested in the Exploration Problems that require MATLAB. Before executing any programs, you are advised to read the readme file included on the Web site. = To Students and Professionals To Instructors In Advanced Engineering Mathematics Using MATLAB, we emphasize the explanation of mathematical principles and support those explana- tions by examples and simple MATLAB scripts. Since we omit most. of the proofs to the theorems, and the examples are generally straight- forward applications of the mathematics, the text is easy to read and substantially free of mathematical difficulties. The content, Examples, and Reinforcement Exercises are designed to present and reinforce the material we consider important for a general course in applied mathe- matics. On the other hand, the Exploration Problems in each chapter are included without answers to inspire inquisitive students. Described below are the conceptual structure of the textbook, the use of MATLAB, and suggestions for courses in which our textbook may be used as a primary textbook or as a companion volume to a more traditional book. STRUCTURE OF THE TEXTBOOK The first chapter iS included for those students who are unfamiliar with MATLAB or those who wish to improve their use of the software. The design of the Examples, Reinforcement Exercises, and Exploration Prob- lems involving MATLAB in other chapters is based on the assumption that the material in Chapter 1 is well understood. Portions of the MAT- LAB tutorials in The Student Edition of MATLAB User’s Guide would be an appropriate supplement to Chapter 1. A AND ENTIAL ONS Recognizing the increasing importance of applied linear algebra and com puter techniques in mathematics instruction, we have included chapters on vectors, matrices, and eigenvalues and eigenvectors. These chapters serve to introduce important mathematical concepts as well as allow the student to take advantage of the computational ability of MATLAB. The emphasis that should be given to Chapter 2, Chapter 3, or Chapter 4 depends on the background of the students. However, the material in Chapter 4 covering eigenvalues and eigenvectors is useful for understand- ing parts of Chapters 5 and 6. Differential equations are covered in the text in several chapters. Chapters 5 and 6 treat ordinary differential equations and Chapter 15 introduces partial differential equations. In Chapter 8, Fourier methods are applied to the solution of ordinary differential equations to determine the frequency response of systems. Chapter 9 presents Laplace transform techniques to solve differential equations. IMATION Chapter 7 presents several of the methods to approximate functions. In- \CTIONS, R ISIS CE FORMS, terpolation by both polynomial and spline fitting is discussed briefly. The equations of the least-squares approximation are presented in matrix form in the text. The vector form as a projection is treated in one of the Ex- ploration Problems. The discussion of orthogonal functions and polynomials begun in Chapter 2 and treated in Chapter 6 is continued in Chapter 7. The emphasis in Chapter 7 is on the properties of orthogonal functions useful for understanding Fourier series in Chapter 8. Chapter 8 presents the essentials of classical Fourier series and Fourier transform methods. MATLAB is used mainly to plot results calculated analytically. However, the errors involved in truncating the Fourier se- ties and the Gibbs phenomenon are illustrated using MATLAB in the examples and in the problems at the end of the chapter. The Fourier spectra for series and transforms are also emphasized in Chapter 8. Again, MATLAB plots are useful to help students visualize the results. As practical examples, both Fourier series and transforms are used to solve differential equations to determine the frequency response of a system modeled by a linear differential equation. Chapter 9 covers the Laplace transform and its applications to linear differential equations and linear systems. The main sections of the chap- ter cover the definition and properties of the Laplace transform, tech- niques for computation of the inverse transform, MATLAB commands for Laplace analysis, Laplace solution of ordinary differential equations, and applications to linear systems including stability criteria. The chapter also presents the relationship between Fourier and Laplace transforms. © To Instructors DISCRETE SYSTEMS AND DFT MULTIVARIATE AND VECTOR CALCULUS. PARTIAL DIFFERENTIAL EQUATIONS Chapter 10 presents various techniques to analyze sequences, discrete sig- nals, and discrete systems. After sequences and discrete functions are introduced, solution methods for linear difference equations are demon- strated. The chapter then introduces the concepts of smoothing and dig- ital filters with MATLAB programs to plot the frequency response of discrete systems. Chapter 11 presents the discrete Fourier transform (DFT) and the im- portant fast Fourier transform (FFT) algorithm. The DFT is presented as an approximation to the Fourier transform and as a method of analyz- ing real signals. The errors involved in practical signal analysis, such as aliasing, are explored in detail. Chapters 12, 13, and 14 describe multivariate and vector calculus and the ways in which MATLAB can be used to aid problem solving or plot useful results. For these chapters, the student is expected to be familiar with single-variable calculus. Chapter 12 introduces differential calculus of functions of several vari- ables. Various topics include limits, continuity, partial derivatives, the differential, the Jacobian, Taylor series, and finding extrema for functions of several variables. Vector functions and curvilinear coordinates are also presented. MATLAB scripts are used to plot multivariate functions to aid visualization as well as to perform other operations such as finding the minimum of a function. Chapter 13 is concerned primarily with scalar and vector fields used to represent physical values that vary with position in space. The differ- ential operators of gradient, divergence, curl, and Laplacian are studied in rectangular and curvilinear coordinate systems. Applications from me- chanics, fluid flow, and electromagnetic theory are presented. Chapter 14 begins with a brief review of integration and presents double and triple integrals in various coordinate systems. The Jacobian is used to explain change of variables in multiple integrals. Applications, nu- merical techniques, and MATLAB commands for integration are covered. Example applications of multiple integrals are two-dimensional Fourier transforms and joint probability functions. Line and surface integrals are first defined in Chapter 14 as generaliza- tions of ordinary integrals and then as line integrals and surface integrals of vector fields. The chapter next covers various theorems of vector in- tegral calculus. The theorems of Green, Stokes, and Gauss are discussed and then applications are considered. Conservative forces, fluid flow, and Maxwell's equations of electromagnetic theory provide useful examples. Chapter 15 introduces Laplace’s partial differential equation, the heat equation, and the wave equation. The solution technique of separation of variables is emphasized since this chapter builds on the treatment of ordinary differential equations given in Chapter 6. 08 Structure of the Textbook wx USE OF MATLAB MATLAB TOOLBOXES IATLAB ERSUS |ATHEMATICS, An important reason we chose MATLAB as the computer language for this book was its wide acceptance in the engineering community. The student edition is a relatively inexpensive investment for the student, par- ticularly considering that the MATLAB program will be useful in many courses. Also, after graduation, students will probably encounter the pro- fessional version of MATLAB or a similar software package for calculation and simulation. The MathWorks provides Classroom Kits to instructors and it is possible to install MATLAB on the school’s computer network for access by all students. One advantage of MATLAB is that many of its functions (M-files) can be read as text files. For these functions, the algorithm is typically described in the script itself or in the MATLAB User’s Guide so that interested students (or instructors) can study the computational methods in more detail. With a few exceptions, such as the Runge-Kutta algorithm in Chapter 6, we have not tried to analyze the algorithms in detail. We| feel that such analysis properly belongs in a Numerical Methods course. Instead, we have tried to address the problems encountered when using the functions. Thus, the condition number of a matrix is considered in’ Chapter 2. As another example, our treatment of the fast Fourier trans- form (FFT) algorithm explains the errors made by improper sampling of a signal rather than numerical errors due to computation. The Student Edition of MATLAB contains a Symbolic Math Toolbox and we have included examples to illustrate the symbolic capability of MAT- LAB in the textbook. We have found that students in a course will soon discover most of the symbolic commands and use them to advantage. The Symbole Math Toolboz is really a MATLAB interface to a limited ver- sion of the Maple software. For Maple users, symbolic solutions to many examples and problems using Maple are included on the disk. The Student Edition of MATLAB also contains the Signal Processing Toolbox. These toolbox functions are useful for courses in Linear Systems or Digital Signal Processing. One use of these toolboxes is to introduce them in a course that presents segments dealing with the mathematics of subjects such as communications, image processing, digital signal pro- cessing, or Fourier methods. The fact that Chapter 1 introduces MATLAB might lead a reader to the (erroneous) conclusion that the textbook is really about MATLAB. This is not the case, and those instructors who wish to start immediately with To Instructors OTHER LANGUAGES the mathematics can begin with Chapter 2 and leave Chapter 1 for study by the students. If the students are familiar with MATLAB, they can try some of the Reinforcement Exercises or Exploration Problems at the end of Chapter 1 to test their skills. It was our intention that the ratio of MATLAB to mathematics in the textbook should be such that mathematical principles rather than computations were emphasized. In a traditional mathematics course, the programming aspects could be downplayed and MATLAB could simply be used for calculations and plotting. Results derived by hand could be checked using commands from the Symbolic Math Toolbox. More detailed programming assignments could be given in a course stressing MATLAB or in a computational laboratory course. Assigning some of the Exploration Problems involving MATLAB would be useful in such courses. Occasionally, in the authors’ courses, students have used Mathematica or Maple to do the assignments from the textbook. These languages are not discussed in the textbook but the students have been successful in the course. Since these programs perform symbolic mathematical operations, some of the assignments using the numerical capabilities of MATLAB could be modified slightly to fit the situation. SUGGESTIONS FOR COURSES The material in the textbook has been used in one- and two-semester courses for students of engineering and physics. In this section, we include suggestions for courses using the textbook. A one-semester introductory course in applied mathematics might cover the material in the first six or seven chapters. In two semesters, all of the book could be completed. Tables in this section list essential topics by section title in specific chapters. Suggestions for optional topics and topics that could be added are also included. A more advanced one-semester course might start with Chapter 6 (Advanced Diffetential Equations) and cover most of the topics up through partial differential equations in Chapter 15. Assignments in such courses should include the Exploration Problems. For programming assignments, the MATLAB scripts included in the text are a starting point. The ex- amples or problems associated with them could be modified suitably and assigned as homework. For a more rigorous course, the instructor could supply details of mathematical proofs and include additional topics not treated in our book. 010 Suggestions for Courses eat Additional topics are suggested in the chapter summaries to follow Spe cific MATLAB commands are indicated by boldface type. Chapter 1 Introduction (to MATLAB) The emphasis placed on this chapter depends on the background of the students and the purpose of the course. Table 0.1 lists the essential sections of Chapter 1. One essential point about MATLAB is that the array (matrix) is the basic data structure for MATLAB. For example, it is important to emphasize the difference in notation for element-by-element operations versus array operations. The discussion of the colon, semicolon, and period operators in Chapter 1 covers such notation. Another capability of MATLAB to emphasize is the extensive on-line help and the use of the echo command during execution of a script. ‘A number of the programming problems at the end of Chapter 1 em- ploy MATLAB essentially as a calculator to give the students confidence in using the software. To highlight the programming language aspects of MATLAB, more complicated scripts such as those required by Prob- lem 1.19 or Problem 1.20 could be assigned as homework. If efficient programming is emphasized in the course, the difference between using loops and vectorizing is vital. Some of our MATLAB ex- amples can be improved in this regard. Improving the scripts gives the students additional motivation for studying the examples and exercises that use MATLAB. TABLE 0.1 Chapter 1 Toprcs Essential Sections Optional Topics Topics to Add ¢ Introduction to MATLAB —_—e eval (Example 13) _ Programming pro; MATLAB Commands for Problem solving and» Symbolic MATLA Display and Plotting programming Creating MATLAB Programs ¢ MATLAB Language As an optional topic, the MATLAB command eval is useful in some applications. The command is introduced in Example 1.3 and it should be compared to MATLAB functions later in the chapter after Example 1.8 is covered. The optional section “Problem Solving and Programming” might be discussed in a course involving a computational laboratory. A number of applications from physics or engineering might be combined to form a programming project for the semester. Also, the symbolic capability of the Symbolic Math Toolbox could be presented and appropriate problems created and assigned. @ To Instructors Chapters 2-4 Linear Algebra Topics Topics from applied linear al- gebra span three chapters because modern applied mathematics combines calculus and algebra in many powerful algorithms that can be solved us- ing a computer. Thus, matrix methods are now used in applications to solve differential equations and in courses to explain algorithms such as the fast Fourier transform. Table 0.2 lists essential and optional topics if these chapters of the text are to be covered in detail in a course. Most of the topics in Chapter 2 and Chapter 3 are appropriate for such a course. TABLE 0.2 Linear Algebra Topres by Chapter Essential Topres Optional Topics Topics to Add Chapter 2 © Most of the topics ¢ MATLAB computer numbers Expanded treatment of in this chapter « Vector spaces of functions complex numbers Chapter 3 © Most of the topics ¢ Homogeneous transformations — Discussion of numerical erro: m this chapter in matrix operations ¢ Symbolic matrix operations Chapter 4 ¢ General Discussion of © Matrix calculus ¢ Motivational examples Eigenvalues © Similar and diagonahzable * Computational methods © Eigenvalues and Eigenvectors © Matrix Eigenvalue Theorems © Complex Vectors and Matrices ¢ MATLAB Commands for Eigenvectors matrices © Special matrices Hermitian and unitary matrices © Applications to differential equations Chapter 2 briefly discusses MATLAB computer numbers, including complex numbers, and this section could be covered if the course empha- sizes the numerical aspects and errors involved in computer computations. For students who need a review, a more complete discussion of complex numbers could be added. Vector spaces of functions is another optional topic; however, this section is useful background for the discussion of orthogonal functions in later chapters. Chapter 3 ébvers useful topics involving matrices. We consider the discussion of homogeneous transformations optional. Obviously, a great deal of material could be added since matrices play a role in many ap- plications. A few suggestions are given in Table 0.2. In some courses, it would be appropriate to explore the numerical problems that arise when large matrices are used. Such discussions could expand on the material 010 Suggestions for Courses > concerning ill-conditioned matrices in the text. A starting point might be operations involving large Hilbert matrices or the Vandermonde matrix. Chapter 4 can be presented in several ways. The introductory sec- tions of the chapter are intended primarily to present the mathematics of eigenvalues and eigenvectors. In fact, the basic material about eigenvalues and eigenvectors was included mainly to serve as background material for differential equation problems in Chapter 5 and Chapter 6. The resistor network used in Example 4.4 and Example 4.5 shows that the currents can be written as a linear combination of eigenvectors, as indicated by Equation 4.20. Later examples demonstrate the fact that the behavior of a vibrating system can be analyzed by knowing the frequencies and the mode shapes of oscillation, which are related to the eigenvalues and the eigenvectors of a dynamic system, respectively. ‘To emphasize the analysis of mechanical systems, Example 4.18 and Example 5.18 with coupled masses or Example 6.13 showing the bending of a vertical column could be studied. MATLAB has useful commands to compute eigenvalues and eigenvec- tors. Example 4.10 is worth some study. This example shows the use of iteration to compute the eigenvalues of a matrix using the QR decomposi- tion method. The displayed results show the relationship between the QR. decomposition and the final eigenvalue and how the matrix scheme con- verges. Such an iterative process could not reasonably be done by hand calculation. The students should be encouraged to execute the script and observe each step as an aid to understanding the algorithm. The sections on matrix calculus and the special matrices can be con- sidered optional if matrix methods are not the main topics in a course. If matrix calculus is covered, the Cayley-Hamilton theorem could be studied in more detail using Example 4.17 to illustrate the use of matrix calculus to solve a system of differential equations. Other examples that could be used with this chapter include mechan- ical systems with a large number of degrees of freedom. Alternatively, such examples could be treated later after the chapters on differential equations. The generalized eigenvalue problem Ax = ABx could also be presented in the form By + Ay = 0 and solved as additional examples in Chapter 5. Since eigenvalues and eigenvectors are generally difficult to compute for large systems, numerical difficulties in computation could be discussed and suitable problems assigned. Chapters 5-6 Differential Equation Topics Chapter 5 is concerned with linear differential equations with constant coefficients. In class, we typically assign equations to be solved by hand and then encourage the use of MATLAB to study variations and plot comparative results. Chapter 6 considers more advanced differential equations and numerical solutions. @ To Instructors ‘Table 0.3 indicates essential and optional topics as well as possible addi- tions for these chapters. TABLE 0,3 Differential Equation Topics by Chapter Essentral Toprcs Optional Toprcs Toptcs to Add Chapter 5 ‘© Most of the topies © State space representation _ Various specific applications in this chapter Chapter 6 Functions and Differential Stiff equations * Generalized inputs Equations ¢ Numerical methods * Nonlinear equations ‘* Sequences and Series Boundary-value problems © Taylor Series © Sturm-Liouville equations e Vector Equations ¢ Equations with Variable Coefficients Bessel and Legendre Equations Chapter 5 begins with a discussion of first-order equations. The MAT- LAB symbolic command dsolve is used to solve an equation with various initial conditions. Second-order differential equation solutions are pre- sented next. Then, systems of differential equations are discussed. ‘The section on transforming a differential equation into a system suit- able for matrix solution should be treated with emphasis on Example 5.18 if students are unfamiliar with the technique. The MATLAB functions ode23 and ode45, used to solve differential equations numerically, are introduced in this chapter but not discussed in detail until Chapter 6. In Chapter 5, the discussion of state space could be skipped, particu- larly if the students are familiar with linear systems theory. Many topics could be added to the material, including applications of specific interest to the students. Chapter 6 treats differential equations with discontinuous inputs and equations with variable coefficients. A review of functions, sequences, and series may be necessary depending on the background of the students. Vector differential equations and equations with variable coefficients are the important topics to be covered. The Bessel and Legendre ordinary differential equations serve as examples. The solution functions are also used in Chapter 15 where partial differential equations are solved. Optional topics in Chapter 6 include stiff differential equations, de- tailed discussion of numerical techniques to solve differential equations, boundary-value problems, and Sturm-Liouville equations. 010 Suggestions for Courses exvii Differential equations with generalized inputs such as impulse (delta) functions are not covered in this chapter, but are treated m Chapter 9 by Laplace transform techniques. Nonlinear differential equations are not treated in detail although such equations are considered in the text and in the problem section. More details on such topics could be added to create a fairly complete course in ordinary differential equations. Chapter 7 Approzimation of Functions The overall purpose of this chapter is to present several ways to represent a function in terms of other functions. The material covered should be selected according to the overall content of the course with particular emphasis placed on numerical methods. An application of curve fitting might be presented to motivate the students. Data values corrupted with noise could be used to simulate the measured values on a data acquisition channel. The MATLAB function rand can generate the simulated noise values. If interpolation is to be covered, Example 7.1 should be discussed in detail. The example points out the errors that can arise using polynomials for interpolation over many points. Other interpolation schemes such as interpolation with arbitrarily spaced points (Lagrange interpolation) could be presented. Spline fitting to data points eliminates the numerical instability as- sociated with polynomial interpolation over a large number of points by using piecewise polynomial interpolation. We have omitted the deriva- tion of the matrix equations for spline fitting but the equations are easily derived. One reason for the omission is that MATLAB has an efficient spline-fitting routine. Interested students can read the M-file (SPLINE.M) that is part of MATLAB. Various applications such as the use of splines in graphics could be presented in class or assigned as homework. Chapter 7 also presents least-squares curve fitting and gives an exam- ple to show how MATLAB solves the problem. The Exploration Problems for Chapter 7 treat other aspects of the least-squares method. Since there are more equations than variables, the least-squares equations derived in the chapter are the normal equations of an overdetermined linear system. Problem 7.15 presents the vector (projection) solution to the least-squares equations. The discussion of orthogonal functions should be reviewed before cov- ering Fourier series in Chapter 8. Theorem 7.1 defines the Fourier coeffi- cients as giving the best least-squares fit when a function is approximated by a sum of orthogonal functions. Example 7.4 and the discussion of or- thogonal functions show that the famous Fourier trigonometric series is but one of many orthogonal series. Convergence of a series of orthogonal functions and Parseval’s equality are other useful concepts to be discussed also in Chapter 8. Chapter 8 Fourier Analysis Chapter 8 presents Fourier series and Fourier transforms for continuous functions. Table 0.4 lists essential and optional topics from the chapter as well as suggestions for added topics. va @ To Instructors TABLE 0.4 Fourer Topics by Chapter Essential Sections Optional Topics Topics to Add Chapter 8 Fourier Series ¢ Power masignal © Symbolic calculatic ¢ Properties of Fourier Series Energy ina signal © Convolution ¢ Fourier Transforms Frequency response Other transforms Complex analysis Before covering Fourier series, the students should be familiar with the material on orthogonal functions in Chapters 2, 6, and 7. In our Fourier series examples, such as Example 8.2, MATLAB is used to plot analytical results only. However, MATLAB is ideal to sum the Fourier se- ties for different numbers of terms and compare the results. In particular. the Gibbs phenomenon could be investigated in detail to show that the amplitude of the overshoot does not diminish with the number of terms in the series. Example 15.3, in which symbolic MATLAB commands are used, shows another approach to calculating Fourier coefficients. The Symbolic Math Toolbox has commands to compute Fourier, Laplace, and Z transforms symbolically. ‘Table 8.3 in the text lists a number of applications for Fourier trans- forms. If linear systems theory is to be reviewed, the convolution theorem fits well here. Alternatively, a number of other examples could be pre- sented after the transform is introduced. : For students interested in image processing or Fourier optics, the two-dimensional transform is presented in Chapter 14. These students might also appreciate a discussion of wavelets: orthogonal functions that are a “hot topic” in certain applications areas. Information on the topic from the Internet is a good starting point for those not familiar with wavelets. Also, the MathWorks offers a Wavelet Toolbox that works with the professional version of MATLAB. Another topic to discuss might be functions, such as the unit step function, for which the ordinary Bourier transform does not exist. This is a useful function for comparing Fourier and Laplace transforms. Trans- forms of generalized functions (impulse) deserve mention if linear systems applications are being stressed. These generalized functions are presented in Chapter 9 in connection with Laplace transform applications. Computer techniques for Fourier analysis are treated in Chapter 11. It would be possible to cover these two chapters as a unit since Chap- ter 8 concentrates on theoretical results and Chapter 11 emphasizes the practical use of Fourier methods. Chapter 9 Laplace Transforms Chapter 9 introduces Laplace trans- forms and presents the analysis of continuous linear systems using the 010 Suggestions for Courses xxix transforms. First, the definition and properties of the transform are cov- ered. Then, the inverse transforms for rational functions of the Laplace variable s are considered using the Heaviside expansion technique. If this is the students’ first introduction to Laplace transforms, some motivation examples explaining the use of the inverse transform may be necessary. For example, Figure 9.1 shows the procedure for solving differential equa- tions using the inverse transform. Also, a review of the partial fraction expansion of ratios of polynomials may be necessary before treating the inversion methods presented in the chapter. MATLAB examples to com- pute an inverse Laplace transform are also presented. The application of Laplace transform techniques to the solution of time-invariant linear differential equations is straightforward. The solu- tions can be compared to those similar equations in Chapter 5 to show the efficiency of the Laplace transform method when initial conditions are involved. The chapter also considers the solutions to the differential equations for special inputs such as a step function, an impulse function, or a periodic function. To present the application of Laplace transforms to the analysis of linear systems, the impulse response of a system and the convolution theorem are explained. The results are used to demonstrate the repre- sentation of a system in both the time domain and the Laplace domain. Applications include the stability of a linear system, the transfer function, and the pole-zero model. Basic control applications could be presented after this section is covered. The close relationship between the Fourier and Laplace transform as presented in Chapter 9 should be shown if Fourier transforms in Chapter 8 have been covered. The chapter provides a summary of the properties of the Laplace transform with a table showing the almost symmetrical relationship be- tween operations in the time domain and the Laplace domain and con- cludes with statements of the initial and final value theorems. Chapter 10 Discrete Systems The presentation of discrete systems in Chapter 10 is intended to serve as an introduction to difference equa- tions, digital signal processing, and Z-transform techniques. The use of discrete models and signal processing to filter acquired data signals has become prevalent in most engineering disciplines. In fact, some educa- tors recommend presenting discrete systems before continuous systems. We take the traditional approach here and assume that the student is familiar with continuous systems. In particular, the discussion of differ- ence equations in Chapter 10 parallels that of differential equations in Chapter 5. Smoothing and digital filtering examples are presented using differ- ence equations to model the filters and MATLAB to compute and plot the results of the filtering. Another example presents the frequency response of a simple digital filter. &@ To Instructors The Z-transform is presented in a manner that follows the develop- ment of the Laplace transform and its applications in Chapter 9. In fact, the Z-transform is first defined mathematically by taking the Laplace transform of a discrete function. The two primary application areas pre- sented are the solution of difference equations and the analysis of linear discrete systems. Chapter 10 should be studied as a prerequisite to Chapter 11 if the students have little experience with sequences and difference equations. Chapter 11 Discrete Fourier Transform and FFT Chapter 11 is intended to present computer techniques to calculate the discrete Fourier transform and, additionally, to introduce some aspects of practical signal analysis. The limitations of the fast Fourier transform (FFT) algorithm in terms of the maximum frequency that can be analyzed should be stressed. Also, students should realize that the fact that the signal processed by the FFT and the resulting spectrum are effectively periodic can lead to misinterpretation of the results. ‘Understanding the phenomenon of aliasing in signal sampling and the consequences of the sampling theorem is necessary to properly apply the FFT to real signals. Example 11.6 demonstrates the error that can occur. If signal processing is to be stressed in a course, programming projects could be assigned based on the Signal Processing Toolbox. This toolbox is included in the MATLAB Student Edition and can be purchased as an addition to the Professional version of MATLAB. It is instructive to demonstrate the errors involved in signal sampling and to explore filtering or windowing techniques to reduce these errors. Chapters 12-14 Multivariate and Vector Calculus Topics Ina course in applied mathematics beyond calculus, it is appropriate to cover almost all of the topics in Chapters 12, 13, and 14, The text contains the theory and a number of concrete examples for a one-semester course in the calculus of functions of several variables and vector analysis. For successful completion of these chapters, it is assumed that the student is proficient in calculus of functions of a single variable. Students should know, or review, the basic rules of differentiation and integrations and techniques such as integration by parts. There is some review material in these chapters and elsewhere in the book. For example, the Taylor series is presented in Chapter 6. Students should also be familiar with operations with vectors as treated in Chapter 2. MATLAB is used extensively to plot functions in Chapters 12-14. For instance, MATLAB plotting commands are used to illustrate con- tour and surface plots in Example 12.1. Two-dimensional interpolation using MATLAB is demonstrated in Example 12.9. Plotting a function can help in determining the initial search point when finding the mini- mum, as shown in Example 12.14. Plots of vector functions are shown in Chapter 13. 010 Suggestions for Courses out Numerical techniques for differentiation and integration are discussed here but not in great detail. This aspect of MATLAB could be em- phasized, or alternatively the symbolic capability of the Symbolic Math Toolbox, which includes commands for symbolic differentiation and inte- gration, computation of Jacobians, and Taylor series expansion, could be explored. Examples show differentiation (Example 12.11) and integration (Example 14.8) with MATLAB commands. Chapter 12 Chapter 12 introduces functions of several variables. The main topics include partial derivatives, Jacobians for transformations, dif- ferentials and linear approximations, two-dimensional Taylor series, and extrema of multivariate functions. The section entitled “Vector Functions and Curvilinear Coordinates” can be stressed and expanded if desired. The electric dipole example (Example 12.17) may appeal only to elec- trical engineering students; however, other examples from mechanics or gravitation theory could be substituted to illustrate Taylor’s expansion in coordinate systems other than rectangular. Chapter 13 The chapter begins with a discussion of vector and scalar fields and introduces various MATLAB commands for vector calculus and plotting of fields. The gradient is derived after the directional derivative is explained. Students can use MATLAB commands to compute the numer- ical gradient (gradient) or the symbolic gradient (jacobian). If physical applications are to be stressed, we find it useful to present a thorough discussion of potential functions as in Example 13.5. Before vector field theory and its applications are presented, the chapter defines the divergence, curl, and Laplacian operators as well as Laplace’s equation. A later section presents these operators in curvilinear coordinates. A discussion of irrotational and solenoidal fields serves to introduce vector field theory. Helmholtz’s theorem is presented to define a gen- eral vector field. The section on physical applications presents examples involving energy and work, fluid flow, and electromagnetic theory. The theorems of vector field theory in Chapter 14 should be presented before more complicated applications are studied. However, a simple example from electrostatics using Laplace’s equation is presented in Example 13.13. Chapter 14 Chapter 14 covers many applications of integrals. Its two primary purposes are to explore uses of single and multiple integrals and to illustrate the integral theorems of vector field theory. Summaries of these topics are presented in Tables 14.1, 14.2, and 14.4. The chapter begins with a discussion of integration and applications of single integrals such as calculations of arc length. It then treats double and triple integrals, including change of variables formulas using the Ja- cobians of the transformations. Applications include standard problems such as finding volumes and mass as well as Fourier transforms and joint probability. ™ To Instructors Line and surface integrals are explained as generalizations of ordinary integrals. These integrals are applied to vector fields to relate line integrals to work and surface integrals to flux. The chapter then relates vector differential calculus (Chapter 13) and vector integral calculus by means of the theorems of Green, Gauss, and Stokes. A variety of applications is presented, including Maxwell’s equations of electromagnetism. Chapter 15 Partial Differential Equation Topics The material in Chapter 15 serves to tie together many of the topics presented earlier in the textbook, as Example 15.2, which uses the separation of variables technique to solve Laplace’s equation, demonstrates. Complex analytic functions might be discussed as an addition to this chapter by showing such solutions to Laplace’s equation. Conformal mapping techniques can be presented to solve the equation subject to various geometries of the boundary. For example, Laplace's equation in a 45° wedge is simplified by the conformal mapping that doubles angles. Poisson’s equation solved by Green’s function, an approach used in physics, could be presented. Engineers often refer to the result as the impulse response of the system. In summary, Table 0.5 lists some of the many possible combinations of topics. TABLE 0.5 Table of Courses Course Toprcs Apphed Linear Algebra Chapter 2, Chapter 3, Chapter 4, Parts of Chapter 7 Differential Bquatons Chapter 5, Chapter 6 Fourier Solution (Chapter 8) Laplace Solution (Chapter 9) Difference Equations (Chapter 10) Chapter 15 (Partial DEs) Founer Analysis Orthogonal functions (Chapters 2 and 7), Chapter 8 DFT and FFT (Chapter 11) 2D Fourier (Chapter 12) Laplace Transforms __Chapter 9, Z-transforms (Chapter 11) Advanced Calculus Series (Chapter 6), Chapter 12, Chapter 13, Chapter 14 Applted Mathematscs Selected topics from Chapters 2-4 Series (Chapter 6), Fourier (Chapter 8) Sequences (Chapter 10) Chapter 12, Chapter 13, Chapter 14 010 Suggestions for Courses xox 0.11 PRACTICAL SUGGESTIONS This section gives a few practical suggestions for using the textbook. ematical motivation for the material in the chapter. In some cases, have emphasized the use of mathematical techniques to solve problems in} electrical engineering. However, we also provide applications to mechanics and other areas of physics. Other suitable examples and discussion could be added if the students are better motivated by applications within a certain discipline. PREVIEWS The Preview for each chapter is intended to provide physical or = USE OF The proofs of most mathematical theorems presented in the textbook hay THEOREMS been omitted to make the text more readable to those who wish to em-| AND PROOFS _phasize applications and computations. Theorems are usually explain by examples or MATLAB programs. Occasionally, a constructive proof i supplied, such as that for the theorem that relates linear transformation and matrices in Chapter 3. The proofs of other assertions can be supplit at the discretion of the instructor. REINFORCEMENT It was decided to include two classes of problems after each chapter ! EXERCISES AND Reinforcement Exercises contain “drill”- type questions, while the Expl EXPLORATION ration Problems extend the difficulty and range of questions. The Rein PROBLEMS forcement Exercises are intended to give students confidence in probl solving and in the use of MATLAB before attempting the more challe ing Exploration Problems. Analytical answers are provided for select Reinforcement Exercises. The Exploration Problems are intended to cover more difficult appli4 cations or elaborate on theory not covered in detail in the text. ‘The represent a starting point for exploring concepts that are the ultimate go: of applied mathematics. The emphasis placed on these problems depends on the way the textbook is used and the level of difficulty suitable for the course. Occasionally, problems require reference to other sources or literature} searches. These problems can be assigned if appropriate. For specific| applications, projects that combine various problems could be assigned. This approach can be particularly useful if the emphasis is on a particular} discipline, such as electrical or mechanical engineering. roxriv m To Instructors Introduction PREVIEW. MATLAB is an interactive computer program containing various commands and functions that aid mathematical analysis of problems in engineering and science. This first chapter is devoted to a discussion of MATLAB and introduces a selection of its many features MATLAB examples will be presented throughout the textbook and applied to vector and matrix operations, ordinary differential equations, Fourier analysis, Laplace transforms, discrete systems, vector calculus, and partial differential equations Table 1.1 lists some of the general features of MATLAB and presents examples of the many operations that are possible As indicated in the table, MATLAB is used for calculation, graphics, mathematical analysis, programming, and additions to MATLAB for solution of problems in specific technical areas For calculations, an important feature of MATLAB is that the program can perform valid mathematical operations using not only real and complex numbers but also vectors and matrices MATLAB also has excellent graphics capability, enabling the user to visualize complicated functions in a variety of ways to aid analysis The functions for mathematical analysis are useful for problem solving in areas such as calculus, differential equations, and linear algebra as well as more advanced studies Finally, MATLAB is a complete programming language Thus, programs can be created to solve many problems of practical interest. TABLE 1.1 Selected MATLAB features Feature Examples Caleulator: Arithmetic and trigonometric x ty, zy, 2/y, V2, €*, log, opergtions x, sin, cos a Graphics. ‘Two- and three-dimensional Plot f(z), f(z,y), and f(x,y, 2) graphs Mathematical Analysts: Calculus Differentiation and integration Differential equations Solve differential equations General Curve fitting and interpolation Linear algebra Solve linear systems of equations Special functions Bessel and Legendre functions ‘Transforms Fourier, Laplace, and Z-transforms Statistics Mean and standard deviation Programming Language: Decision-making instructions For, while, and if-then-else statements 1/O transfer Load and save disk files Example MATLAB Esztenswons: Symbolic Operations Symbolic Math Toolbox Signal Processing Signal Processing Toolbox Compilers MATLAB C Compiler Many extensions to MATLAB are available from the MathWorks as well as other sources The toolboxes are designed to solve problems in specialized areas of engineering and science For example, one toolbox contains a set of commands (functions) for operations on variables and expressions defined symbolically. Collectively, these commands comprise the Symbohe Math Toolbox Occasionally in our textbook, we give examples using this toolbox Another toolbox is the Signal Processing Toolbox This toolbox is most useful in the study of signal processing or linear systems MATLAB code can be converted to C code using the C compiler This chapter begins with descriptions of the basic mathematical and graphical capability of MATLAB Then, several sections are devoted to Chapter 1. @ INTRODUCTION MATLAB programming techniques Many of the MATLAB features discussed in this introductory chapter are treated in more detail in later chapters For example, the features and limitations of MATLAB for ‘operations on numbers and vectors are discussed extensively in Chapter 2. Matrix operations are covered in Chapter 3. This first chapter is intended to be somewhat interactive in nature. We suggest that the reader use the MATLAB program itself and the MATLAB User's Guide available from The Math Works, Inc , along with our text to clarify the points being discussed INTRODUCTION TO MATLAB INSTALLATION MATLAB is an interactive environment for numeric and symbolic com- putation. The program provides a mathematical library for matrix op- erations, the solution of differential equations, data analysis, and signal processing. The various operations are performed when MATLAB com- mands are recognized and executed. There are also a number of graphical commands that allow the display and visual analysis of data in two and three dimensions. In addition to the mathematical, scientific, and engi- neering functions that are the basic operations provided by MATLAB, the commands can be combined into programs to solve realistic problems. The description in this chapter applies mainly to MATLAB as used on personal computers (PCs) with the Windows operating system. Ver- sions of the program for other types of computers may not have exactly the same features. The reader should refer to the MATLAB User’s Guide for a specific computer to determine any differences. In the PC version, MATLAB commands can be entered through the keyboard or MATLAB can execute special programs called M-files to perform various operations, such as invert a matrix, evaluate an integral, or solve a system of differ- ential equations and plot the results. The system requirements and installation procedure differs for different types of computers and different operating systems. For example, the pro- cedure for Windows systems, Unix-like systems, and Macintosh software systems require specific procedures for installation. Unfortunately, it is not possible to give general instructions for installation. For the version of MATLAB that the reader is using, the latest installation instructions in the release notes should be consulted. Also, different versions of MATLAB 11 Introduction to MATLAB 3 “URE have slightly different characteristics. Again, it is important to consult the release notes that come with the version you are using. In the descriptions in this text, MATLAB commands are shown in bold- face type, such as help, which displays the available MATLAB topics for which help is available. However, in examples that present executable MATLAB commands, the commands are shown exactly as typed, such as help. The names of files stored on disk are designated by capital letters. The examples in this chapter illustrate the use of basic MATLAB commands. In later chapters, other commands will be defined as they are introduced. However, many of the commands have a number of variations that are not discussed in this text. These variations are explained in the MATLAB User’s Guide or by the on-line help notes that are part of MATLAB itself. The inexperienced MATLAB user should study this chapter while experimenting with the commands on the computer. MATLAB executes commands entered from the keyboard or from files stored on disk. The variables used in a problem can be defined via key- board input or read from disk files also. The structure of the MATLAB file system is shown in Figure 1.1. M-Files Functions Data files WORKSPACE MATLAB}—__ Diary file variables & MATLAB files FIGURE 1.1 MATLAB structure This figure shows the general relationship between the MATLAB pro- gram and various files on disk. The M-files and function files contain MATLAB commands to be executed when a file is called by entering the name of the file in response to the MATLAB prompt. A collection of MATLAB commands is usually called a MATLAB script. Variables used during a MATLAB session are held in the workspace! The data files result when variables are saved with the save command. These variables can be loaded into the workspace with the load command. Chapter 1 m= INTRODUCTION’ A MATLAB SESSION The diary file contains a copy of the commands executed and the results obtained during a MATLAB session. A MATLAB sessvon is said to begin when the program prompts the user for a command with the >> prompt on the computer screen. This screen is MATLAB’s command window. Then, the user may input variables or execute any one of the available commands to perform calculations, solve equations, and display or plot the results. The variables used in the session are held in the workspace, which is created whenever MATLAB is invoked. The computer directory in which variables and other data are saved in the current session is considered the working directory. MATLAB responds to commands of the form: >> (CR) >> = (CR) >> [ ] = (CR) The notation means that any valid command can be substituted for command in the list just shown. This same notation is used for the variables. Since many commands require input values as arguments for the command, the reader should consult the MATLAB User’s Gude for a complete discussion of any command. After a command followed by a carriage return (CR) is entered at the keyboard, MATLAB will perform the specified action. Subsequent discussions will omit the CR from the text. In MATLAB examples, the CR is not printed since it is not displayed in an actual MATLAB session. As an example, the command >>demo passes control to the demonstration program included with MATLAB. This is a good command to execute when learning MATLAB since the demo programs show many of the capabilities for calculation and plot- ting. Other commands, such as exp, compute a value. The second form of a command assigns a value to a variable. As an example, the commands to define a variable z and compute the value y = e” are as follows: >>x = 2 xe 2 >>y = exp(x) y= 7.3891 The commands assign the value of e* to the MATLAB variable y and display the value of the MATLAB variable x as well as the result e” in this case. Mathematical functions such as exp require an argument. In the case of exp, the argument can be a scalar variable, a row of numbers 11 Introduction to MATLAB 5 -T-IN CTIONS. ) M-FILES. EXAMPLE 1.1 corresponding to vector, or an array of numbers entered row by row. ‘The array corresponds to a matrix of numbers and it represents the fun- damental variable type for MATLAB. For the vector and the array, the exp command computes the exponential value for each element. Example 1.1 illustrates the forms of various MATLAB commands The method of entering vector and array variables is shown in Exam- ple 1. ‘The MATLAB program executes commands to perform specified opera- tions. For example, after x is defined, executing the command >>exp(x) causes the function exp in MATLAB’s directory of functions to calculate and display the value of e”. Many functions, such as exp, are called butlt-an functions because they are a fundamental part of the MATLAB program. For these functions, the user cannot modify or even read the MATLAB computer code that performs the operation. Information for built-in functions can be obtained by using the help command with the name of the function during a session. Try the command >>help exp to see the properties of the exp function. Other methods of getting help will be described later in this section. MATLAB can also read and execute programs called M-files that are stored on the computer's disk. The M-file is a text file called a script that contains sequences of MATLAB commands. Contents of the file can be displayed on the computer screen or printed for inspection. The commands in the script are executed when the name of the M-file 1s entered at the keyboard. MATLAB Commands ‘This example demonstrates the use of the three forms of MATLAB com- mands during a MATLAB session. The keystrokes to input commands and the MATLAB responses are reproduced in the accompanying MATLAB session The typed commands and the responses were saved in a diary file on our com- puter’s disk. The diary file was created by the command diary, as explained later. Only the example number was added before the record of the MATLAB session. In the text, statements preceded by >> were typed by the author Lines that begin with a % are comments. ‘The command format compact suppresses blank lines between MATLAB responses to commands. After x is assigned the value 1.0, the exp command computes e*, with the result 2.7183, as expected Since no variable was defined as the result, MATLAB assigns the result to the variable ans. Each calculation without a variable name assignment will be stored in ans Typing >>ans Chapter 1 m= INTRODUCTION will display the last value computed The standard display of numbers shows four digits to the right of the decimal point. MATLAB Script Example 1.1 >>% Sample MATLAB commands >>format compact >>% Assignment and Computataon 0 x= 1 >>exp(x) ans = 2.7183 % Assagn the result to the varaable y >>yzexp(x); >oy os 2.7183 % Computer type and maximum size of arrays >> [ctype maxsize]=computer ctype = POWIN maxsize = 16384 >>quit Next a scalar variable y is defined as €. Notice the semicolon (;) following the assignment of y This suppresses echoing the display of y on the screen when y is computed. The variable y is saved in the workspace and is available any time during the session. Typing y at the MATLAB prompt displays the value. The command computer generates two results, indicating the type of com- puter (ctype) and the maximum size of an array allowed (maxsize). This result is for the student edition of MATLAB executed on a PC running Windows. ‘The maximum size array could contain 16384 elements since this script was ex- ecuted using a Student Edition of MATLAB. The restriction to 16384 locations for variables does not apply to the professional version of MATLAB Using the professional version on another computer yielded maxsize 68,435,455. The variables x and y and the variables ctype and maxsize are saved during the current session only. After the quit command, the variables are removed from the workspace and the MATLAB session is finished o Example 1.1 used only built-in MATLAB functions and comments by the author during an interactive session. As far as the reader is concerned, the difference between the MATLAB built-in functions and M-files is not important at this point. Later in the chapter we will describe MATLAB programs and show how to create M-files. 11 Introduction to MATLAB 7 /SEFUL JENERAL IOMMANDS WHAT IF? Jf you are new to MATLAB, create a diary file for the MATLAB session of Example 1.1. For example, the command >>diary exampi.dir will open a diary file on the disk. Type the commands shown in the script and end the example with the command diary off. Then, display or print the diary file. This simple exercise is to verify that MATLAB is working properly on your computer. If you encounter difficulties, consult the installation instructions in the MATLAB User’s Manual for your computer. ‘There are commands useful for general operations such as displaying m- formation about the workspace or seeking help during a MATLAB session. Several of these are defined in Table 1.2. The MATLAB command help general will list the complete set in the command window. TABLE 1.2 MATLAB general commands Command Action demo Executes the demonstration program type Displays the text of an M-file help Displays the help topics helpdesk Web browser help files from disk or CD-ROM helpwin MATLAB help window what Lists M-files in the working directory Displays the names of files in the working directory Creates a file with a copy of the current MATLAB session Ends the MATLAB session without saving any information The command demo that opens the MATLAB demonstration win! dow has been described previously. The M-file filename.m can be dis- played with the command >>type The command help by itself will display the help topics by category. Ag an example, the command help elfun lists the elementary mathematic! functions available as MATLAB commands. For a particular M-file, the command >>help displays the comment lines (if any) at the beginning of the M-file. Thé command what lists only the M-files in the working directory. The di rectory command dir (directory) lists the names of all the files. Chapter 1 = INTRODUCTION MATLAB VARIABLES CLEXAMPLE 12 A diary file is created as a disk file with the diary command. The diary command was used to create the examples in this book that show MATLAB sessions. It is particularly helpful to specify a diary during debugging and testing of MATLAB programs. The diary contains all of the commands and data input via the keyboard as well as MATLAB’s responses. The command quit terminates the current session. Additional Help Several methods of getting help are available with MATLAB in addition to using the help command. Try typing help help and observe the result. The Help desk uses a Web browser to provide information stored on disk or CD-ROM. Many of the documents use the HyperText Markup Language (HTML) so that links can be made between topics. The com- mand helpwin invokes the MATLAB Help window. The window allows the computer’s mouse to be used to select the help topic category and function of interest. The lookfor command searches through MATLAB files and returns the name and first line of a command containing a keyword. For example, >> lookfor exponential lists several files. Users of the Windows operating system can also get help on a variety of topics by using the Windows Help menu. There are a number of ways to define the variables for MATLAB. The simplest way is to enter data from the keyboard. The variables can be scalars, vectors, arrays (matrices), or strings. Strings are variables con- taining text in the ASCII format. This is a standard format that is used to represent alphanumeric characters for input and display. Naming Variables MATLAB variables can contain up to 19 charac- ters, but they must begin with a letter. The remaining characters can be letters, numbers, or underscores. Thus, variables can have any names that are convenient to represent the variables being defined. However, when MATLAB executes, commands and variables are case sensitive to uppercase and lowercase letters. Thus, the variables scalar and Scalar are different variables. MATLAB Variables This example shows an interactive session to define a number of variables by typing in the values. The MATLAB session was recorded on a disk file using the diary command and the diary file that resulted is reproduced as the accompanying MATLAB session. In the session, we define the values of a scalar named “scalar,” a vector named “vector,” and a matrix named “array.” After the definition of a variable is entered, MATLAB echoes (displays) the values as shown, since the statement does not end with a semicolon. The command quit ends the session. 11 Introduction to MATLAB 9 MATLAB Script mm Example 1.2 >>% MATLAB Varzables >>format compact >escalar-3.5 scalar 3.5000 >evector=[1 2 2 4 1] vector = 1 2 2 4 42 >>array=[1 1 3;3 4.0 2;1 5 1] array = . 7 3 3 4 - 1 5 1 >>quit a WHAT IF? ‘Try the command exp with scalar, vector, and array variables, respectively, and compare the result. Does the command wor| as you expected? Variables in the Workspace The important commands that gover the manipulation of variables in the workspace are defined in Table 1. TABLE 1.3 MATLAB commands for variables Command Action clear Clears the variables in the workspace save Saves variables in a file load Loads variables from a file whos Lists the variables in the workspace and their size S| 1 ‘The clear command deletes any variables in the current workspace, Before exiting MATLAB, variables in the workspace may be saved in 4 file with the command >>save which allows the same variables to be used in a later MATLAB sessiog, The load command in the form >>load reloads the variables during a subsequent session. The command whos| lists the variables in the current workspace and defines their size. In Example 1.2, vector has size 1 x 5 and array has size 3 x 3. | { \ Chapter 1 INTRODUCTION| COEXAMPLE 1.3 String Variables A string variable contains readable text used for prompting for input data and labeling screen displays of data as well as creating special commands. Such variables are sometimes called strings or simply tezt for simplicity, A string variable must be input as ’’, and must be enclosed by single apostrophes. Commands in Table 1.4 are useful for the display and evaluation of strings. TABLE 1.4 MATLAB commands for strings Command _ Action disp Displays text or variables eval Evaluates the text in a string fprintf _Displays a string on the screen Text and the results of computations can be shown on the screen using the display command disp. The eval evaluates a text string and interprets it as a MATLAB command or a value. The fprintf and disp commands allow screen display of text and data. They are important for prompting the user or explaining the data displayed. The use of these commands is demonstrated later in the chapter. MATLAB eval Example (Optional) In some problems, it is convenient to define functions and values to be text strings, as shown in the accompanying MATLAB session, The use of the eval command allows these text strings to be executed as MATLAB commands As an example, the MATLAB script using string variables defines the variable £1 to be the string exp(x). The numerical values are computed if x is defined and the eval command 1s executed with £1 as argument. In this session, the function e* was first evaluated using eval at three points defined by the array variable x. The command y-exp(x) accomplishes the same result, However, if x is changed, eval can be used to compute the new values without retyping the function. The variable x can be a scalar, vector, or an array in subsequent definitions, as shown when x is redefined as a, scalar in the script. MATLAB Script Example 1.3 >>4 Use of Strings and eval >>f1=’exp(x)’ % Define a string function fi= exp(x) >ex=[1 2 3] xs 11 Introduction to MATLAB. n 1 2003 >>eval (£1) % Compute the results ans = 2.7183 7.3891 20.0855 >> y=exp(x) % Compute the exponential without eval y* 2.7183 7.3891 20.0855 >>h >>% Redefine x to be a scalar variable >>x=0.5 x 0 5000 >>eval (£1) ans = ! 1.6487 The command eval is better employed when a complicated foal is to be repeatedly evaluated during a MATLAB session. Another Use of eval (Optional) ‘The accompanying MATLAB session shows the definition of a polynomig as a string and evaluation of the polynomial at several points. The polynomig is f(x) = 2° — 152°. (LY MATLAB Script Example 1.4 >>% Defane a polynomial function as a string >of: x75 - 15#x73? f2= x75 - 15#x°3 >>x=3 % Compute a value Ae 3 >>eval (£2) ans = 162 >>x=-3 % Compute another value x= “3 >>eval (£2) ans = 162 After the polynomial is defined as the MATLAB variable £2, the command eval computes the result that f(3) = —162 and f(—3) = 162. Notice that once the function is defined as a string in the script, it does not have to be retyped during the session. In MATLAB, a text string is called Chapter 1 = INTRODUCTION INPUT AND CREATION OF DATA CLEXAMPLE 1.5 ‘a macro if it can be executed by the eval command. Macros are often useful to pass function names to function files, as will be demonstrated in several examples in later chapters. Qo In addition to keyboard input of data, there are other commands to gen- erate data values that may be more convenient, as listed in Table 1.5. TABLE 1.5 MATLAB commands for input Command Action load Loads variables from a file input Inputs the data to an M-file The load command was discussed earlier. The input command can be used to input numerical data or text strings. It is usually used in an M-file to input data, from the keyboard. This is particularly useful when the same M-file is to process various data values. MATLAB M-file Example ‘The accompanying MATLAB script shows an M-file program to evaluate @ function. This file was created with a text editor, as described later in the section on programming. The file is stored on the disk included with this textbook as file EX1-5.M Before the M-file is executed, it 1s displayed with the type command. In the script, the function being evaluated is y=axe?*—-30xe?* where a and ¢ are variables to be specified when the M-file executes. The purpose of writing this M-file is to rerun it with different values of a and t. As ‘a specific example, a = 2 and ¢ = 1 were input from the keyboard as the M-file was executed The file is executed by the command >>exi5 which causes line-by-line execution of the commands in the file, just as if they were typed at the keyboard. The fprintf commands are used to explain the purpose of the M-file and to display the results. The \n in the fprintf command causes a line to be skipped in the display Note the single apostrophes enclosing the text of the command; quotation marks are not legal MATLAB delimiters for text. The first two input statements prompt the user to input the numerical values of a and ¢, respectively The program then displays the complete function y using the numerical values for a and t This is another use of the fprintf to display both text and numerical values. The term %g indicates that the values 11 Introduction to MATLAB 13 are to be displayed as either decimal values or in scientific notation. The most appropriate format 1s determmed by MATLAB according to the size of the number, as discussed further in Chapter 2 MATLAB Si Example 1.5 >>format compact ‘ >>type ext % N-fle (EX1_5.M) to evaluate the function y= awexp(-1.2t) - 3.0*exp(-2t) % INPUT. Coefficrent a and tame t % OUTPUT: y(t) displayed fprantf(’Compute y= a*exp(-1.24t) - 3.0*exp(-24t) \n’) asinput (’Coefficient a, a=’); teamput(’Variable t, t= ”) h % Dasplay results fprantf(’\n Function: y=%g*exp(-1.2#*%g)-3.0*exp(-2+%g) \n’,a,t,t) y=atexp(-1.24t) - 3.0*exp(-24t) % End M-file >>Y% MATLAB session to execute EX1_5.M >>exi_b Compute y= axexp(-1.2#t) - 3.0#exp(-2*t) Coefficient a, a= 2 Varzable t, Function: ye 0.1964 >>quat 14 flops. exp (-1.2#1)-3. OFexp(-2#1) In the script, the parameter flops gives the approximate number of mathemd ical operations to compute the function. WHAT IF? Suppose you wish to use the M-file in Example 1.5, perhaps with a modified function such as y= axe? —3.0 x e SM, The M-file is stored on the disk accompanying this textbook as file EX1.5.M. Simply transfer the M-file to a directory on your computer's: disk and modify it with a text editor. It is recommended that you save, the modified file with a new name to preserve the original. Then execut it with MATLAB. Chapter 1m INTRODUCTION 1.2 [2] MATLAB COMMANDS FOR DISPLAY AND PLOTTING DISPLAY OF DATA CLEXAMPLE 16 MATLAB commands are available for displaying and plotting data. The disp command can be used to annotate displayed results and thus im- prove the appearance and readability of the output. MATLAB also has a powerful graphics capability useful for engineering and scientific appli- cations. ‘Typing the name of a variable at the MATLAB prompt will cause the name of the variable and its value or values to be displayed. Other com- mands used for display of data are listed in Table 1.6. TABLE 1.6 MATLAB commands for display or clearing Command _ Action ans Displays the results of a calculation cle Clears the command window clear Clears the workspace variables disp Displays text or a variable without displaying the name The ans command was discussed in Example 1.1. This command is used to display the result of a calculation that is not associated with a named variable. The cle command is issued to remove clutter from the screen before beginning a new set of calculations. To free memory space, clear can be used to remove all the current variables from memory. Use of the disp command will be demonstrated in Example 1.6. Default Values When MATLAB begins execution, the program uses default values for various parameters. These values can generally be changed using appropriate MATLAB commands. As an example, MAT- LAB uses the format short as its default format for display of numbers. This typically displays four decimal digits to the right of the decimal point unless the value is an exact integer. Other formats are set with the format command, as described in Chapter 2. MATLAB Display Example Consider the results of acceleration tests on a sports car, as shown in the accompanying table The time in seconds represents the time from a stop to 12 MATLAB Commands for Display and Plotting 15 reach the final speed in miles per hour in the specified gear. The MATLAB script shows how to enter the data and display the values in columns wit headings Gear Teme (3) Final Speed (ma/h) 1 2.5 30 2 10.0 55 3 21.0 78 4 45.0 100 5 90.0 120 MATLAB Script Example 1.6 >>type ext_é % EXi_6.M Display a table with Heading test=[1 2.5 30 2 10.0 55 3 21.0 78 445 100 590 120]; disp(? Acceleration Tests ’) disp(’ Gear Tame(s) Final Speed(m1/h)’) disp(test) % End M-file >>exi_é Acceleration Tests Gear Time(s) Fanal Speed(m2/h) 1.0000 2.5000 30.0000 2.0000 10.0000 55.0000 3.0000 21.0000 78.0000 4.0000 45.0000 100.0000 5.0000 90.0000 120.0000 >>quit The script shows the diary file for the execution of the M-file named EX1.6 M The array is first defined row by row by entering a CR after each row. Then the disp commands display the table title, column headings, and data, Tht spacing of the column headings was determined with a bit of trial and error Ga WHAT IF? Suppose you wish to store the test data on disk. Execute; the M-file and save the numbers in array test with the command >>save test 1 which creates the disk file TEST.MAT. Then, modify EX1_6.M to use the load command and save the new version as EX1-6a.M. Execute the new script to verify the results. Also, you may wish to add a few more comments to describe the script. Chapter 1 m= INTRODUCTION GRAPHICS MATLAB is capable of plotting both two-dimensional (2D) functions f(«,y) and three-dimensional (3D) functions f(z, y, 2). In fact, for some applications the ability to plot complicated functions is one of the most powerful aspects of MATLAB. Executing the demo command allows the user to choose a number of graphics programs that illustrate MATLAB’s graphics capability. The commands help graphics and help graph2d will list the complete set of commands for general graphics and 2D plots. The plot command automatically scales the data for a 2D plot and draws x and y axes. Other commands are available to refine the plot and add axes, labels, and a title. Various commands useful for plotting results are listed in Table 1.7. TABLE 1.7 MATLAB commands for graphics Command Action Plotting: figure Creates a figure window plot Plots a linear x-y graph subplot Divides the graphics window for multiple plots clf Clears a figure whitebg — Changes background to white hold Holds the plot on the screen fplot Plots e function defined by a string Labeling: axis Allows manual scaling of axes grid ‘Adds grid lines to a plot title Adds a title to a plot xlabel_ Adds a label to x-axis ylabel Adds a label to y-axis Data: linspace Creates linearly spaced values logspace Creates logarithmically spaced values Printing: print Prints the current figure widow The MATLAB command window previously discussed represents a tect screen in which commands are entered and results are displayed. MATLAB also has a graphics window for the display of plotted data. Figures are created in a graphics window by various plotting commands. The command figure(n) creates a numbered blank figure window with number n. It is possible to create up to four independent plots in the same graph- ics screen with the subplot command. The command clf clears the cur- rent figure from the graph window. To reverse the background from its 2 MATLAB Commands for Display and Plotti Ww ‘JEXAMPLE 17 default black color, the command whitebg is used to create a white back- ground. This is useful for printing the figure with black lines on a white, background. The command actually “toggles” the background color, so that two consecutive executions of the whitebg command change the background back to black. ! ‘Multiple plots can be placed on the same screen with the hold com- mand. However, the plot will use the already established scales for thd axes. The command fplot is useful to plot the graph of a function of om variable defined as a string variable. Thus, a function such as ’sin(x) can be plotted over a defined interval of x. The fplot command auto matically determines the abscissa points in x to evaluate the functiot according to the variations of the function. The commands linspace and logspace create vectors of points fo function evaluation or plotting. Points generated by linspace are linearly spaced over a specified interval. For example, the command >>x = linspace(0,10,11) generates 11 points between 0 and 10 in the vector x. The command logspace creates logarithmically spaced points. A figure can be printed using a printer attached to the computer sys! tem. Alternatively, the figure can be saved as a disk file for later printin, or display. The print command has various options that define the out put device and the format of the figure if saved on disk. The MATLAI figures in this text were saved in Encapsulated PostScript (EPS) form an then incorporated in the text during printing. MATLAB Graphics Example Consider plotting the function y(t) = 28 sin (ut + 5) (12 for t > 0 Since the sin function varies between —1 and 1, we expect the functi to vary at most between +2/3/9 = +0 38. Of course, the exponential term. “4 drive the function tb zero rapidly. When t = 1, the value 1s below 0.02 Thug a plotting range in t between 0 and 1.5 seems reasonable with a vertical ax{ range between 40.5. The M-file EX1_7 M plots the function using the value w= 4Vv¥3 for the radian frequency of the sine wave Using MATLAB’s plot command, we have only to define a sequence + values of y(t) versus t and not be concerned with the horizontal and vertic. scales on the resulting graph unless the autoscaling ranges are not appropriat{ for the problem. However, even if autoscaling is used, the calculations of thi range of data by hand ate useful for checking the result approximately to ensuri that there were no blunders in defining the equation for the MATLAB program Chapter 1 m INTRODUCTION MATLAB Script Example 1.7 % EX1_7.M Define t values (151 points, 0.0, 0.01, ...) and % plot y(t)=(2*sqrt (3) /9)*exp(-4et) .*san(w+t + pa/3) t=[0:.01 1.5]; % Defane y(t) we 4esqrt(3); % Fixed frequency Qesqrt(3)/9)sexp(-4et).xsin(wet + p1/3); 4 Plot the results with a grid clf % Clear previous figures plot(t,y) grid title(’Plottang example’) xlabel(’Time t?) ylabel(y(t)?) egend([’\omega=’ znum2str(w),’ radians/sec’]) Potting examplo 095; —— _ 06.9282 radians/sed| oa] 05} art 02| ons 005 a 05 1 Tmet FIGURE 1.2 MATLAB plot ‘The vector of t values is first defined with an assignment statement of the form [to: Ae ty], where to is the starting pomt, At is the increment, and ty is the final value. In the MATLAB workspace, t is actually a 1 x 151 row vector. The colon (:) separating the arguments 1s called an operator when used in this manner to create a vector of values. ‘The function y in the script 1s defined using MATLAB’s built in sqrt, exp, and sin functions. The definition of y illustrates several points about 12 MATLAB Commands for Display and Plotting 19 MATLAB's formats for equations. Multiplications are indicated by the * be- tween operands and the variable pi is the value x The period (.) between the exponential and sine functions 1s an operator that is necessary because the intent is to perform element-by-element multiplication. More generally, if A and B are arrays with the same dimensions, then A. + B yields the array whose elements are the products of the individual elements of A and B. This use of the period (.) operator is described in more detail later. ‘The plot command creates a graph of y(t) versus ¢, and grid overlays a rectangular grid, as shown in Figure 1.2, The commands xlabel and ylabel are used in the script to annotate the axes. The command legend puts the frequency value on the graph by using the } num2str command, which converts a number to an ASCII string for display’. ‘The notation for w follows that for Greek letters used in the word processing program IsTRX. im) WHAT IF? Suppose you wish to determine the zero crossings of the function plotted in Figure 1.2. The first value appears to be near # = 0.3. A closer estimate can be obtained by typing the command , zoom on. Pressing the left mouse button changes the axes limits of a figure on the computer screen by a factor of two. By zooming in on the region near the zero crossing, an accuracy of several decimal places in defining y, where y(t) ~ 0, should be possible. Don’t forget to turn the zoom feature off with zoom off after viewing the graph. Otherwise, zoom will be active during the entire MATLAB session. The command [x,y]=ginput can be used to get the numerical values from a graph. Using the mouse, the command returns the x and y coordinates of the points selected on the graph shown on the computer screen, Refer to the MATLAB User’s Manual for more details. Suppose w in Equation 1.2 is to be a variable parameter. Plot the function with various values of w on the same figure using the hold command from Table 1.7. Three-Dimensional Plotting MATLAB also contains plotting com- mands to create surface and 3D plots. The command help graph3d) displays the numerous options. Figure 1.3 shows the plot and contour lines for the function 2= flay =v +y? +1, which represents a surface in xyz-space. The contour lines shown in the: zy-plane in this case are circles. They indicate the shape of the curves where the function is constant and show the locus of points Flay)=e, f(ery) =a, legend will not work for versions of MATLAB earher than 5.0. Chapter 1. m INTRODUCTION for various choices of the constants c1,¢2,-.. defining each of the curves Studying these level curves often provides a better understanding of the function than a plot of the surface itself. a4 FIGURE 1.3 Plot of surface z = y/z? + y?+1 and contour lines Only a few MATLAB commands are necessary to create Figure 1.3, as the accompanying MATLAB script shows. MATLAB Script (x, y] =meshgrid! [ z=sqrt(x.~2+y.72+1); meshc(x,y,z); The meshgrid command defines the range of x and y on a square grid. The function z = f(z, y) is defined for plotting using the sqrt com- mand. Notice that the period operator (.) is used with the power operator (~) to square each element of the arrays. The command meshe plots the function and the contour lines. These commands will be used extensively to represent functions of interest in vector calculus, as presented in later chapters. Colors Unfortunately, a textbook with black and white figures cannot. demonstrate the use of colors when creating MATLAB figures. The colors can be used for various purposes, such as differentiating between several graphs in one figure. However, there are more sophisticated uses of colors, particularly in plots of 3D functions. For example, different colors can be 12 MATLAB Commands for Display and Plotting a used to represent different heights in a contour plot. The MATLAB User’: Guide describes such uses of colors. 3 BY CREATING MATLAB PROGRAMS oe ILES AND ACTIONS. ‘TLAB fuctions A MATLAB program, often called a script, consists of a number of mart LAB statements designed to solve an engineering, mathematical, or sci- entific problem. The simplest statements contain one or more MATLAB commands. As we have seen, the MATLAB commands refer to built-in functions, such as exp, for calculation and more general commands that are provided as M-files with MATLAB. In addition to the commands provided as part of MATLAB, the user can define unique sequences of MATLAB commands and combine them into a script as in Example 1.5. The script can be stored on disk as an M-file. The complete program typically includes comments, statements for input and output of data, including graphical output, as well as the executable statements to perform calculations. This section explains the MATLAB M-files and functions. MATLAB is often used in a command-driven mode called the wmmedt- ate mode. When single-line commands are entered during an interactive session, MATLAB processes the statement and displays the results im- mediately. The MATLAB examples in Example 1.1 through Example 1.4 are of this type. Once the MATLAB session is completed, the commands, are no longer available, although they may be saved in a diary file for} viewing, but not for execution. If a sequence of commands is to be used repeatedly, perhaps witht different data values, the MATLAB commands can be saved as a disk file called an M-file. An M-file may contain a complete MATLAB script for execution or a function. The previous MATLAB scripts, including the M-files of Example 1.5 and Example 1.6, have used only the built- in MATLAB functions and commands. A user-defined function must be created in a special way that is defined by the conventions of MATLAB. A function file consists of sequences of MATLAB statements that serve to add a new function to the existing set provided by MATLAB. A func- tion is stored on the disk as an M-file which typically provides a specific * numerical result as the function is called. A function file must begin with the word function as the first exe- cutable statement of the file. Values may be passed to the function for Chapter 1 @ INTRODUCTION manipulation and output values can be returned. The format of the first statement for a function named fname is of the form function [outi,out2,...]=fname(an1,in2,...) where the input variables are placed within parentheses and outputs are enclosed in square brackets if there is more than one. This function exe- cutes when it is called by name as fname in a MATLAB session or M-file. One important distinction between variables defined in a script and those in a function is that the function’s variables are local variables. These local variables exist only during the execution of the function and do not appear in the MATLAB workspace. Cexametei8 MATLAB Function Example Example 1 7 contained the MATLAB script to compute values of the equa- tion ava ® u(t) = Wet sin (av e+ 2) and to plot the result If the equation is to be used in various MATLAB programs, t would be better to create a function that evaluates the expression. The accompanying MATLAB script shows the M-file of Example 1.7 rewritten to call the function clxfunct. ‘The function is also displayed in the second script. This function is con- tained in a disk file CLXFUNCT.M. It is necessary to create the M-file that calls the function separately from the function because each must be stored in a different disk file The plotting statements from Example 1.7 could be added to the MATLAB script to produce the plot shown in Figure 1.2. Notice that the variable names within the function are not related to the names used in the calling M-file. Because of this, a programmer writing an M-file that calls the function is not restricted to using specific variable names. ‘The variables passed between the function and M-file must agree as to type, such as scalar or array. MATLAB Script Example 1.8 % EX1_8.M Plot x(t) defaned by function clxfunct(t) t=[0:.01:1.5]5 % Define t values % Call function x=clxfunct(t) 5 % Plot the results with a grid plot (t,x) grad % End £11e\nopagebreak ‘The function must be stored in the disk file CLXFUNCT.M. The contents of the file are shown in the next script. It is generally good practice to define the function call and the results in the prologue comments of the function, These comments appear if the help command is used with the function name. The statements in the function are executed when the function is called by another M-file such as EX1_8.M. 13 Creating MATLAB Programs 2B MATLAB Script function xvalues=clxfunct (tvalues) % CLXFUNCT Function for Example 1.8 % Call: xvalues=clxfunct(tvalues) to compute function % xvalues=(2xsqrt(3)/9)*exp(-4*tvalues) x sin(4*sqrt (3) *tvalues+ p1/3) xvalues=(2+sqrt (3)/9) *exp(-4+tvalues) .*sin(4*sqrt(3)*tvalues + pi/3); % End function Qo, Subfunctions Function M-files may contain more than one function. The first function is called the primary function and the entire M-file is called by the primary function’s name. Other functions beginning with a function command are appended below the first function in the M-file. | These subfunctions can be called from the primary function only. MATLAB itself contains a text editor program, but any editor on the computer system can be specified to create M-files. An M-file can be created using any text editor or word processor that allows files to be| saved in the ASCII format. The files written using a text editor are called ASCII files or text files since they contain only standard text characters, such as letters, numbers, and a few special characters, including Carriage Return to end a line and Line Feed to create a blank line. Word processors normally allow the user to insert a number of for- matting commands, such as a command to italicize a word. These special commands are not understood by MATLAB. Each statement in a MAT- LAB program must end with a Carriage Return, so the word processing capability to wrap text from line to line must not be used. Also, if a word processor is used to create a program, the file must be saved as an ASCII‘ file. This is an option in most popular word processors. The editor provided with MATLAB is not simply a text editor as is indicated by its name as the M-file Editor/Debugger because it can be used to create M-files (editor) as well as debug the completed files. The Editor/Debugger allows breakpoints to be set in the program and other operations such as single stepping through an M-file. Debugging methods and commands are described in more detail later in this section. Chapter 1. m INTRODUCTION ARITHMETIC, LOGICAL, RELATIONAL, AND SPECIAL OPERATORS [+] MATLAB PROGRAMMING LANGUAGE For mathematical programs, the primary characteristics of a high-level programming language, such as C, FORTRAN, or MATLAB, are de fined by the allowed data types and the operations involving the data Other features of a language include the control statements and the in- put/output (I/O) capability, as well as any special operations or com- mands. MATLAB is particularly suited for vector and matrix operations This makes the language convenient for solving problems in applied math- ematics or physics. Moreover, MATLAB contains a number of special functions that can be used by a programmer to create powerful algorithms without programming many of the mathematical functions. Table 1.8 liste a few of the characteristics and examples of commands of the MATLAB language. A selection of these commands is presented in this section. Example I/O commands were discussed previously. TABLE 1.8 MATLAB program characteristics Classification Examples Data types Scalars, vectors, matrices, strings, and special values Operators: Arithmetic Ne Logical & | ~ all, any, fin Relational sects aie aa a Special Heiss Functions Mathematics, signal processing, and symbolic math Program statements: Control fow if, for, while, break Debugging _ echo on, pause, keyboard, dbtype Evaluation Timing commands such as clock, etime, and profile yo Commands to input data, create graphics, and print MATLAB contains a number of operators for ordinary arithmetic, such as + and —, raising to a power (~), and logical operations representing AND (&), OR ( | ), and NOT (“). However, these operators not only apply to single variables but such operators will also work on vectors and matrices when the operation is valid. The relational operators are used to compare values or elements of arrays. If the relationship is true, the result is a logical variable whose 14 MATLAB Programming Language 25 value is one. Otherwise, the value is zero if the relationship is false. Thus, the statement as=b is testing the variables for equality. These operators are used frequently with other commands such as all, any, or find which test arrays for logical conditions. For example, assume the vector V contains numerical , values that are all different. The commands >> peakindx=find (V==max(V)) >> peakV=V(peakindx) find the location of the maximum value and assign that value to the variable peakV. In MATLAB, the expression V(n) indicates the nth item in the vector so that the value of peakindx selects the location of the maximum value in the vector. This variable is an integer called an index that locates a value in a vector. Notice that there is no need to specify the length of the vector as would be necessary in some high-level languages. ‘You may care to test the commands with a vector of values such as V=[1.1,3.4,-2,7,1,8]. What do the commands return if the vector is, V=[1,0,1,0,0,1]? Hint: MATLAB creates a scalar variable, a vector, | or an array automatically as needed in a script. In contrast to the relational operator (==), the single equal sign i statements such as x = y indicates an assignment statement that sets one: variable equal to another. Colon, Semicolon, and Period Operators The colon (:), semicolon (;), and period (.) are called operators when used in MATLAB program statements because they cause operations to be performed by MATLAB commands. These versatile operators are not merely convenient but form an essential part of useful and efficient programs. The MATLAB User’s Guide calls the colon operator “one of the most useful operators in MATLAB.” An important use of the colon operator was demonstrated in Example 1.8 by the statement t=[0:.01:4.5] which creates a vector of t values 0.0, 0.01, 0.02,...,1.5. Another use of ' the colon is to designate sequential elements in a vector or an array. For t, the first element of the vector is t(1). Thus, the statement t (1:5) designates the first through the fifth elements of the vector t. As shown in Chapter 3, this operator is vital for matrix operations. Problem 1.12 provides some practice using the colon operator. The semicolon operator has been used in several examples in this chapter. Putting a semicolon at the end of a MATLAB statement pre- vents the display of the results as the statement executes. A semicolon is also used to separate several individual MATLAB statements typed on one line Another application was presented in Example 1.2, where the Chapter 1. = INTRODUCTION STATEMENTS FOR CONTROL FLOW semicolon was used to separate rows of the matrix array defined in that example. Period operators are used primarily to define element-by-element op- erations for arrays. This is the operation desired when the array represents separate values of a function that are stored in an array for convenience. These operators are Ll for element-by-element multiplication, raising to a power, and division, respectively. In element-by-element multiplication and division, the arrays involved must have the same number of elements unless one is a scalar. Chapters 3 and 4 present the use of the mathematical operators when array opera- tions rather than element-by-element operations are intended. WHAT IF? Define two 3 x 3 arrays such as the array in Example 1.2. Call the arrays A and B and compare the results of the operations A*B with A+B and AB with A-B using MATLAB. ‘The commands if, for, and while define decision making structures called control flow statements for the execution of parts of a script based on various conditions. Each of these structures is ended by an end command. The If Command The if is a conditional command that causes follow- ing statements to execute if the given condition is true. For two conditions in a loop, the else command is used and the structure is if-else-end. As an example, assume that A is an array of numbers with m rows and n columns. The script MATLAB Script (m n] = size(A) % Determine size as [rows columns] af AC:,1) 0 % If all the elements of Column 1 are zero B=A(1:m,2 % set B to an m by n-1 array else Bea % BeA af first column of A is nonzero end tests the entries in the first column of A for zero values. If all the values are zero, the columns of A are copied into the array B with the first column deleted. Otherwise, the arrays are set equal. Notice in the indexing of the array A, 1:m refers to the first m rows and 2:n selects the columns starting from the second column. 14 MATLAB Programming Language a Loops Ina program, loops are used to execute a series of statements repetitively. Thus, loops serve to perform the iterative parts of an al gorithm. Several MATLAB commands are available for looping a fixed number of times, as well as looping based on a condition. The for com- mand is used to execute the series of MATLAB statements iteratively. For example, the loop for 1=2:2:6, v(I)=0, end operates on the elements of v with index I=2,4,6. The commands set to zero the values in vector v with even index 2, 4, and 6. The While Command The while command will repeat a series of statements while a given condition is true. The statements will be exe- cuted as long as a logical condition defined by a relational operator is true or a mathematical expression remains nonzero. MATLAB Control Flow Example Consider a function that steadily increases from 0 to 1.0 (monotonically increasing) defined in the vector f. To find the first value that is greater than or equal to 0.5 and copy it to the variable £1, the statements while £(I) < 0.5; I=I+1; end; f1-£(1) could be used. In this program segment, semicolons are used to separate indi- vidual MATLAB statements and also to suppress display of partial results in the while loop. In general, it is not necessary to use explicit looping commands when dealing with arrays. For example, the commands >> kefind(f >=0.5);f1=#(k(1)) will accomplish the same thing as the previously shown while loop. Here k would specify the locations of all the values greater than or equal to 0.5. The accompanying MATLAB script finds the first value of a vector that is greater than or equal to 0.5 or returns £1=0 if no value exists. MATLAB Script Example 1.9 % EX1_9.M Test of While and Break ~ Fund first value >= .5 % Test case f=[0.0,0.2,0.3,0.4,0.5,1.0] £=[0.0,0.2,0.3,0.4,0.5,1.0] 1-0; Tet while £(I) < 0.5 T=1+1 if T>length(t), break, end end af (I <= length(£)), £1=£(1), end A break command can terminate the execution of a for or while loop before completion of the entire looping process This command usually follows Chapter 1. = INTRODUCTION DEBUGGING an if conditional statement to terminate the loop when a specific condition oceurs. ‘The command length computes the number of elements (length) of a one- dimensional array (vector). Thus, the conditional (if) statement in the script tests the index I and causes the loop to end if the index exceeds the length of the vector £. When the script ends, the variable £1 contains either the first. value equal to or greater than 0.5 or zero. The zero value indicates that no value in the vector meets the criterion. Qo WHAT IF? Suppose the vector f in the previously shown while loop or find command does not contain a value greater than or equal to 0.5. You should try this case to show that an error occurs for both methods. The simple script using the break command will stop the looping if all of the values in the vector are less than 0.5. Vectorizing Usually there are several ways in MATLAB to accomplish the same programming task. An important point about the MATLAB programming language is that it is not similar to FORTRAN or C in terms of its treatment of arrays. In general, good MATLAB programmers avoid for loops if MATLAB will create an array with an alternative command or series of statements. The process of creating arrays without loops is called vectorizing. A simple example was shown in Example 1.7, where the statement t=[0:.01:1.5] was used to create a vector of time values, A for loop replacing this statement would be less efficient in terms of execution time. Problem 1.21 requires comparison of the times of execution for vector- izing and looping program segments. Generally speaking, the programs in this textbook were written with clarity rather than efficiency as the primary goal. Therefore, improvements using vectorizing are certainly possible in some examples. The syntax errors in a MATLAB script—such as undefined variables or missing parentheses—will be found when MATLAB evaluates the script. Such errors are displayed in the command window with the line number of the error. The errors that require more effort to find in many cases occur when the M-file script is executing. These errors are called run-time errors. Normally, as a MATLAB script is executed, the commands within the file are not displayed on the screen. The command echo on causes the commands to be displayed for debugging or demonstrations. When it is desired to stop the display of commands, the command echo off is used. 14 MATLAB Programming Language 29 cY OF RAM Several commands are useful to pause the execution of an M-file for debugging or other purposes. The pause command in an M-file causes the execution of a script to stop. This is useful for creating delays to view displays or partial results. Generally, a pause command would be used between graphic displays. Otherwise, the first display is visible only momentarily. When a key is pressed on the keyboard, execution continues. The keyboard command in an M-file will give temporary control to the keyboard. This allows you to execute commands such as whos to interrogate the workspace and to study intermediate results. Typing the command return causes the M-file to continue execution. MATLAB also has a set of debugging commands for more extensive debugging. For example, the command >>dbtype lists the statements in the named M-file with line numbers. The line numbers are often used to set. breakpoints at a certain line in the script. At a breakpoint, control is temporarily returned to the terminal so the user can diagnose the program results that have been calculated up to the statement at the breakpoint. The command dbstop sets a breakpoint and dbcont resumes execution from a breakpoint. For example, the command >>dbstop in at 8 will set a breakpoint at line 8 of the M-file with name filename.m. After the debugging session is complete, the command dbelear is used to clear any breakpoints. The entire debugging command set can be viewed with the command help debug. Note: The debugging capability of the Editor/Debugger provided in MATLAB also allows you to set or clear breakpoints as well as single- step the program. If you are an inexperienced MATLAB user, a little experimenting with this capability will be worthwhile when later debug- ging difficult programs. The MATLAB command clock returns a vector that contains the current time and date as indicated by the computer's time-of-day clock and calen- dar. The time between events in a program could be timed by comparing the values from clock. To calculate the elapsed time, command etime can be used. The sequence of MATLAB commands tstart=clock; < MATLAB commands to be timed > elapset=etime(clock,tstart) sets the variable elapset to the difference in time between tstart and the time elapset is evaluated. Thus, elapset represents the time taken by the MATLAB commands executed between the two clock commands. Chapter 1 # INTRODUCTION ‘The profile command is used to determine the time spent in a MAT- LAB function, and the option report provides an analysis line by line by giving the percentage of time spent on each line. After profiling to determine which functions or statements require the most time, it may be possible to improve the performance by modifying the algorithm or rewriting certain statements to make them more efficient. Exercises You should now be able to do all the Reinforcement Exer- cises at the end of the chapter. Try using the debugging commands of MATLAB to find the errors if your program is not executing properly. PROBLEM SOLVING AND PROGRAMMING (OPTIONAL) PROBLEM DEFINITION It is perhaps presumptuous to discuss problem solving with readers study- ing advanced mathematics, since problem solving is a key part of all pre- vious courses in engineering, mathematics, and physics. However, our present purpose is to integrate problem solving by traditional methods with MATLAB solutions. Therefore, problem solving and programming are two skills that must be combined. The basic approach is as follows: 1. Define the problem precisely in terms of the input and output variables and the algorithm to be used. 2. Design the MATLAB program and various test cases. 3. Create and debug the program. 4. Test the program thoroughly. Each of these steps is discussed in detail. The first step in problem solving is to define the problem in a mathe- matical form that is amenable to computer solution. For example, an analysis of a physical problem system might lead to the conclusion that a quadratic equation of the form ax? +be+e=0 (1.3) must be solved for the variable x with a, b, and c known constants. This might appear to define the problem adequately for computer solution; that is, find the roots of the equation and display these values of x. In fact, the physical problem may dictate that x can vary over only a certain interval of values. If this is the case, the specification of the problem must include any constraints on the solution. As an example, a constraint for 15 Problem Solving and Programming (Optional) ali the solution of the quadratic equation might be that only positive values of x would be allowed. The next step is to define a solution method using the equations and constraints from the statement of the problem. This should include @ definition of the input and output information. For the quadratic equation example, a, b, and ¢ are input variables and z is the output variable. In more complicated situations, the output might be a graph including a display of the input variables themselves. For numerical values, the data formats should also be defined. For example, the output values could be ‘ represented as numbers in scientific notation with four decimal places of accuracy. The purpose of specifying the inputs and outputs is to separate the data from the algorithm. The way the input values are manipulated to determine the output values constitutes the algortthm used to solve the problem. Selection of the algorithm can be one of the most difficult and involved aspects of the problem-solving process. The accuracy and efficiency of a program depends on the algorithm chosen, which in turn may depend on the range of data values involved. The efficiency of a computer algorithm can be defined in terms of its speed of execution or its use of memory and disk storage. Thus, there can be a dependency on the programming language and even the computer used. Considering these factors, there is rarely one algorithm for solution of a given problem. One approach to solve the quadratic Equation 1.3 is to apply the quadratic formula for x as + Vt? ~4ac a (14) since we can write an explicit analytical solution. For computer solution, it is convenient to separate the input variables, the algorithm, and the output variables as shown in Figure 1.4. FIGURE 1.4 Input varables (a,b,c), algorithm, and output variable (x) for the quadratic formula Chapter 1 # INTRODUCTION PROGRAMMING CONSIDERA- TIONS Without further information, such as a definition of the accuracy required for x, it is not possible to define the best algorithm to solve an equation even as simple as a quadratic one. In fact, a simple formulation of the solution, as in Equation 1.4, has a number of potential drawbacks, For example, what should the program do if a = 0? Any algorithm should have provisions for special data values that cause mathematical errors. In conclusion, a certain amount of study and experimentation is re- quired to define an acceptable method of solution because of the various factors that affect the correctness and efficiency of an algorithm. WHAT IF? Consider the solution to Equation 1.3 for arbitrary values of a, b, and c. What error provisions would you incorporate? Problem 1.17 explores the quadratic equation further. Once a problem to be solved by computer is defined in terms of data input and output, algorithm, and test cases, it is necessary to create a computer program that implements the algorithm. The aspects to be considered include 1. Program style, 2. Design, 3. Debugging, 4, Testing. These general programming aspects can be discussed independently of the specific problem to be solved. Notice that program style is first in the list of programming issues. Style refers mainly to the readability of the program and its general struc- ture. Program design covers many factors, such as modularity, efficiency, and the provisions for debugging and testing. However, debugging and testing are so important in computer problem solving that they are con- sidered separately here. All these aspects of programming are affected by the intended use for a program. A commercial program, such as MATLAB itself, that will be widely used but not modified or even read in its C-language form by the user obviously should be as efficient as possible. On the other hand, efficiency in speed of execution may not be an important consideration for a scientific program used once to solve a specific problem. However, the program should be easy to read, debug, and test to save time for the programmer. Thus, programming always has subjective aspects, but there are certain guidelines developed by experienced programmers that should be followed in any programming project. Of course, the overriding concern is correctness of a program. Most of the guidelines have as their underlying purpose the creation of correct programs. 15 Problem Solving and Programming (Optional) 33 Program Style The style of a program is defined by the type of com ments, variable names, indentation, and similar techniques to improve readability. For example, each program should begin with preamble com ments. These describe what the program does and how to use it if any special instructions are necessary. Then, input and output data should be defined, as well as any other program or function called by the pro- gram. Any errors that are detected and the results of encountering an : error should be described. Also, include the author’s name and the date if the program is to be used by others. Many ezplanatory comments should be included to explain parts of the program that do not perform obvious functions. Such comments help any reader of the program, but, most importantly, they aid the program- ! mer in understanding and modifying the program. One caveat is that these comments should explain what the program does, not what thei computer instructions do. The instructions are better explained in the} User’s Guide for the programming language rather than in the program. Variable names should be chosen to reflect the programming, math- ematical, or scientific quantities being represented. The programming variables include array indices and loop counters in repetitive segments of the program. In summary, liberal use of comments and careful selection of variable names can greatly enhance the readability of a program. MATLAB Program Example The accompanying MATLAB script shows a possible preamble to a function | that solves the quadratic equation ax” + br +c = 0 using the quadratic formula ’ solution of Equation 1.4. MATLAB Script function [x,Eflag] = quadrat(a,b,c) Function to solve the quadratic equation ax"2+bx+c=0 CALL: (x,Eflag]=quadrat (a,b,c) INPUTS: a, b, and c coefficients as real numbers OUTPUTS: x, a vector of the solutions as real or complex numbers Eflag, error condition 1f a=b=0, Eflag=i since x 1s not defined otherwise Eflag=0 ALGORITHM: The quadratic formula 1s used in the form (1) x = -b/2a +/- sqrt(b"2-4ac)/2a, if a not = 0; (2) x = -c/b, 1f a =0 and b not = 0 nh _ Eflag-0; % Assume result 1s correct % (Program statements start here) In the preamble, the calling method is specified and the input variables are’ named and their type defined. Here the vanables are specified as real numbers, Chapter 1. INTRODUCTION although MATLAB would allow complex numbers as variables. The solution to be output is defined as a vector x that would contain two entries in the general case A variable usually called an error flag by programmers, is defined. This variable (Eflag) indicates the correctness of the computation based on the error criteria used in the function. In this function, the initial value of Eflag is zero. An error occurs if the coefficients a and b both are zero, in which case the error variable has the value 1 rather than zero. Another program using this M-file should check the value of the error flag after execution and take appropriate action if the value is not zero. ‘The description of the algorithm is simple in this example. According to the description of the algorithm, the equation brt+e=0 is also solved. This allows a = 0 as a legitimate value for the leading coefficient of the quadratic equation. However, no mention is made of the accuracy of the solution that is achieved using the quadratic equation when a # 0. The results of Problem 1.17 indicate that this formulation may lose accuracy for certain values of the coefficients. A good numerical algorithm should specify the accuracy expected for the expected range of the input variables if the numerical value of the computed solution can be inaccurate in some cases. o WHAT IF? Suppose you wish to have a MATLAB function to solve the quadratic equation. Create and test a function defined by the statement function [x,Eflag] = quadrat (a,b,c) where the input variables are the coefficients of the quadratic equation and the output variables are the solution and the error flag described in Example 1.10. Our disk file QUADRAT.M is an example function. Program Design There are several important issues in program design after the problem solution is well defined and ready for programming. One decision is whether the program will be general or very specific. Generality in a program refers to the capability of the program to solve a class of similar problems using variables, rather than a specific problem with fixed numerical values. For example, a program to solve the equation 327 + 22 + 4 = 0 is obviously specific. A more general program solves ar?+bz +c = 0, where a, b, and ¢ are variables that are input each time the program executes. Similarly, a program that performs 20 iterations to produce a result is less general than one that performs N iterations, where N is increased in the program until a certain accuracy in the solution is reached. If the program is to be used to solve a variety of similar problems, designing for generality will save time if modification of the program is to be avoided to solve each specific problem. 15 Problem Solving and Programming (Optional) 35 Complexity Another aspect to consider is the reduction in complexity of a program after a preliminary design has been created. Reading, de- bugging, and testing the program will be easier if the program is divided into independent segments that perform specific tasks. If possible, avoid programming constructs that “jump around” (transfer control) from seg- ment to segment. Such transfers make the flow of the program difficult to follow for debugging, Efficiency It is possible that following the programming guidelines just discussed can increase the size of the program and possibly increase the time of execution. However, experienced programmers also know that program efficiency can be improved after a correct program is produced. Thus, attempts to speed up the program should be made after the pro- gram is made correct, readable, general, and easy to debug and test. Generally speaking, increasing the efficiency means refining segments of the program to execute faster or to use less storage. Since most high-level languages have commands to allow program segments to be timed, program segments that seem to be using excessive amounts of execution time can be found. Then, improving the program segment might involve changing the programming commands or even the algorithm. Debugging Debugging is the art of locating and correcting errors in a program. These errors, often called bugs, may arise from a number of sources, including those listed in Table 1.9. TABLE 1.9 Program error sources Cause Type of Error Misunderstanding of the Syntax error or programming language _ calculation error Data error Incorrect inputs Error in algorithm Incorrect outputs In many cases, MATLAB will discover and indicate a syntax error, ' such as the improper termination of a loop or an undefined variable used * in a program. However, other errors resulting from a misunderstanding of a command or a sequence of instructions may not cause MATLAB to indicate the cause of an error. If a command is not completely understood, it is best to test the command with simple examples. This is particularly important with a program, such as MATLAB, that has a number of very sophisticated commands. The eval command discussed previously is one example. Errors occurring because of incorrect data may not be detected by MATLAB. For example, using a value in degrees rather than radians in Chapter 1 = INTRODUCTION the sin command would cause a numerical error in the expected result but not a syntax error, since MATLAB would use the input value in radians. Adequate program testing should uncover such errors. ‘The algorithm or logic of the program may be in error if a program or program segment is free of the previously discussed bugs but produces incorrect answers. The logec of a program here means the paths taken as. the program executes. A logic error could result from taking the wrong path after a decision or failure to consider one or more conditions, such as not testing for a negative value if a negative result would cause an error. Always check for every case, even if you are “sure” that a certain case could never occur. An input data error might cause an unexpected condition. One way to catch logic errors is to create a flowchart before starting the coded program and then to trace the proposed program logic with various conditions according to the flowchart. An improper algorithm may solve the problem incorrectly, or it may solve certain special cases but not the entire problem. When the algorithm uses an iterative process, there is always a danger of numerical errors. In some cases, the method may produce a solution that diverges rather than converges to the expected solution. Some experimentation with different. algorithms is often required to find a suitable method to solve a particular problem. Testing Testing a program is typically considered an art, particularly by novice programmers. However, an experienced problem solver creat- ing mathematical software will proceed with a well-prepared set of test data, a systematic test procedure, and a complete understanding of the expected results. Solutions to the test cases should be calculated by hand or the results should be obtained from a reliable source, such as a math- ematical handbook. Then, the test cases should be compared with the computer output. Obviously, this approach may not work for some prac- tical problems whose solutions are not known beforehand. However, it may be possible to formulate the problem so that a simpler version can be tested. As an example, consider a method for solving the cubic equation oa? + ax? + ba +e=0 using a numerical algorithm. One test case should consider a = 0 so that the reduced equation becomes the quadratic equations. Another case could be the equation (x — 1)° = 0 with the three solutions +1, +1, +1. For a general case, the computed x values should be substituted in the cubic equation to see if the result is zero. Modules Since solving a problem may involve a long and complicated sequence of operations, it is recommended that the program be imple- mented as a series of relatively short program segments, usually called program modules. Ideally, each module should perform only one task 15 Problem Solving and Programming (Optional) 7 that is easily tested. Using MATLAB, each module would be ap M-file consisting of a script or function. Errors Any testing should be thorough and also include error condi tions that might be expected. For example, if problem is designed to deal with a certain range of input data, then values outside of the range should not be processed and an etror should be indicated to the user. 1.6 REINFORCEMENT EXERCISES AND EXPLORATION PROBLEMS You should now be able to create the MATLAB scripts required by the Reinforcement Exerciges with little difficulty. The Exploration Problems are intended to provide more challenging opportunities to try your MATLAB programming skill. REINFORCEMENT EXERCISES P1.1. Vector multiplication Given the vectors a b [1,2,3, 4], {0.1, 0.2, 0.3, 0.4}, compute the following: a. d=2a; b. £ as the element-by-element product of a and b, i.e., £(i) = a xb, 1 =1,...,4, using the period (.*) operator. P1.2. Function evaluation Evaluate the following functions at the values indicated: a f(e)=a%+2-3 ab e=-2; a(x +2)(e—1) b I) = ae ©. f(x) = (30°? +20V2)"* ate a4. atx 1, 4; Comment: In Part b, vectorize x and evaluate at three points simultaneously. Be careful'¥o do element-by-element multiplication. P1.3. MATLAB built-in functions Let x be a real number, say, 2.0 How many MATLAB built-in functions can you find that compute f(«)? Compute the value of f(7) for each function. For example, V2.0 = 1.414. Then, try numbers that are not integers, such as 7, and complex numbers, such as 3 + 42. s "38 Chapter 1 m INTRODUCTION PL MATLAB table of powers Create a table of squares, cubes, and fourth powers for 2=0,1,-- ,10 Display the table in columns. MATLAB converts a row of numbers x to a column using the transpose operator in the form x? Hint: This can be done with two MATLAB statements. P1.5. MATLAB conversion table Create and print a conversion table between degrees and radians. The range of degrees is 0° to 360° in 10° increments Label the table and each column. P1.6. Simple plot Plot x versus y for the function created by the equations x=3sin(t), y= 2cos(t), for t = [0,0.1,0.2,.. ,2n]. Also, put text at the center of the plot that says, “ This is an ellipse.” What values actually occur in vector ¢ if the end point is designated 2x? P1.7. Use of eval Using the MATLAB command eval, for each element a, of the vector a= (0,1,2,3,4}, compute a =e b. f, =a. P18. Plots Given the function y = 3cos(7) + 5.cos(13z) on the interval 0 to 10, plot: a, The function in rectangular coordinates; b. The function in polar coordinates. Experiment by increasing the number of points to use for the plot until a smooth curve results. P1.9. MATLAB function Write a MATLAB function that plots a function entered as a string using the variable 2, in the interval from 1 to 10. An example of the usage of the function is >>pfun(’funct (x)’) where funct 1s a MATLAB function such as sin. Test the function using 2? — 2°. P1.10. Program and plot Write a MATLAB function that returns the ratio of the area of an isosceles triangle to the perimeter of the same triangle, given the base and height. Using that function, write a program that plots the ratio of area and perimeter versus the ratio of base to height. Use a fixed height of 10, and vary the base from 0 to 100. EXPLORATION PROBLEMS P1.11. Fibonacci numbers Wnte a program to compute and display the Fibonacci numbers f(n+2)=f(nt)+f(r), fO=fM=1 for values of f less than 100. Hint: Use a while conditional loop to stop the program. 16 Reinforcement Exercises and Exploration Problems 39 1.12. Matrix operations Given the matrix of numbers 1 10 11 12 13 20 21 22 23 A=] 39 31 32 33 |° 40 41 42 43 predict the outcome of the following MATLAB commands and then check the results qj, computer. a. A(:,2) b. AQ) c. A(:,2:3) a AQ) e. ACs) £. diag(A) g. diag(A,1) P1.13. Plotting For 0 <¢< 15, plot the three functions A(t) = 3.0e7°* cos(2.5¢ + 150°) + 1.2, falt) = 3.0e°°% 41.2, fat) = 12 Plot these functions on the same graph using different line styles. Include a title and axes labels well as a legend defining the graphs. P1.14. Circle plot Plot the unit circle x? + y? = 1 using the MATLAB plot command. Does look like a circle on the screen or when printed? If not, explore the use of the axis command so that the circle looks symmetrical as it should be. P1.15. Root finding Let f(x) =e” —2—2 and use MATLAB to find graphically the approximate roots of the equation f(z) = 0 on the real axis. Try to get the results to two or thret decimal places and test your answers. Hint: Use the zoom command to help find the roots. P1.16. Vectorizing and timing Compute the sine of the numbers from 0 to 10 radians with resolution of 0.01 in two ways: a. Use a for loop; b. Vectorize the loop. Execute and time each approach on your computer, What is the improvement by vectorizing? P1.17. Quadratic equation Suppose you wish to write a MATLAB program to solve the equation f(a) = a2? + br+c=0 Considering the discussion of program style, design, debugging, and testing in the text, create the Program to solve for the roots of the equation. First, define the basic algorithm. Then, list all or the special cases and limitations of the program. 0 Chapter 1 m INTRODUCTION Document the program properly so it can be used with confidence by another programmer. Can your program fail for any values of a, or c? Does the accuracy of the solution change with changes jn the constants? Test the program with the cases f(z) = 2? +241, f@) = 2-2, f(z) = 32+6, f(a) a? 10° +1, F(a) =? — 1,000,000.0000012 + 1. Comment: The textbook by Mathews and Fink listed in the Annotated Bibliography for Chapter 2 discusses various numerical errors, including difficulties that arise using the quadratic formula. P1.18. Exponential Write @ program to evaluate e* approximately as Compare the 10th and 20th partial sums for e with the numerical value returned by MATLAB’s built-in exp function. Use the command format long to get the full decimal representation. P1.19. Flyball program Write a program to compute and print the height versus time of a ball whose trajectory is governed by the equation y(t) = —16? + 96¢ feet, where y(t) is the ball’s height above the ground at time ¢ in seconds. Start at t = 0 and print the results at reasonable intervals of time, such as every 0.01 seconds Comment: Be sure to stop the program when the ball hits the ground (y(t) = 0,¢ > 0). P1.20. Rise time The rise time T, of a function is a measure of the initial rate of increase of a function. Numerically, the rise time is defined as the time it takes the function to rise from 10% to 90% of its value. a. Write a program to calculate the rise time of a function. b. Plot the function and label the 10% and 90% points. c, Test the result with the function Y@=(-e%) using various values of r such as T = 0.5, 1.0, Can you find an approximate relationship between the rise time T; and the parameter 7? 16 Reinforcement Exercises and Exploration Problems a ‘1.21, Program timing Compare the time needed to compute the function y= Vexp (#71000) log F y the following MATLAB methods" | \ a. for I=1:1000 : t=.001«T; y(D=sqrt (exp(t)) -#1og(t) ; end b T=[1:1000], y=sqrt(exp(.001*T)) .*log(T); scuss the reasons for the time difference. If you have a very fast computer, such as a pnttum-based system, put the program segments themselves in a loop and compute the average mes Also, are the element-by-element operations necessary in these scripts? 1.22. Project - Handle Graphics and GUI Handle Graphics is the name of a collection of 'w-level graphics routines. These routines allow plot and other such MATLAB commands to ecute. The purpose of Handle Graphics for the user is to customize the fonts, lines, axes, and her properties of figures. These are objects that have properties that define their characteristics a. Explain the use of the get and set commands for object properties. b. How many properties does a figure object have? c. How many properties does an azes object have? test your skill, create a simple plot and modify it using the Handle Graphics capability as lows a. Plot y= sin(z) from —2n to 2m in light orange color with a linewidth of 3. b Add a light blue cosine curve on the same figure. c. Add a title “Handle Graphics Examples” in 24-point green. an you label the «x-axis with the Greek letter theta? | raphical User Interface (GUI) makes a program user-friendly The result 1s essentially lenu-driven program MATLAB GUI programs are controlled by the actions on the interface, suct clicking on an item, rather than sequentially as in an M-file. feate a figure of x = sin(z) from 0 to 2 and add a pull-down menu to allow the plotting of the lowing functions over the same range: sin(z), cos(2), exp(), cos (2). hnt Explore the use of the uimenu command. Chapter 1 @ INTRODUCTION 17 ANNOTATED BIBLIOGRAPHY 1. MATLAB User’s Guide. The MathWorks, Natick, MA. The manual 1s the most complete source of information about all the MATLAB commands The on-line help files contain much of the material in the manual. 2. Garcia, Alejandro L, Numerical Methods for Physics, Prentice Hall, Englewood Cliffs, NJ, 1994. The textbook applies MATLAB solutions to many numeral problems im physics. Many programming aspects of MATLAB are presented and MATLAB and FORTRAN programs are compared. 3, Nakamura, Shoichiro, Numeral Analysis and Graphic Visuahzation with MATLAB, Prentice Hall, Upper Saddle River, NJ, 1996. The tert em- phasizes msual analysis of engineering and sctentific problems. An appendix describes the development of a graphical user interface (abbreviated GUI) that will be helpful to programmers creatmng menu-driven MATLAB applications. 4. VanTassel, Dennie, Program Style, Design, Efficiency, Debugging, and Testing, Prentice Hall, Englewood Cliffs, NJ, 1978 A very readable book for those who wish to umprove their programming abtlity. 1 [is ANSWERS The answers to the Remforcement Exercises in this chapter require MATLAB scripts. 18 Answers 43 Numbers and Vectors PREVIEW. Generally, the study of vectors in analytic geometry, calculus, and elementary physics takes the geometric point of view when vectors are spoken of as having magnitude and direction in two or three dimensions. However, an algebraic approach is necessary for computer representation and generalization beyond three dimensions In many problems in physics and engineering, as well as in mathematics, the variables describing a physical situation are treated as functions of vectors. These vectors have components that may represent the values of the variable in different directions or at different times. The chapter begins with a review of the properties of real and complex numbers, including their representation in MATLAB. Then, we present the basic properties of vectors in two and three dimensions Many properties of three-dimensional vectors are easily generalized to a vector with n > 3 components Also, collections of functions and other mathematical entities can be described as vectors in a vector space That such generalizations are useful is an indication of the great power of mathematics when applied to physical problems. Just as the use of a three-dimensional vector to represent force is an abstraction from the physical world, these further abstractions will prove valuable in analyzing many physical systems. The remainder of the chapter considers vectors and vector spaces for applications to problems in engineering and physics presented in later chapters The important topics include linear independence for vectors. abstract vector spaces, and vector spaces of functions Table 2 1 lists various scalar and vector topics covered in this textbook. TABLE 2.1 Topics in vector analysis Chapter Chapter 2 Symbol atp op ox x+y xy xxy Ill R" v Ax=b L(ax + By) Ax =x Chapter 3 Chapter 4 ® ~ax Ht) Af(t) dt” at dx(t) ae MEE Vex Vxx Chapters 5, 6 Chapter 13 Topic Sum of scalars Product of scalars Scalar times vector Sum of vectors Dot product Cross product Norm Real vector space Abstract vector space Linear equations Linearity Eigenvectors Differential equations Derivative of a function Derivative of a vector Gradient of a function Divergence of a vector Curl of a vector In the table, « and f are real numbers (scalars), x, y, and b are vectors, and A ts a matrix. PROPERTIES OF REAL NUMBERS Since real numbers are used extensively to describe physical phenomena a review of the fundamental operations on real numbers is presented first’ in this chapter. Then, we consider numbers as represented by MATLAB. Chapter 2.» NUMBERS AND VECTORS REAL NUMBERS The set of real numbers consists of integers, rational numbers, and érra- tional numbers. The integers are 1,2,3,...,—1,—2,—3,..., and 0. Frac- tions in the form p/q, where p and q are integers, are rational numbers. Irrational numbers can be represented by an infinite decimal expansion, such as 3.14159... for ™. However, irrational numbers cannot be repre- sented exactly as a ratio of integers. Real numbers that are not integers can be represented by nonter- munating decimal expansions, as in the example of 7 just given. The sequence of decimal digits of 7 is both nontermznating and nonrepeat- ig. In contrast, rational numbers have a repeating decimal expansion, such as } = 0.25000000..., in which the repeated digit is zero. In most, cases, the repeated digits will not be zero. For example, the fraction Z = 0.3181818... has a nonterminating but repeating decimal expan- sion. Since the representation of most real numbers requires an infinite se- ries of digits, we expect that only certain numbers can be represented exactly for hand or computer calculations because the number of decimal places is limited in any such calculations. The importance of these ob- servations will be explored later when MATLAB computer numbers are described. Axioms for Real Numbers In mathematics, certain operations and basic properties involving the quantities being considered such as num- bers, vectors or matrices are assumed to be true. These assumptions are called amoms or postulates and no proof is necessary. Most of the other properties are presented by theorems, which are proven using the postulates and perhaps other theorems. The theorems allow further gen- eralizations and applications to be developed. The basic axioms for real numbers define how numbers are combined by addition and multiplication. These axioms define the associative, com- mutative, and distributive laws as well as the identity and inverse elements for any real numbers x,y, and z. Associative laws. For real numbers, the grouping of the operations for addition or multiplication is not important, since lL. (e+y)+z=24+(yt2), 2. (axy)xz=ax (yx2). A number of basic operations are not associative. For example, sub- traction is not associative, since (e-y)-2#e-(y—2). Thus, if 2 = 5,y = 3,z = 1, the left grouping yields 1, but 3 results from the operations on the right. For nonassociative operations, careful grouping is important. Commutative laws. The order of addition or multiplication of real numbers does not matter: 21 Properties of Real Numbers a7 Laty=yte, Qaxy=yxa. Certain operations of importance in vector and matrix algebra that we, will study later are not commutative with respect to multiplication. Distributive laws. Addition and multiplication are connected by the distributive law: ax(y+2z)=axytexz. Identity elements. The numbers 0 and 1 are called the sdentity ele- ments for addition and multiplication, respectively: 1. 2+0=2, 21xc=2. Inverse elements. For each real number < there is an inverse element for addition, and if the real number is not zero there is an inverse for multiplication: 1. e+(-2z) =0, 2. ifa £0, xx (1/n) =1. The inverse for addition is called the negatwe of the number and the; inverse for multiplication is called the reciprocal. The negative can be used to define the operation of subtraction as addition of the negative, writing) 2—y = 2+ (-y). The reciprocal can be used to define the operation’ of division as multiplication by the reciprocal, x + y = x x (1/y) where! y#0. It is interesting to note that the properties just listed do not uniquely: define the real numbers. For example, the complex numbers and the| binary numbers also satisfy these properties. { Generalization Part of our mathematical education is the generaliza-. tion of the concept of number from the positive integers (counting num- bers) to fractions (ratic numbers) and then to negative and irrational numbers. The generalization continues with the study of transcendental numbers such as 7 and finally the complex numbers. All these numbers satisfy the axioms just presented. The real numbers can be represented as points on the real number line shown in Figure 2.1. For convenience, the entire real number line will be referred to as R. Thus, a statement about R applies to all the real numbers. On R, the distance of any real number from the origin is the mag- nitude, or absolute value, of the number. The absolute value is defined as Chapter 2. NUMBERS AND VECTORS See lei={_2 if <0. (24) Applying the formula, +5 has the absolute value 5, as expected. The number —5 also has the absolute value —(~5) = 5. FIGURE 2.1 The number line R The distance between the real numbers z and y is defined as | x ~ y |. This distance is the length of the line segment of R with the endpoints a and y. The distance on R between the numbers ~5 and 5 is then | -5 — (+45) | = 10. Notice that the absolute value defines the positive distance of the number x from the origin where z = 0. These concepts will be generalized when vectors are studied. [=] MATLAB COMPUTER NUMBERS (OPTIONAL) In modern computer systems, numbers are represented in the binary num- ber system. The digits are 0 and 1 and the computer can store a finite number of binary digits to represent any number. For integers, the deci- mal value of a binary number is mo N= SdH dot di x 2+ dex Pte t+ dm x2", (2.2) 1=0 where m is the number of digits and the d, are binary digits. The number range for a binary number with m digits is from (000...0000)2 to (11111...1111)2, where the notation (N)2 means that N is a number in base 2.1 The most positive value sums to the decimal value 2”—1. An 8-digit positive binary number thus has the maximum value of 2° —1, or 255. The number 10113 has the decimal value 11 using the expansion of Equation 2.2. If a fraction is to be represented, a binary point is used to separate the integer from the fractional part of the number, just as the decimal ‘In the text, numbers other than decimal numbers will have the base specified explicitly 22 MATLAB Computer Numbers (Optional) 49 point is used for decimal numbers. The binary number (0.11111, ..1111)2 has the decimal value m Dea etad x2 +d x24 =I N + dom x 2°" 11 1 = gtgtgt tmx, (2.3) since d_, = 1 for i=1,...,m. This is a geometric series whose sum con- verges to 1 as m goes to infinity, as you are asked to show in Problem 2.3. For a finite value of m digits, the sum is 1—2-™. With 16 binary digits, the value is 1~ 2716 = 0.99998 to five places after the decimal. The binary number representation just discussed assumes that the bi- nary point was located in a fixed position, yielding either an integer or fraction as the interpretation of the internal machine representation. Un- fortunately, the binary point is not actually stored with the number, but its position must be remembered by the programmer (or the program) t display the results in the usual form. This method of representation called fixed pomnt. It is a theorem that any real number x such that 0 < x < 1 canf be represented in a unique manner as a nonterminating binary fraction. In the computer, the binary series must be terminated after m digits ta represent a decimal number. Except in special cases such as 1/2, thé binary representation will be an approximation. The error can be shown to be less than 27”. In practice, the machine number also is limited to a finite range de- termined by the number of binary digits used in the representation. For 4 32-digit binary number, the range of positive fixed-point integers is about +2"? or +10", obtained by solving the equation 2°* = 10¥ for the expo- nent y = 32 logig2. This limited range of the fixed-point numbers is Aranback for certain applications. ‘To overcome many of the limitations of fixed-point notation, a metho that is the counterpart of scientific notation is used for number represen- tation in computers. Floating-point notation represents a number as a) fractional part times a selected base raised to a power. The choice for the base is usually 2, although base 16 is sometimes used. In the machine representation, only the fractional part and the value of the exponent are stored. The decimal equivalent is written as Nn=fx2 (2.4) ‘using base 2 in this case. Thus, 1.5 could be written as (11)2 x 2~). The fraction f is called the mantissa and e is the exponent. Chapter 2m NUMBERS AND VECTORS In floating-point notation, the number of binary digits devoted to the fraction determines the precision and the length of the exponent in digits determines the range. The actual arithmetic operations may be carried out by a computer's Central Processing Unit (CPU) or by a separate hardware chip called a co-processor. In some cases, the arithmetic is performed by a software package containing routines for floating-point arithmetic. MATLAB Floating-point Notation MATLAB and many other pro- grams for mathematics may employ the IEEE floating-point standard rep- resentation for machine numbers.” The results of a calculation for this format can contain as many as 16 significant decimal digits and have a range of from 10~° to 10°°°, However, the results may be displayed in a number of different ways. Comment: Unless floating-point operations are implemented in soft- ware, the machine floating-point hardware actually determines the num- ber format used. In fact, some machines do not conform to the IEEE standard. Try the MATLAB command isieee to determine if your com- puter uses IEEE arithmetic. COEXAMPLE21 MATLAB Range of Numbers Although MATLAB’s calculations are carried out to the maximum pre- cision in floating point internally, the results may be displayed as fixed-point decimal numbers or as numbers in scientific notation. Table 2.2 lists the choices. TABLE 2.2 MATLAB formats for numbers Command Format format Default setting (short) format short —_Fixed-point format with 5 digits format long Fixed-point format with 15 digits format short e Floating-point format with 5 digits format longe Floating-point format with 15 digits format hex Hexadecimal format Although physical measurements rarely justify the precision yielded by the long display formats in the table, MATLAB computes values to the highest precision to reduce roundoff errors Roundoff error is the difference between the perfectly accurate number used in mathematical analysis and the computed number with only a fixed number of significant digits. The hexadecimal format listed in the table is frequently used to read binary numbers in base 16 notation for convenience. *IEEE, usually pronounced I-triple-B, 1s the Institute of Electrical and Electronics Engineers 22 MATLAB Computer Numbers (Optional) 51 The accompanying MATLAB script is taken from a diary file to show vor ious numerical values. The diary file was edited to display the results of each numerical input on the same line. The smallest fraction representable in the author’s machine is shown in the MATLAB script as machine epsilon (eps). Using eps can sometimes avoid a divide by zero. For example, consider th« limit As computed by MATLAB, sin z/z with x = 0 would result in a divide-by-zero error. However, the statements x=xteps yesin(x)/x would lead to the correct result. Adding eps to each element in an array should not affect the results of arithmetic operations unless the values are so small that eps is significant. ‘Various long and short formats are also shown in the MATLAB script. Each number was entered by typing the value at the MATLAB prompt, and the MATLAB representation is shown on the same line. Notice that the pro gram warns the user if a division by zero occurs. Remember that machine zero is simply a number smaller than the smailest possible computer number. Mathematically, this number is not necessarily actually zero. ‘The answer NaN (Not a Number) is standard IEEE floating-point notation for an indeterminate result. Thus, if the IEEE standard is being used, MATLAB. does not stop after calculations such as 0/0 or 00/co, although the results are not meaningful. The purpose of introducing NaN in this way is so that a program can determine that a calculation was invalid and proceed accordingly. Next in the script, the value y is entered in exponential form representing 10°°°. When multiplied by 100, the number is still within MATLAB's range. If the new y is then multiplied by 5, the value overflows and MATLAB indicates that the product z is infinity. Other values, such as 10~*” and log,o(2), are also shown. MATLAB Script Example 2.1 >>% (Machine epsilon) % EX1_2.M >>eps eps = 2.2204e-016 >>format short 4/3 ans = 0.3333 >>format long >>1/3 ans = 0.33333333333333 >>1/0 Warning: Davide by zero ans = Inf >>0/0 Warning: Divide by zero Chapter 2m NUMBERS AND VECTORS MATLAB COMMANDS, FOR REAL NUMBERS NaN e306 1. 000000000000000e+306 >>y=100%y y = 1,000000000000001¢+308 >>esBay z= Inf 10g10(2) ans = 0.30102999566398 >>x=10-307 x = 9.999999999999999e-308 >>1og10(2) ans = 0.30102999566398 >>quit o WHAT IF? Suppose the MATLAB representation of a number is not accurate enough for an application. Investigate the variable precision arithmetic command vpa of the Symbolic Math Toolbox. Compare MATLAB’s numerical value of with the symbolic representation to more than 15 digits. Problem 2.18 and Problem 2.24 treat MATLAB roundoff errors. Use the command format long to see the 15 digit fixed-point representation of the numbers or format long e for the floating-point representation. MATLAB has various commands that are useful for manipulating real numbers. Some commands are listed in Table 2.3 and are illustrated in Example 2.2. The abs command computes the absolute value. The commands for rounding numbers produce the results listed in the table. The sign evaluates the Signum function. The result from sign is zero if the value being tested is zero, +1 if the value is positive, and —1 if the value is negative. TABLE 2.3 MATLAB commands for real numbers Command _ Format abs Absolute value ceil Round toward infinity fix Round toward zero fioor Round toward minus infinity sign Signum function 22 MATLAB Computer Numbers (Optional) 53 PLE 22 MATLAB Commands for Real Numbers Let z = 9.2. The accompanying script illustrates the edited results using the commands from Table 2.3. MATLAB Script Example 2.2 >> x= 9.2 x = 9.2000 >> abs(x) ans = 9.2000 >> cerl(x) ans= 10 >> floor(x) ans= 9 >> fax(x) ans= 9 >> sagn(x) ans= 1 ' COMPLEX NUMBERS A complex number can be written 2 = + iy or z = 2+y, where ¢ and yj are real numbers and 1 is the imaginary unit with the property i? = —1. The number « is called the real part of z and y is called the smaginary part. In functional notation it is sometimes convenient to write z=Rez and y=Imz. (25) A complex number can also be represented as a point P(z,y) in the’ zy-plane (Cartesian plane) as shown in Figure 2.2. This representation is! called an Argand diagram using the ry-plane to plot the complex number., When used this way, the ry-plane is often referred to as the complex! plane or the z-plane. Another notation for a complex number is formed’ by writing 2 = 2 + iy as the ordered pair z (z,y) which gives the correspondence between an ordered pair of real numbers} and each complex number. Thus, z+ iy is a single value in the zy-plane.! Polar coordinates can be associated with a complex number in the: complex plane. From the figure, the radial distance r and the polar angle: 6 with respect to the positive real z-axis are r= Vx+y = tang = 2% (2.6) Chapter 2m NUMBERS AND VECTORS for z #0. If x= 0, 0 = 1/2 when y > 0 and 6 = —m/2 when y <0. Imaginary axis Piry)axtiyaz FIGURE 2.2 Complex numbers The radial distance of z is written as r = |2| and is called the magni tude of z. The magnitude is also called the modulus or length of z. The complex conjugate of z is the number Z = x — iy in Figure 2.2 with polar angle —8. From the figure, it is evident that |3| = |z|. The polar angle is called the argument of z, written arg 2. We see that arg 2 = —argz. The value of arg 2 is usually taken to be in the range from —m to m, and this value is called the principal value of the argument. In calculations it is frequently useful to take advantage of the fact that angle measure is a multi-valued function, with values of the form 6 + n2m, where n is an integer and @ is a particular angle measure. The complex numbers have operations of addition and multiplication that obey the properties of real numbers previously listed. The sum of two complex numbers is formed by adding the real and imaginary parts. ‘Thus, if 21 = 2, + iy: and zp = 2 + 1y2, the sum is 2+ 22 = (U1 +22) + i(y + y2)- (2.7) The negative of 22 = t2 + iy is —22 = —2g — tyz. Subtraction can be accomplished by adding —22 to 2; to form the difference 2 — 22. Thus 2 — 22 = (@1 — 22) + (yn — 2). (2.8) The product of two complex numbers 2; and 22 is 222 = (t1x2 — yry2) + i(a1y2 + Y1%2)- (2.9) From this formula, it follows that 22 = |z|?. 23 Complex Numbers. Using the definition of multiplication of complex numbers, division of complex numbers can be shown to be given by the formula A a\ (4 1% _ (2122 + 1Y2) + Utne — e1y2) 4 (2) (2) _ 34 _ _— + (2.10) 22 22 [22/7 3+ YB BR By definition, two complex numbers are equal if and only if their real parts are equal and their imaginary parts are equal. Thus, a= ifandonlyif Rea =RezandIma=Imz (2.11) or mi +iy =z) +iye ifandonlyif 2)=z2,andyi=ys. (2.12) The real numbers can be viewed as a subset of the complex numbers,: namely the complex numbers of the form z = x+i0 = (z,0). In the plane, this set is the z-axis. Moreover, the definitions of addition, subtraction,' multiplication, and division for these complex numbers correspond exactly} to the usual definitions for real numbers. It is traditional to speak of a complex number as real (or a real scalar) in this case. Since 2 = 2 if and; only if Im z = 0, we have that 2 is real if and only if = Z. Multiplication! of z= 2 + iy by a real scalar value k yields the results i kez = k(x +0y) = (b+ i0)(a + iy) = ka + ky. (2.13) It is straightforward to show that the complex modulus function fol- lows exactly the same rules relative to arithmetic as the real absolute! value function. Namely, leze] = jarllzal a lal a. . 214) 2 zal eal Using the magnitude and argument of 2 in Figure 2.2, a complex number ; can be expressed in the form 2=r(cos8 +isin6). (2.15) Using Equation 2.15 and some basic trigonometry, it can be shown that for 2) =11(cos 6; + isin6,) and 29 =r; (cos6 + isin 6), 2122 = rir [cos(9; + 62) + isin(9; + 62)] (2.16) which means that multiplying complex numbers not only corresponds to multiplying their absolute values, as observed in Equation 2.14, but also corresponds to adding their arguments, a quite useful fact in applications Chapter 2.» NUMBERS AND VECTORS involving rotations. Strictly speaking, the addition of arguments must be understood modulo 2z, since the principal value of the argument of (1+ 4)(1 +4) = 24 is not 3/2 (= 3/4 + 37/4), but rather —1/2, Complex analysis extends the basic concepts and many of the familiar functions of calculus to the set of complex numbers. For example, there is a complex exponential function exp z, or e*, which has the values of the real exponential function when 2 is real. In complex analysis it is shown that the complex exponential function satisfies the relationship 28 cos 0 + isin® (2.17) which is known as Buler’s formula. In Equation 2.17, the sin and cos functions on the right are the familiar real-valued functions? Thus, the polar form of a complex number can also be written as zare, (2.18) This is a convenient form for certain applications, as discussed in Chap- ter 5. Since the complex exponential function satisfies the same multipli- cation rule as the real exponential function e*, the expression e* has the representation oF sett = eel = e* (cosy + isiny). (2.19) ROOTS OF Let a be a nonzero complex number. Then if a complex number z satisfies COMPLEX the equation NUMBERS a 2 is called an Nth root of a. The determination of the Nth roots of a uses the theorem of De Moivre (cos6 + isin8)% = cos. NO + isin NO (2.20) which follows from Equation 2.16. Writing a in polar coordinates as a=r(cos@ + isin 6), the roots of a are o an 8 Qn aN isin( — + p— 7 a = V5 [cos ($+ 932) +i0n (5 +077)| (2.21) where p takes the values 0,1,..., N—1. These are N distinct values, and it can be shown that there are no others. The term 4/r is the positive real Nth root of r and for the specific case |a| = 1 this value is 1. For our purposes, we will consider @ to be real, although actually Equation 2.17 helds for any complex 9, with the extensions of the trigonometric functions to the complex numbers 23 Complex Numbers 57 Complex Numbers a Various operations on complex numbers are illustrated as follows: (i). (8 + 62) + (2 ~ 32) = 5 + 32, (i). (7 +54) — (1+ 2) = 6-438; (iii). (5 + 74)(3-+ 42) = (15 — 28) + 4(20 + 21) = 13 + 414; (iv). 44i _ Ati 2431 _ (B-3)+i(2412) _F+lr_ 5 2-3 2-31 243i 13 13 sau b. ‘To solve the equation (e+ (2-13) =4 4 for z and y, equate the real and imaginary parts to yield the simultaneous set of equations Qr+3y = 4 32+ 2y = The solutions are x = 5/13 and y = 14/13. In Equation 2.21, let a = 1. For this complex number, the argument 6 is vero and the magnitude is 1, so we can write peal cI con? 4 sin POE with the property that |a| = 1 so that every one of these complex numbers hes on the unit circle in the complex plane. Consider the values (p/N)27 for integers p = 0,1, 2,3 when N = 4. Writing = e* where a = 2np/4, these values correspond to the angles @=0(2n), a= 2/2, a= 7m and a= 31/2 n the complex plane, respectively. The complex values allowed for z are then ma = é = 1 Po ee (2.22) a ee = -1 oa The square roots of unity (N = 2) are -+1, and the square roots of these ots are 1,—1,2, —2 as is easily verified. The sum of the roots (1 +1—1~1) is ero. a Chapter 2. NUMBERS AND VECTORS MATLAB COMPLEX NUMBERS Clexampte 24 MATLAB accepts complex numbers in both Cartesian and polar fc The Cartesian format for the complex number z = 3 + 42 would be >> 223+4i >> 29344) since either i or j can be used to specify the imaginary number v Because MATLAB would interpret i4 as a variable name, even thc mathematically 42 = i4, in MATLAB we must write i*4 in statem such as z=3+i*4. The MATLAB polar form is >> wertexp(ixtheta) where r and theta must be defined before w is used. Comment: It is important not to use the variables 2 and j for variables or similar purposes in programs that also use MATLAB’s c plex numbers since the loop variables may override their definitio: imaginary numbers. Table 2.4 lists some of the MATLAB commands that are usefu manipulating complex numbers. TABLE 2.4 MATLAB commands for complex numbers Command Format zextyi, zextyj Complex number zervexp(irtheta) Polar form abs Magnitude |z| = V/2? + y? angle Angle in radians (—7, 7); 9 = tan” *(y/z) conj Complex conjugate 2 — yi imag Complex imaginary part y real Complex real part Plotteng. compass Draws complex numbers as arrows on polar plot feather Draws complex numbers as arrows on linear plot Ordinary operations +,~,*,/ for addition, subtraction, multiplica‘ and division, respectively, perform these operations on two complex r bers. MATLAB Complex Numbers ‘The accompanying script shows the MATLAB commands to compute F and Part c of Example 2.3. 23 Complex Numbers MATLAB Script __ ee — Example 2.4 >> 3461 + 2-31 ans = 5.0000 + 3.00001 >> 7+51 ~(1422) ans = 6.0000 + 3.00001 >> (#72) *(3+42) ans = -13.0000 +41.00002 >> (4#1)/ (2-31) ans = 0.3846 + 1.07691 >> % Solve 274-10 >> roots([1 0 0 0 -1]) 1.0000 0.0000 + 1.00004 0.0000 - 1.00002 1.0000 VECTORS IN TWO DIMENSIONS AND THREE DIMENSIONS -TION ORS ‘The notion of vectors has proven invaluable in physics and mathematics. The vector in space is a combination of a positive number called the magnitude and a direction. One useful feature of vectors is that the equations of physics can be represented in terms of vectors independent of a particular coordinate system. Newton’s second law F=ma { provides an example. The vector form of the equation is not altered by a change in the coordinate axes. For example, the form shown for, Newton’s law holds whether F is defined in rectangular, polar, or spherical coordinate systems. Also, the vector equation is a convenient “shorthand” to represent complicated formulas. The use of vectors can lead to greater! understanding of a problem as well as simplification of computations as will be shown in many examples in this text. In some cases involving two-dimensional (2D) and three-dimensional (3D) space, visualization of a physical situation is aided by drawing the vectors involved as directed line segments to give the vectors a geometric inter- pretation. A vector can also be identified using coordinates that represent its origin and endpoint. This latter view is the algebraic view. Chapter 2. = NUMBERS AND VECTORS As discussed previously, the real numbers can be identified with the points of a straight line, as shown in Figure 2.1. Each number z is repre- sented by a point on the line, so the value can be pictured geometrically with respect to other real numbers. Similarly, the origin and endpoint of vectors in the 2D plane can be represented as pairs of real numbers, and the components can be plotted in the zy-plane, as shown in Fig- ure 2.3. When the origin of the vector is [0,0] in the zy-plane, the vector is typically defined only by the coordinates of its endpoint. For example, the 2D vector starting at [0,0] with endpoint [3, 4] can be drawn as a line segment from the origin [0, 0] to its endpoint 3 units in the z direction and 4 units in the y direction. These values of 3 and 4 represent the components of the vector in the x and y directions, respectively. In three dimensions, the vector’s endpoints are represented by three real numbers so the vector can be designated as [x1, 2, 73] ‘A vector can thus be described geometrically by a line from its origin to its endpoint. The geometric view is used to visualize the problem at hand, as when the vectors represent distances or forces in various direc- tions. The algebraic notation is useful when performing calculations such as addition with vectors. The legitimate operations that are allowed for vectors will be defined later in this chapter. y 4 1.4) 3 2 ' O 7 2 3 45 FIGURE 2.3 Points and vectors Notation In this text, individual vectors are usually designated by ro- man letters printed in boldface type (a,b, A,x...). As an example, the equation a = [3,4] defines a as the vector from the origin to the point [3,4]. The same notation means that the vector a has component 3 in the direction and component 4 in the y direction. Numbers are often called scalars to emphasize the distinction between numbers and vectors. Thus, energy and power in physics are scalar quan- tities, whereas velocity and acceleration are vector quantities, since these later quantities have a direction associated with them. The term scalar multiple of a vector means multiplication of the vec- tor components by a number. The multiplication operation is denoted as ax for the scalar a and the vector x. 24 Vectors in Two Dimensions and Three Dimensions 61 ‘The notation R? is used to denote the set of all 2D vectors, and R® indicates all of the 3D vectors ‘The exponent defines the dimension of the vectors being discussed. Thus, a = [3,4] is a 2D vector that 1s a member of R?. Addition and Subtraction of Vectors Consider two arbitrary vec- tors x = [71,22] and y = [y;,y2]. The sum and difference of the vectors are the new vectors xty = [erty.2e +m), x-y = [a1 — 1,22 — ya], in terms of the components of the original vectors. Notice that the result-( ing vectors would not generally have the origin as their beginning point. | ‘We can also draw the vectors and determine the sum and difference asi shown in Figure 2.4. In Figure 2.4(a), the vector y is shifted so the initial point of y is placed at the terminal point of x. The vector x + y is the vector from the origin to the end point of y in the figure. By drawing the diagram with y at the origin, you can show that y +x = x+y. Notice that this definition of addition of 2D vectors corresponds exactly to the addition of complex numbers. Figure 2.4(b) shows the subtraction of two vectors. As an aid to remembering the direction, note that x = x — y + y, so that x — y is the, vector that must be added to y to obtain x. The vector y — x has the} same length as x — y but points in the opposite direction. (xy + yn. 42 + Y2) (@) Addition (b) Subtraction FIGURE 2.4 Addition and subtraction of vectors Scalar multiplication of vectors The multiplication of a vector x = (e1, 72] by a scalar r is defined by rx = [rz1,7rz2] Chapter 2. = NUMBERS AND VECTORS which, for r positive, has the effect of stretching or shrinking x by a factor of r. For r negative, it also reverses its direction. Notice that this definition for 2D vectors corresponds exactly to the multiplication of a complex number by a scalar. Length of a Vector The length of a vector x is a nonnegative scalar quantity that measures the distance between its initial point and terminal point. In the Cartesian coordinate system, the components of a 3D vector represent the lengths along the three mutually perpendicular axes 1, y, and z. The length of a vector is also called its magnitude, especially when the vector represents a physical quantity. Thus, if a defines the acceleration vector for a body, the magnitude of the acceleration is written @ in this textbook. The length of a 2D vector with components [2,29] in the ry-plane follows from the Pythagorean theorem as Il] = Vari? + 22?. (2.23) The length of the 2D vector a = [3, 4] previously defined is thus ll all = V3? +42 =5. Generalization to three dimensions is straightforward. The length of the vector a between points [x1,y:] and [72, ya] can be found by forming 2 = 2 — 1 and y = ya — y; and then computing all = Vo+y. Some authors use the notation | a | to indicate the length or magni- tude of the vector a. This representation is quite common for vectors in R? and R®. In a later section of this chapter, the length or magnitude of a vector will be called the norm of the vector. This is a generalization of the concept of length, which is useful for vectors with more than two or three components. The norm of a is written || a ||. Unit Vectors A vector x of length 1 (|| x || = 1) will be called a uns vector. For any vector x, a unit vector n in the direction of x can be computed as “Tx assuming that || x {| is not zero, This unit vector defines the direction of vector x. A nonzero vector that is divided by its magnitude is said to be nor- mahzed. Such a vector, as for example the vector n = x/|[x||, has the property that ||n|| = 1. 24 Vectors in Two Dimensions and Three Dimensions 63 vcr An important operation for two vectors of the same dimension is the scalar, or dot, product. One definition of the dot product for two nonzero vectors with a common origin point is x+y = [|x lly Il cosé. (2.24) In the equation, is the angle between the vectors, usually measured in radians, taken from the interval 0 < @ < 7. The dot product of the 3D vectors x = [21,22,23] and y = [y1, 42, ys] can also be shown to be x°Y = Ziyi t 2ay2 + Tsy3 (2.25) in terms of their components. Of course, for 2D vectors the terms in z3 and y3 are not included. Notice that the length of the vector x can be j computed as \/x+x, as shown by letting x = y in Equation 2.25, which defines the dot product in terms of the components of the vectors. ‘The two definitions just given for the dot product are equivalent. For example, if x and y are two nonzero vectors in three dimensions that originate from a common point, the cosine of the angle between them is _ (x+y) cos? =O MyD ey : Ziyi + Cayo + rays 2) Va+ata Veith This relationship can be proven, as indicated by Problem 2.29. Use of the Dot Product Let x = [2,4,0] and y = [6,—4, 2]. Thus, the vectors have length Ix ll xx = va4I6+0 v5, Pall vy = v3e+16+4 2vi4, and the dot product is x+¥ = (2)(6) + (4)(—4) + (0)(2) = -4. By combining Equation 2.24 and Equation 2.23, the angle between the vectors is computed as a= oo rival “1 =o] [aie (2V5)(2V14). If we define d = y —x, then the distance between the endpoints of y and x is the length of d. Thus, the distance is Hall = tly-xll = VG@-2?+ (4-4)? + 2-0? = VE = 2a. oO Chapter 2.» NUMBERS AND VECTORS Orthogonal Vectors If two vectors have a nonzero length and x+y =0, the vectors are said to be perpendicular, or orthogonal, to each other. In 2D and 3D, the vectors thus meet at right angles, since @ = 90° when cos@ = 0. The fact that two vectors x and y are orthogonal can be represented by the notation x Ly. Standard Unit Vectors The 3D unit vectors, defined as i = [1,0,0, i = (01,9, k = (0,0,1], (2.28) are called the standard, or natural, unit vectors in R°. The triplet i,j,k is also called a set of basis vectors, since any 3D vector can be represented as a sum of scalar multiples of these three unit vectors. The standard unit vectors all have length 1 and are mutually orthog- onal, as is easily shown by forming the dot product between any pair of these vectors. Such a set of vectors is said to form an orthonormal set. Dexample 26 Use of Unit Vectors The unit vectors are frequently used to form an alternative notation for a vector in ordinary 3D space. Thus, the vector F = [fz, fy, fz] can be written as F = fei+ fyi+ fek, (2.29) where fe, fy, and f. represent the lengths of the vector along the 2-, y-, and z-axes, respectively. However, the unit vectors and the dot product have far greater application than notational convenience or geometrical interpretation. For example, assume that the force on an object is defined by the vector F. Then, the component of the force in the z-direction is given by F «i. The proof is straightforward, since Feta fe(iel) + fy +i) + falet) = fe (2.30) after taking the dot product of the standard unit vectors. o Application of the Dot Product The dot product is frequently used to find the component of one vector in the direction of another. For example, an important use of the dot product is to determine the work done by a constant force F acting on a body moving a distance and in a direction defined by the vector s. The magnitude of s defines the distance moved, but only the component of F in the direction of s does work. The calculation F +s multiplies the component of F in the direction of 24 Vectors in Two Dimensions and Three Dimensions 65 motion times the distance traveled and hence defines the work done. In vector calculus, the dot product plays a role in computing certain line and surface integrals and in the definition of the divergence of a function (V - F) to be studied in later chapters. So far in this chapter, we have represented a vector as a row of numbers, called a row vector. The vector x can also be represented as a column vector in the form zy x=| 22 23 ‘These representations of vectors will be useful in Chapter 3 when matrix: operations are considered. For two vectors x and y that have the same number of components, the dot product can be computed by writing one vector as a row vector and the other as a column vector and performing matrix multiplication to yield un x+y =[21,22,23] | yo | = 21 + Taye + Z3ys- (231) vs In some contexts, the terms scalar product and inner product are also used to describe the product of Equation 2.31. A very important application of the dot product of two vectors is in} determining the projection of one nonzero vector along another. Figure 2.5} shows the geometry of the problem. FIGURE 2.5 Projections The figure shows the projection of y on x determined by dropping a line from the end of y that is perpendicular to x in the plane of x and y. Thus, the length of the projection measured from the origin of the vectors" to the intersection of the line with x is ||y|| cos @. We now wish to define the projection in terms of the dot product and also define the vector that Chapter 2. = NUMBERS AND VECTORS

You might also like