An introduction to numerical methods a matlab approach fourth edition guenther

Page 1

An

Guenther

Visit to download the full and correct content document: https://textbookfull.com/product/an-introduction-to-numerical-methods-a-matlab-appro ach-fourth-edition-guenther/

numerical
introduction to
methods : a MATLAB® approach Fourth Edition

More products digital (pdf, epub, mobi) instant download maybe you interests ...

An introduction to numerical methods: a MATLAB approach 4th Edition Guenther

https://textbookfull.com/product/an-introduction-to-numericalmethods-a-matlab-approach-4th-edition-guenther/

Applied Numerical Methods with MATLAB for Engineers and Scientists Fourth Edition Steven C. Chapra Dr.

https://textbookfull.com/product/applied-numerical-methods-withmatlab-for-engineers-and-scientists-fourth-edition-steven-cchapra-dr/

Numerical Methods for Engineering: An introduction using MATLAB® and computational electromagnetics examples (Electromagnetic Waves) 2nd Edition Karl F. Warnick

https://textbookfull.com/product/numerical-methods-forengineering-an-introduction-using-matlab-and-computationalelectromagnetics-examples-electromagnetic-waves-2nd-edition-karlf-warnick/

Numerical Linear Algebra A Concise Introduction with MATLAB and Julia Folkmar Bornemann

https://textbookfull.com/product/numerical-linear-algebra-aconcise-introduction-with-matlab-and-julia-folkmar-bornemann/

Numerical Methods for Engineers and Scientists Using MATLAB Second Edition Esfandiari

https://textbookfull.com/product/numerical-methods-for-engineersand-scientists-using-matlab-second-edition-esfandiari/

A Little Bit of Numerology An Introduction to Numerical Divination Novalee Wilder

https://textbookfull.com/product/a-little-bit-of-numerology-anintroduction-to-numerical-divination-novalee-wilder/

Numerical Methods for Engineers and Scientists Using MATLAB® Ramin S. Esfandiari

https://textbookfull.com/product/numerical-methods-for-engineersand-scientists-using-matlab-ramin-s-esfandiari/

Numerical Methods of Exploration Seismology With Algorithms in Matlab r Gary F. Margrave

https://textbookfull.com/product/numerical-methods-ofexploration-seismology-with-algorithms-in-matlab-r-gary-fmargrave/

Numerical Linear Algebra An Introduction 1st Edition Holger Wendland

https://textbookfull.com/product/numerical-linear-algebra-anintroduction-1st-edition-holger-wendland/

An Introduction to Numerical Methods

A MATLAB® Approach

Fourth Edition

An Introduction to Numerical Methods A MATLAB® Approach

Fourth Edition

Dr. Abdelwahab Kharab Abu Dhabi University

Professor Ronald B. Guenther Oregon State University

MATLAB • is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks does not warrant the accuracy of the text or exercises in this book. This book’s use or discussion of MATLAB • software or related products does not constitute endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular use of the MATLAB • software.

CRC Press

Taylor & Francis Group

6000 Broken Sound Parkway NW, Suite 300

Boca Raton, FL 33487-2742

© 2019 by Taylor & Francis Group, LLC

CRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government works

Printed on acid-free paper

Version Date: 20180612

International Standard Book Number-13: 978-1-138-09307-2 (Hardback)

This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers.

For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.

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

Library of Congress Cataloging-in-Publication Data

Names: Kharab, Abdelwahab, author. | Guenther, Ronald B., author.

Title: An introduction to numerical methods : a MATLAB approach / Abdelwahab Kharab, Ronald B. Guenther.

Other titles: Numerical methods

Description: Fourth edition. | Boca Raton, Florida : CRC Press, [2018] | Includes index.

Identifiers: LCCN 2018011079| ISBN 9781138093072 (hardback : alk. paper) | ISBN 9781315107042 (ebook)

Subjects: LCSH: Numerical analysis--Data processing. | MATLAB.

Classification: LCC QA297 .K52 2018 | DDC 518--dc23

LC record available at https://lccn.loc.gov/2018011079

Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the CRC Press Web site at http://www.crcpress.com

Dedicatedto
TheYearofSheikhZayed binSultanAlNahyan the FoundingFatheroftheNation
Contents Preface xiii 1Introduction 1 1.1ABOUTMATLABandMATLABGUI(GraphicalUserInterface) 1 1.2ANINTRODUCTIONTOMATLAB................. 2 1.2.1Matricesandmatrixcomputation............... 2 1.2.2Polynomials........................... 6 1.2.3Outputformat.......................... 7 1.2.4Planarplots........................... 8 1.2.53-Dmeshplots......................... 9 1.2.6Functionfiles.......................... 10 1.2.7Definingfunctions........................ 11 1.2.8Relationsandloops....................... 12 1.3TAYLORSERIES............................ 15 2NumberSystemandErrors 23 2.1FLOATING-POINTARITHMETIC................. 23 2.2ROUND-OFFERRORS........................ 28 2.3TRUNCATIONERROR........................ 32 2.4INTERVALARITHMETIC...................... 34 3RootsofEquations 41 3.1THEBISECTIONMETHOD..................... 42 3.2FIXEDPOINTITERATION..................... 50 3.3THESECANTMETHOD....................... 57 3.4NEWTON’SMETHOD........................ 62 3.5CONVERGENCEOFTHENEWTONAND SECANTMETHODS.......................... 72 3.6MULTIPLEROOTSANDTHEMODIFIED NEWTONMETHOD.......................... 74 3.7NEWTON’SMETHODFORNONLINEAR SYSTEMS................................ 80 APPLIEDPROBLEMS............................ 86 vii
viii Contents
93 4.1MATRICESANDMATRIXOPERATIONS............. 94 4.2NAIVEGAUSSIANELIMINATION................. 97 4.3GAUSSIANELIMINATIONWITHSCALED PARTIALPIVOTING......................... 105 4.4LUDECOMPOSITION........................ 118
119 4.4.2Gaussianeliminationmethod................. 122 4.5ITERATIVEMETHODS........................ 132 4.5.1Jacobiiterativemethod..................... 132 4.5.2Gauss-Seideliterativemethod................. 134 4.5.3Convergence........................... 137 APPLIEDPROBLEMS............................ 145 5Interpolation 153 5.1POLYNOMIALINTERPOLATIONTHEORY............ 154 5.2NEWTON’SDIVIDED-DIFFERENCEINTERPOLATING POLYNOMIAL............................. 156 5.3THEERROROFTHEINTERPOLATING POLYNOMIAL............................. 167 5.4LAGRANGEINTERPOLATINGPOLYNOMIAL.......... 172 APPLIEDPROBLEMS............................ 177 6InterpolationwithSplineFunctions 181 6.1PIECEWISELINEARINTERPOLATION.............. 182 6.2QUADRATICSPLINE......................... 188 6.3NATURALCUBICSPLINES..................... 192 APPLIEDPROBLEMS............................ 206 7TheMethodofLeast-Squares 209 7.1LINEARLEAST-SQUARES...................... 210 7.2LEAST-SQUARESPOLYNOMIAL.................. 216 7.3NONLINEARLEAST-SQUARES................... 224 7.3.1Exponentialform........................ 224 7.3.2Hyperbolicform......................... 226 APPLIEDPROBLEMS............................ 232 8NumericalOptimization 235 8.1ANALYSISOFSINGLE-VARIABLEFUNCTIONS......... 235 8.2LINESEARCHMETHODS...................... 238 8.2.1Bracketingtheminimum.................... 238 8.2.2Goldensectionsearch...................... 239 8.2.3FibonacciSearch........................ 241 8.2.4ParabolicInterpolation..................... 244 8.3MINIMIZATIONUSINGDERIVATIVES.............. 251
4SystemofLinearEquations
4.4.1Crout’sandCholesky’smethods................
Contents ix 8.3.1Newton’smethod........................ 251 8.3.2Secantmethod.......................... 252 APPLIEDPROBLEMS............................ 255 9NumericalDifferentiation 257 9.1NUMERICALDIFFERENTIATION................. 257 9.2RICHARDSON’SFORMULA..................... 264 APPLIEDPROBLEMS............................ 270 10NumericalIntegration 273 10.1TRAPEZOIDALRULE........................ 274 10.2SIMPSON’SRULE........................... 283 10.3ROMBERGALGORITHM...................... 294 10.4GAUSSIANQUADRATURE..................... 301 APPLIEDPROBLEMS............................ 312 11NumericalMethodsforLinearIntegralEquations 317 11.1INTRODUCTION........................... 317 11.2QUADRATURERULES........................ 320 11.2.1Trapezoidalrule......................... 321 11.2.2TheGauss-Nystr¨ommethod.................. 323 11.3THESUCCESSIVEAPPROXIMATIONMETHOD........ 330 11.4SCHMIDT’sMETHOD......................... 332 11.5VOLTERRA-TYPEINTEGRALEQUATIONS........... 334 11.5.1Euler’smethod......................... 335 11.5.2Heun’smethod......................... 336 APPLIEDPROBLEMS............................ 340 12NumericalMethodsforDifferentialEquations 343 12.1EULER’SMETHOD.......................... 344 12.2ERRORANALYSIS.......................... 350 12.3HIGHER-ORDERTAYLORSERIESMETHODS.......... 355 12.4RUNGE-KUTTAMETHODS..................... 359 12.5MULTISTEPMETHODS....................... 373 12.6ADAMS-BASHFORTHMETHODS.................. 374 12.7PREDICTOR-CORRECTORMETHODS.............. 383 12.8ADAMS-MOULTONMETHODS................... 384 12.9NUMERICALSTABILITY...................... 392 12.10HIGHER-ORDEREQUATIONSANDSYSTEMS OFDIFFERENTIALEQUATIONS.................. 395 12.11IMPLICITMETHODSANDSTIFFSYSTEMS........... 402 12.12PHASEPLANEANALYSIS:CHAOTICDIFFERENTIAL EQUATIONS.............................. 404 APPLIEDPROBLEMS............................ 410
x Contents 13Boundary-ValueProblems 417 13.1FINITE-DIFFERENCEMETHODS................. 418 13.2SHOOTINGMETHODS........................ 425 13.2.1Thenonlinearcase....................... 425 13.2.2Thelinearcase......................... 430 APPLIEDPROBLEMS............................ 437 14EigenvaluesandEigenvectors 441 14.1BASICTHEORY............................ 441 14.2THEPOWERMETHOD....................... 446 14.3THEQUADRATICMETHOD.................... 449 14.4EIGENVALUESFORBOUNDARY-VALUE PROBLEMS............................... 458 14.5BIFURCATIONSINDIFFERENTIAL EQUATIONS.............................. 461 APPLIEDPROBLEMS............................ 466 15DynamicalSystemsandChaos 467 15.1AREVIEWOFLINEARORDINARYDIFFERENTIAL EQUATIONS.............................. 468 15.2DEFINITIONSANDTHEORETICALCONSIDERATIONS.... 471 15.3TWO-DIMENSIONALSYSTEMS.................. 478 15.4CHAOS................................. 490 15.5LAGRANGIANDYNAMICS..................... 495 APPLIEDPROBLEMS............................ 502 16PartialDifferentialEquations 505 16.1PARABOLICEQUATIONS...................... 506 16.1.1Explicitmethods........................ 506 16.1.2Implicitmethods........................ 510 16.2HYPERBOLICEQUATIONS..................... 517 16.3ELLIPTICEQUATIONS........................ 524 16.4NONLINEARPARTIALDIFFERENTIALEQUATIONS..... 530 16.4.1Burger’sequation........................ 530 16.4.2Reaction-diffusionequation................... 532 16.4.3Porousmediaequation..................... 533 16.4.4Hamilton-Jacobi-Bellmanequation.............. 535 16.5INTRODUCTIONTOFINITE-ELEMENTMETHOD....... 537 16.5.1Theory.............................. 538 16.5.2TheFinite-ElementMethod.................. 544 APPLIEDPROBLEMS............................ 549 BibliographyandReferences 551 Appendix 556
Contents xi ACalculusReview 557 A.1Limitsandcontinuity.......................... 557 A.2Differentiation.............................. 558 A.3Integration................................ 558 BMATLABBuilt-inFunctions 561 CTextMATLABFunctions 565 DMATLABGUI 567 D.1RootsofEquations........................... 567 D.2SystemofLinearEquations...................... 569 D.3Interpolation............................... 570 D.4TheMethodofLeastSquares..................... 570 D.5Integration................................ 571 D.6Differentiation.............................. 572 D.7NumericalMethodsforDifferentialEquations.......... 573 D.8Boundary-ValueProblems....................... 573 D.9NumericalMethodsforPDEs..................... 574 AnswerstoSelectedExercises 577 Index 611

Preface

Thisisatextbookdesignedforanintroductorycourseinnumericalmethods.It dealswiththetheoryandapplicationofthemostcommonlyusednumericalmethodsforsolvingnumericalproblemsonmicrocomputers.Itis intendedforstudents inmathematics,science,andengineeringwhohavecompletedtheintroductorycalculussequence.Inaddition,thereaderisassumedtohavetakenastructured programmingcourse.Thethrustofthistextistoassistthestudentstobecome familiarwiththemostcommonnumericalmethodsencounteredinscienceandengineering.Thecontentmaterialofthisbookhasbeendesignedtobecompatible withanyintroductorynumericaltextbookthatexistsinthe market.Studentswill beabletoexamineandsolvemanynumericalproblems,usingMATLAB R 1 ina shortperiodoftime.

Duetotherapidadvancementofcomputertechnologyandsoftwaredevelopments, wehaveusedMATLABasthecomputingenvironmentthroughout allthechapters ofthebook.Eachnumericalmethoddiscussedinthisbookisdemonstratedthrough theuseofMATLABwhichiseasytouseandhasmanyfeaturessuchas:

1.Powerfulmatrixstructure,

2.Powerfultwo-andthree-dimensionalgraphingfacilities,

3.Avastnumberofpowerfulbuilt-infunctions,

4.MATLAB’sstructuredprogrammingstylethatresemblesFORTRANandBASIC.

Thegoalofthispresentfourtheditionisthesameasthepreviousone.Thebook introducesstudentstoawiderangeofusefulandimportantalgorithms.Computer

1MATLAB R isaregisteredtrademarkoftheMathWorks,Inc. Forproductinformation,pleasecontact: TheMathWorks,Inc. 3AppleHillDrive Natick,MA01760-2098USA

Tel:508-647-7000Fax:508-647-7001

E-mail:info@mathworks.comWeb:www.mathworks.com

xiii

resultsarepresentedwithfulldetailssothatthemainstepsofthealgorithmofeach numericalmethodarevisualizedandinterpreted.Forthisreason,asupplementary CD-ROM,attachedatthebackofthebook,hasbeendevelopedforstudents’use withMATLAB.TheCD-ROMcontainssimpleMATLABfunctionsthatgiveaclear step-by-stepexplanationofthemechanismbehindthealgorithmofeachnumerical methodcovered.Emphasisisplacedonunderstandinghowthe methodswork. Thesefunctionsguidethestudentthroughthecalculations necessarytounderstand thealgorithm(s).Themainfeatureofthisbook,besidetheuseofMATLABasits computingenvironment,isthatthestyleofthebookiseasy, direct,andsimple. Thisislikelytobooststudents’confidenceintheirability tomastertheelements ofthesubject.

Thebookisorganizedinafairlystandardmanner.Topicsthataresimpler,both theoreticallyandcomputationally,comefirst;forexample Chapter2 containsan introductiontocomputerfloatingpointarithmetic,errors,andintervalarithmetic andfindingtherootofequationsiscoveredin Chapter3 .

Bothdirectanditerativemethodsarepresentedin Chapter4 forsolvingsystems oflinearequations.

Interpolation,splinefunctions,conceptsofleastsquaresdatafitting,andnumericaloptimizationarethesubjectsof Chapters5, 6, 7,and 8. Interpolationforms thetheoreticalbasisformuchofnumericalanalysis.

Chapters9 and 10 aredevotedtonumericaldifferentiationand integration.Severalefficientintegrationtechniquesarepresented.

In Chapters11 and 12 awidevarietyofnumericaltechniquesispresentedforsolvinglinearintegralequationsandordinarydifferentialequations.Anintroductionfor solvingboundaryvalueproblemsispresentedin Chapter13. Chapter14 isdevoted tosomenumericaltechniquesforcomputingtheeigenvalues andeigenvectorsofa matrix.AnintroductiontoDynamicalsystemsandChaosispresentedin Chapter 15.Thelast Chapter16 providesabasicintroductiontonumericaltechniquesfor solvingpartialdifferentialequations.

Ineachchapterwehaveattemptedtopresentclearexamplesineverysection followedbyagoodnumberofrelatedexercisesattheendofeachsectionwith answerstosomeexercises.

Itisthepurposeofthisbooktoimplementvariousimportant numericalmethods onapersonalcomputerandtoprovidenotonlyasourceoftheoreticalinformation onthemethodscovered,butalsotoallowthestudenttoeasilyinteractwiththe computerandthealgorithmforeachmethodusingMATLAB.

Thistextshouldprovideanexcellenttoolsuitableforteachingnumericalmethod coursesatcollegesanduniversities.Itisalsosuitableforself-studypurposes.

FeaturesintheFourthEdition

Therehavebeensomeminorchangesinsomesections.Majornewfeaturesare asfollows:

• AnewchapteronDynamicalsystemsandChaos.

xiv Preface

Acknowledgments

Wewishtothankthemanypersonswhohavehelpedusinthecreationofthis book.Theyare:

FromAbuDhabiUniversity,Dr.DeenaElsori,Dr.JamalBenbourenane,Dr. MakhtarSarr,Prof.HaydarAkcaandProf.HichemEleuch.Mr. SaadaouiMohamedfromUniversityofLaghouat.

Specialthanksareduetothosewhogavetheirtimetoeditour book,Mr.Zack PolaskiandMr.FayselKharabfromLisbonUniversity.

TheauthorsremainverygratefultoSarfrazKhanandtheeditorialandproductionstaffofChapman&Hall/CRCwhohavebeenhelpfulandavailableatall stages.

Finally,theauthorsaregratefulforthefinancialandfacilitiessupportprovided byDr.AshrafKhalilDirectorofResearchofAbuDhabiUniversity.

Suggestionsforimprovementstothebookarealwayswelcome andcanbemade bye-mailat:awkharab@yahoo.com.

AbdelwahabKharab RonaldB.Guenther

Preface xv

Chapter1 Introduction

TheTaylorSeriesisoneofthemostimportanttoolsinnumericalanalysis.It constitutesthefoundationofnumericalmethodsandwillbe usedinmostofthe chaptersofthistext.FromtheTaylorSeries,wecanderivetheformulasanderror estimatesofthemanynumericaltechniquesused.Thischaptercontainsareview oftheTaylorSeries,andabriefintroductiontoMATLAB R .

1.1ABOUTMATLABandMATLABGUI(GraphicalUserInterface)

MATLAB(MATrixLABoratory)isapowerfulinteractivesystemformatrixbasedcomputationdesignedforscientificandengineeringuse.Itisgoodformany formsofnumericcomputationandvisualization.MATLABlanguageisahighlevelmatrix/arraylanguagewithcontrolflowstatements,functions,datastructures, input/output,andobject-orientedprogrammingfeatures. Tofullyusethepower andcomputingcapabilitiesofthissoftwareprograminclassroomsandlaboratories byteachersandstudentsinscienceandengineering,partof thistextisintendedto introducethecomputationalpowerofMATLABtomodernnumericalmethods.

MATLABhasseveraladvantages.Therearethreemajorelementsthathave contributedtoitsimmensepopularity.First,itisextremelyeasytousesince datacanbeeasilyentered,especiallyforalgorithmsthatareadaptabletoatable format.Thisisanimportantfeaturebecauseitallowsstudentstoexperiment withmanynumericalproblemsinashortperiodoftime.Second,itincludeshighlevelcommandsfortwo-dimensionalandthree-dimensional datavisualization,and presentationgraphics.Plotsareeasilyobtainedfromwithinascriptorincommand mode.Third,themostevidentpowerofaMATLABisitsspeedof calculation. Theprogramgivesinstantaneousfeedback.Becauseoftheir popularity,MATLAB andothersoftwaresuchasMAPLEandMathematicaarenowavailableinmost universitymicrocomputerlaboratories.

Oneoftheprimaryobjectivesofthistextistogivestudents aclearstep-by-step explanationofthealgorithmcorrespondingtoeachnumericalmethodused.To accomplishthisobjective,wehavedevelopedMATLABM-functionscontainedin

1

asupplementaryCD-ROMatthebackofthebook.TheseM-filescanbeusedfor theapplicationorillustrationofallnumericalmethodsdiscussedinthistext.Each M-functionwillenablestudentstosolvenumericalproblemssimplybyenteringdata andexecutingtheM-functions.

Itiswellknownthatthebestwaytolearncomputerprogrammingistowrite computerprograms.Therefore,webelievethatbyunderstandingthebasictheory underlyingeachnumericalmethodandthealgorithmbehindit,studentswillhave thenecessarytoolstowritetheirownprogramsinahigh-levelcomputerlanguage suchasCorFORTRAN.

AnotherfutureofMATLABisthatitprovidestheGraphicalUserInterface (GUI).Itisapictorialinterfacetoaprogramintendedtoprovidestudentswith afamiliarenvironmentinwhichtowork.Thisenvironmentcontainspushbuttons, togglebuttons,lists,menus,textboxes,andsoforth,allofwhicharealreadyfamiliartotheuser,sothattheycanconcentrateonusingtheapplicationratherthanon themechanicsinvolvedindoingthings.Theydonothavetotypecommandsatthe commandlinetoruntheMATLABfunctions.Forthisreason,we introducedGUI inthiseditiontomakeiteasierforthestudentstoruntheM-functionsofthebook. Areadmefilenamed”SUNPackagereadmecontainedinthedirectoryNMETH” oftheCDattachedatthebackcoverofthebook,explainsindetailsthestepsto followtoruntheMATLABfunctionsusingGUI.Inaddition, AppendixD shows theuseofGUIforsolvingseveralexamples.

1.2ANINTRODUCTIONTOMATLAB

InthissectionwegivetothereaderabrieftutorialintroductiontoMATLAB. Foradditionalinformationweurgethereadertousethereferenceanduser’sguides ofMATLAB.

1.2.1Matricesandmatrixcomputation

MATLABtreatsallvariablesasmatrices.Theyareassignedtoexpressionsby usinganequalsignandtheirnamesarecase-sensitive.Forexample,

>> A=[4-25;617;-106]

A= 4 25 617 106

Newrowsmaybeindicatedbyanewlineorbyasemicolon.Acolumnvector maybegivenas

>> x=[2;8;9]orx=[289]’

x=

2 INTRODUCTION

2 8 9

Elementsofthematrixcanbeanumberoranexpression,like

>> x=[21+212/42^3]

x= 2338

Onecandefineanarraywithaparticularstructurebyusingthecommand

x=a:step:b

Asanexample

>> y=[0:0.2:1]

y=

00.20000.40000.60000.80001.0000

>> y=[0:pi/3:pi]

y=

01 04722 09443 1416

>> y=[20:-5:2]

y= 2015105

MATLABhasanumberofspecialmatricesthatcanbegenerated bybuilt-in functions

>> ones(2)

ans= 11 11 amatrixofall1’s.

>> zeros(2,4)

ans= 0000 0000 a2 × 4matrixofzeros.

>> rand(2,4)

ans=

0.95010.60680.89130.4565

0 23110 48600 76210 0185

ANINTRODUCTIONTOMATLAB 3

a2 × 4randommatrixwithuniformlydistributedrandomelements.

>> eyes(3)

ans=

100 010 001

the3 × 3identitymatrix.

The diag functioneithercreatesamatrixwithspecifiedvaluesonadiagonalor extractsthediagonalentries.Forexample,

>> v=[325];

>> D=diag(v)

D=

300 020 005

a3 × 3diagonalmatrixwith v onthemaindiagonal.

Toextractthediagonalentriesofanexistingmatrix,the diag functionisused:

>> C=[2-47;318;-156];

>> u=diag(C)

u= 2 1 6

The linspace functiongeneratesrowvectorswithequallyspacedelements.The formofthefunctionis linspace(firstValue,lastValue,numValues)

where firstValue and lastValue arethestartingandendingvaluesinthesequence ofelementsand NumValues isthenumberofelementstobecreated.Forexample,

>> evens=linspace(0,10,6) evens= 0246810

Themostusefulmatrixfunctionsare

4 INTRODUCTION

eig eigenvaluesandeigenvectors inv inverse lu LUdecomposition

qr QRfactorization rank rank

Acomponent-by-componentadditionoftwovectorsofthesamedimensionsis indicatedas

>> x=[158]; >> y=[243]; >> x+y

ans= 3911

Multiplyingavectorormatrixbyascalarwillscaleeachelementofthevector ormatrixbythevalueofthescalar.

>> C=2*[13;42]

C= 26 84

>> v=3*[14-57]

v=

312 1521

Thecomponent-by-componentmultiplicationofthevectors xandyisindicatedas

>> x.*y

ans= 22024

Theinner,ordot,productoftwovectorsisascalerandcanbe obtainedbymultiplyingarowvectorandacolumnvector.Forexample,

>> u=[57-12]; v=[2;3;10;5]; >> u*v

ans= 31

Thetransposeofamatrixoravectorisdenotedbyaprimesymbol.Forexample

>> x’

ans=

ANINTRODUCTIONTOMATLAB 5

1 5 8

Thematrixoperationsofmultiplication,power,anddivisionareindicatedas

>> B=[13;42];

>> A=[25;06];

>> A*B

ans= 2216 2412

>> A^2

ans= 440 036

>> A/B

ans= 1 60000 1000

2.4000 0.6000

>> A.*B

ans= 215 012

Notethatthethreeoperationsofmultiplication,division,andpowercanoperate elementwisebyprecedingthemwithaperiod.

1.2.2Polynomials

MATLABprovidesanumberofusefulbuilt-infunctionsthatoperatesonpolynomials.Thecoefficientsofapolynomialarespecifiedbytheentriesofavector. Forexample,thepolynomial p(x)=2x3 5x2 +8isspecifiedby[2-508].To evaluatethepolynomialatagiven x weusethe polyval function.

>> c=[2-508];

>> polyval(c,2)

ans=

4

evaluatesthepolynomials p(x)=2x3 5x2 +8at x =2.

6 INTRODUCTION

Thefunction roots findsthe n rootsofapolynomialofdegree n.Forexample,to findtherootsofthepolynomial p(x)= x3 5x2 17x +21,enter

>> a=[1-5-1721]; >> roots(a)

ans=

7.0000 3.0000 1.0000

1.2.3Outputformat

WhileallcomputationsinMATLABareperformedindoubleprecision,theformat ofthedisplayedoutputcanbecontrolledbythefollowingcommands:

formatshortfixedpointwith4decimalplaces(thedefault) formatlongfixedpointwith14decimalplaces formatshortescientificnotationwith4decimalplaces formatlongescientificnotationwith15decimalplaces formatratapproximationbyratioofsmallintegers

Onceinvoked,thechosenformatremainsineffectuntilchanged. ItispossibletomaketheprintedoutputfromaMATLABfunctionlookgoodby usingthe disp and fprintf functions.

disp(X) displaysthearray X,withoutprintingthearrayname.If X isastring, thetextisdisplayed.Forexample,

disp(’TheinputmatrixAis’)

willdisplaythetextplacedinsinglequotes.Thefunction disp alsoallowsusto printnumericalvaluesplacedintextstrings.Forexample, disp([’Newton’smethodconvergesafter’,num2str(iter),’iterations’]) willwriteonthescreen Newton’smethodconvergesafter9iterations

Herethefunction num2str(iter) convertsanumbertoastring.

Theotherfunction fprintf ismoreflexibleandhastheform

fprintf(’filename’,’format’,list)

ANINTRODUCTIONTOMATLAB 7

where

filename isoptional;ifitisomitted,outputgoestothescreen.

format isaformatcontrolstringcontainingconversionspecificationsoranyoptional text.Theconversionspecificationscontroltheoutputofarrayelements.

Commonconversionspecificationsinclude:

%P.Qeforexponential

%P.Qffixedpoint

%P.Qgtoautomaticallyselecttheshorterof%P.Qeor%P.Qf wherePandQareintegersthatsetthefieldwidthandthenumberofdecimal places,respectively.

list isalistofvariablenamesseparatedbycommas,andthespecialformat \n producesanewline.

Forexample,thestatements

>> x=pi;y=4.679;z=9; >> fprintf(’\nx=%8.7f\ny=%4.3f\nz=%1.0f\n’,x,y,z)

printsonthescreen

x=3.1415927

y=4.679

z=9

1.2.4Planarplots

PlottingfunctionsisveryeasyinMATLAB.Graphsoftwo-dimensionalfunctions canbegeneratedbyusingtheMATLABcommand plot.Youcan,forexample,plot thefunction y = x2 +1overtheinterval[ 1, 2]withthefollowingcommands:

>> x=[-1:0.02:2];

>> y=x. ˆ2+1;

>> plot(x,y)

Theplotisshownin Figure1.1.Thecommand plot(x,y,’r+:’) willresultin r=red with + forpointsanddottedline.Use helpplot formanyoptions.

Toplotafunction f 1definedbyanM-file(see Subsection1.2.7)inaninterval [a,b],weusethecommand

>> fplot(’f1’,[a,b]).

8 INTRODUCTION

FIGURE1.1

Plotofthefunction f (x)= x2 +1 in [ 1, 2].

Otherfeaturescanbeaddedtoagivengraphusingcommandssuchas grid, xlabel, ylabel,title,etc....Forexample,thecommand gridon willcreategridlinesonthe graph.

Plotsofparametricallydefinedcurvescanalsobemade.Try, forexample,

t=[0:0.01:4*pi]; x=cos(2*t); y=sin(3*t); plot(x,y).

Multipleplotsonasinglegraphareillustratedby

>> x=[0:0.1:2*pi];

>> y1=cos(x);y2=sin(x);y3=cos(2*x); >> plot(x,y1,x,y2,x,y3)

1.2.53-Dmeshplots

Three-dimensionalor3-Dmeshsurfaceplotsaredrawnwiththefunction mesh. Thecommand mesh(z) createsathree-dimensionalperspectiveplotoftheelements ofthematrix z

Thefollowingexamplewillgeneratetheplotshownin Figure 1.2 ofthefunction z = e x2 y2 overthesquare[ 4, 4] × [ 4, 4].

>> [xy]=meshgrid(-4.0:0.2:4.0,-4.0:0.2:4.0);

>> z=exp(-x.^2-y.^2);

>> mesh(x,y,z)

ANINTRODUCTIONTOMATLAB 9 −1 −0.5 0 0.5 1 1.5 2 1 1.5 2 2.5 3 3.5 4 4.5 5

FIGURE1.2

Three-dimensionalsurface.

Thefirstcommandcreatesamatrixwhoseentriesarethepointsofagridin thesquare 4 ≤ x ≤ 4, 4 ≤ y ≤ 4withgrid0.2unitswideand0.2unitstall. Thesecondcommandcreatesamatrixwhoseentriesarethevaluesofthefunction z(x,y)atthegridpoints.Thethirdcommandusesthisinformation toconstruct thegraph.

Othercommandsrelatedto3-Dgraphicsare plot3 and surf.

1.2.6Functionfiles

MATLABcontainsavastcollectionofbuilt-infunctionsfromelementaryfunctionslikesineandcosine,tomoresophisticatedfunctions likematrixinversions, matrixeigenvalues,andfastFouriertransforms. Table1.1 containsasmallselectionofelementarymathematicalMATLABfunctionsand AppendixB contains additionallistsoffunctionsgroupedbysubjectarea.

Notethatallthesefunctionnamesmustbeinlowercases.MATLABfunctions mayhavesingleormultiplearguments.Forexample,

[U,D]=eig(A)

producesamatrix U whosecolumnsaretheeigenvectorsof A andadiagonalmatrix D withtheeigenvaluesof A onitsdiagonal.

10 INTRODUCTION −4 −2 0 2 4 −4 −2 0 2 4 0 0.2 0.4 0.6 0.8 1

cos(x) cosineof x

sin(x) sineof x

tan(x) tangentof x

sqrt(x) squarerootof x

abs(x) absolutevalueof x exp(x) exponentialof x

log(x) logtothebase e of x

log10(x) logtothebase 10 of x

cosh(x) hyperboliccosineof x

tanh(x) hyperbolictangentof x

asin(x) inversesinefunctionof x expm(A) exponentialofmatrix A

Table1.1 ElementarymathematicalMATLABfunctions.

1.2.7Definingfunctions

MATLABallowsuserstodefinetheirownfunctionsbyconstructinganM-filein theM-fileEditor/Debugger.Thefirstlineofafunctionhastheform

functiony=function name(inputarguments)

Asanexample,letusdefinethefunction f 1(x)=2x3 3x +1asanm.file.Using theEditor/Debuggeroranytexteditorlike emacs,or vi,weenter

functiony=f1(x)

y=2*x.ˆ3-3*x+1;

OncethisfunctionissavedasanM-filenamedf1.m,wecanusetheMATLAB commandwindowtocompute,forexample,

>> f1(2)

ans= 11

Userdefinedfunctionscanthemselveshavefunctionsasinputparameters.They canbeevaluatedinternallybyusingthefunction feval.Forexample,

>> x1=fzero(’f1’,0)

x1=

0.3949

givesthezeroof f1 closestto0.

ANINTRODUCTIONTOMATLAB 11

Wecanpassonefunction f1.m toanotherfunction f2.m inMATLABbyusing the@symbol:

>> f2(@f1)

Forexample,thebuilt-infunction quad(f,a,b) inMATLABapproximatelyintegratesthefunction y = f (x)from a to b.Tousethisbuilt-infunctiontoapproximatelyintegrate y =cos(πx)+2from x = 1to x =1,webeginbywritinga MATLABfunctioncalled f1.m:

functiony=f1(x) y=cos(pi*x)+2;

Ifweareinthecorrectdirectory,wetypeinMATLAB:

>> quad(@f1,-1,1)

ans=

4 00000001667477

1.2.8Relationsandloops

Likemostcomputerlanguages,MATLABoffersavarietyofflowcontrolstatementslike for,while,and if.Thestatements,thatweusetocontrolthefloware calledrelations.

The Relationaloperators inMATLABare

==equal

<=lessthanorequal

>=greaterthanorequal

˜=notequal

< lessthan

> greaterthan

Notethat“=”isusedinanassignmentstatementwhile“==”is usedinarelation.

Logicaloperators &and

| or ˜not if,for,whilestatements

12 INTRODUCTION

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.