373
Numerical and Analytical Methods with MATLAB Ā® for Electrical Engineers William Bober ā€¢ Andrew Stevens

Numerical and Analytical Methods with MATLAB for

  • Upload
    others

  • View
    19

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Numerical and Analytical Methods with MATLAB for

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

William Bober ā€¢ Andrew Stevens

Bober ā€¢ Stevens

ISBN: 978-1-4398-5429-7

9 781439 854297

9 0 0 0 0

K12515

Electrical Engineering

Combining academic and practical approaches to this important topic, Numerical and Analytical Methods with MATLABĀ® for Electrical Engineersis the ideal resource for electrical and computer engineering students. Based on a previous edition that was geared toward mechanical engineering students, this book expands many of the concepts presented in that book and replaces the original projects with new ones intended specifically for electrical engineering students.

This book includes:

ā€¢ An introduction to the MATLABĀ® programming environment ā€¢ Mathematical techniques for matrix algebra, root finding,

integration, and differential equationsā€¢ More advanced topics, including transform methods, signal

processing, curve fitting, and optimization ā€¢ An introduction to the MATLABĀ® graphical design environment,

SimulinkĀ®

Exploring the numerical methods that electrical engineers use for design analysis and testing, this book comprises standalone chapters outlining a course that also introduces students to computational methods and pro-gramming skills, using MATLABĀ® as the programming environment. Helping engineering students to develop a feel for structural programmingā€”not just button-pushing with a software programā€”the illustrative examples and extensive assignments in this resource enable them to develop the necessary skills and then apply them to practical electrical engineering problems and cases.

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

Numerical and Analytical M

ethods with M

ATLABĀ® for Electrical Engineers

K12515_Cover_mech.indd 1 7/27/12 9:01 AM

Page 2: Numerical and Analytical Methods with MATLAB for
Page 3: Numerical and Analytical Methods with MATLAB for

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

Page 4: Numerical and Analytical Methods with MATLAB for

CRC Series inCOMPUTATIONAL MECHANICS

and APPLIED ANALYSIS

Series Editor: J.N. ReddyTexas A&M University

Published Titles

ADVANCED THERMODYNAMICS ENGINEERING, Second EditionKalyan Annamalai, Ishwar K. Puri, and Miland Jog

APPLIED FUNCTIONAL ANALYSISJ. Tinsley Oden and Leszek F. Demkowicz

COMBUSTION SCIENCE AND ENGINEERINGKalyan Annamalai and Ishwar K. Puri

CONTINUUM MECHANICS FOR ENGINEERS, Third EditionThomas Mase, Ronald Smelser, and George E. Mase

DYNAMICS IN ENGINEERING PRACTICE, Tenth EditionDara W. Childs

EXACT SOLUTIONS FOR BUCKLING OF STRUCTURAL MEMBERSC.M. Wang, C.Y. Wang, and J.N. Reddy

THE FINITE ELEMENT METHOD IN HEAT TRANSFER AND FLUID DYNAMICS,Third Edition

J.N. Reddy and D.K. Gartling

MECHANICS OF LAMINATED COMPOSITE PLATES AND SHELLS:THEORY AND ANALYSIS, Second Edition

J.N. Reddy

MICROMECHANICAL ANALYSIS AND MULTI-SCALE MODELINGUSING THE VORONOI CELL FINITE ELEMENT METHOD

Somnath Ghosh

NUMERICAL AND ANALYTICAL METHODS WITH MATLABĀ®

William Bober, Chi-Tay Tsai, and Oren Masory

NUMERICAL AND ANALYTICAL METHODS WITH MATLABĀ®

FOR ELECTRICAL ENGINEERSWilliam Bober and Andrew Stevens

PRACTICAL ANALYSIS OF COMPOSITE LAMINATESJ.N. Reddy and Antonio Miravete

SOLVING ORDINARY AND PARTIAL BOUNDARY VALUE PROBLEMSIN SCIENCE and ENGINEERING

Karel Rektorys

STRESSES IN BEAMS, PLATES, AND SHELLS, Third EditionAnsel C. Ugural

Page 5: Numerical and Analytical Methods with MATLAB for

CRC Press is an imprint of theTaylor & Francis Group, an informa business

Boca Raton London New York

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

William Bober ā€¢ Andrew Stevens

Page 6: Numerical and Analytical Methods with MATLAB for

MATLABĀ® and SimulinkĀ® are trademarks of The MathWorks, Inc. and are used with permission. The Math-Works does not warrant the accuracy of the text or exercises in this book. This bookā€™s use or discussion of MATLABĀ® and SimulinkĀ® software or related products does not constitute endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular use of the MATLABĀ® and SimulinkĀ® software.

CRC PressTaylor & Francis Group6000 Broken Sound Parkway NW, Suite 300Boca Raton, FL 33487-2742

Ā© 2013 by Taylor & Francis Group, LLCCRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government worksVersion Date: 20120801

International Standard Book Number-13: 978-1-4665-7607-0 (eBook - PDF)

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, transmit-ted, 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.

Visit the Taylor & Francis Web site athttp://www.taylorandfrancis.com

and the CRC Press Web site athttp://www.crcpress.com

Page 7: Numerical and Analytical Methods with MATLAB for

v

Contents

Preface.............................................................................................................ixAcknowledgments...........................................................................................xiAbout.the.Authors........................................................................................ xiii

ā€‚ 1ā€‚ Numerical.Methods.for.Electrical.Engineers..........................................11.1 Introduction......................................................................................11.2 EngineeringGoals.............................................................................21.3 ProgrammingNumericalSolutions...................................................21.4 WhyMATLAB?................................................................................31.5 TheMATLABProgrammingLanguage............................................41.6 ConventionsinThisBook.................................................................51.7 ExamplePrograms.............................................................................5

ā€‚ 2ā€‚ MATLAB.Fundamentals.........................................................................72.1 Introduction......................................................................................72.2 TheMATLABWindows...................................................................82.3 ConstructingaPrograminMATLAB.............................................112.4 MATLABFundamentals................................................................122.5 MATLABInput/Output.................................................................212.6 MATLABProgramFlow.................................................................262.7 MATLABFunctionFiles................................................................322.8 AnonymousFunctions.....................................................................362.9 MATLABGraphics.........................................................................362.10 WorkingwithMatrices................................................................... 462.11 WorkingwithFunctionsofaVector................................................482.12 AdditionalExamplesUsingCharactersandStrings.........................492.13 InterpolationandMATLABā€™sinterp1Function.........................532.14 MATLABā€™stextscanFunction...................................................552.15 ExportingMATLABDatatoExcel.................................................57

Page 8: Numerical and Analytical Methods with MATLAB for

viā€ƒ ā—¾ā€ƒ Contents

2.16 DebuggingaProgram......................................................................582.17 TheParallelRLCCircuit.................................................................60Exercises....................................................................................................63Projects......................................................................................................63References..................................................................................................76

ā€‚ 3ā€‚ Matrices.................................................................................................773.1 Introduction................................................................................... 773.2 MatrixOperations.......................................................................... 773.3 SystemofLinearEquations.............................................................823.4 GaussElimination...........................................................................873.5 TheGauss-JordanMethod...............................................................923.6 NumberofSolutions.......................................................................943.7 InverseMatrix.................................................................................953.8 TheEigenvalueProblem................................................................100Exercises..................................................................................................104Projects....................................................................................................105Reference.................................................................................................108

ā€‚ 4ā€‚ Roots.of.Algebraic.and.Transcendental.Equations..............................1094.1 Introduction..................................................................................1094.2 TheSearchMethod.......................................................................1094.3 BisectionMethod.......................................................................... 1104.4 Newton-RaphsonMethod.............................................................1124.5 MATLABā€™sfzeroandrootsFunctions...................................113

4.5.1 ThefzeroFunction........................................................ 1144.5.2 TherootsFunction....................................................... 118

Projects.................................................................................................... 119Reference.................................................................................................128

ā€‚ 5ā€‚ Numerical.Integration.........................................................................1295.1 Introduction..................................................................................1295.2 NumericalIntegrationandSimpsonā€™sRule....................................1295.3 ImproperIntegrals.........................................................................1335.4 MATLABā€™squadFunction..........................................................1355.5 TheElectricField...........................................................................1375.6 ThequiverPlot..........................................................................1415.7 MATLABā€™sdblquadFunction...................................................143Exercises..................................................................................................146Projects....................................................................................................147

ā€‚ 6ā€‚ Numerical.Integration.of.Ordinary.Differential.Equations................1576.1 Introduction.................................................................................. 1576.2 TheInitialValueProblem..............................................................158

Page 9: Numerical and Analytical Methods with MATLAB for

Contentsā€ƒ ā—¾ā€ƒ vii

6.3 TheEulerAlgorithm......................................................................1586.4 ModifiedEulerMethodwithPredictor-CorrectorAlgorithm........1606.5 NumericalErrorforEulerAlgorithms...........................................1666.6 TheFourth-OrderRunge-KuttaMethod.......................................1676.7 SystemofTwoFirst-OrderDifferentialEquations.........................1696.8 ASingleSecond-OrderEquation...................................................1726.9 MATLABā€™sODEFunction...........................................................1756.10 BoundaryValueProblems.............................................................1796.11 SolutionofaTri-DiagonalSystemofLinearEquations.................180

MethodSummaryformequations.................................................1816.12 DifferenceFormulas......................................................................1836.13 One-DimensionalPlateCapacitorProblem...................................186Projects....................................................................................................190

ā€‚ 7ā€‚ Laplace.Transforms.............................................................................2017.1 Introduction..................................................................................2017.2 LaplaceTransformandInverseTransform....................................201

7.2.1 LaplaceTransformoftheUnitStep..................................2027.2.2 Exponential......................................................................2027.2.3 Linearity...........................................................................2037.2.4 TimeDelay.......................................................................2037.2.5 ComplexExponential...................................................... 2047.2.6 Powersoft........................................................................2057.2.7 DeltaFunction................................................................ 206

7.3 TransformsofDerivatives..............................................................2097.4 OrdinaryDifferentialEquations,InitialValueProblem................2107.5 Convolution................................................................................. 2207.6 LaplaceTransformsAppliedtoCircuits.........................................2237.7 ImpulseResponse..........................................................................227Exercises................................................................................................. 228Projects....................................................................................................229References................................................................................................232

ā€‚ 8ā€‚ Fourier.Transforms.and.Signal.Processing..........................................2398.1 Introduction..................................................................................2398.2 MathematicalDescriptionofPeriodicSignals:FourierSeries........2418.3 ComplexExponentialFourierSeriesandFourierTransforms........2458.4 PropertiesofFourierTransforms...................................................2498.5 Filters.............................................................................................2518.6 Discrete-TimeRepresentationofContinuous-TimeSignals...........2538.7 FourierTransformsofDiscrete-TimeSignals.................................2558.8 ASimpleDiscrete-TimeFilter........................................................258Projects....................................................................................................269References................................................................................................273

Page 10: Numerical and Analytical Methods with MATLAB for

viiiā€ƒ ā—¾ā€ƒ Contents

ā€‚ 9ā€‚ Curve.Fitting.......................................................................................2759.1 Introduction..................................................................................2759.2 MethodofLeastSquares...............................................................275

9.2.1 Best-FitStraightLine........................................................2759.2.2 Best-Fitmth-DegreePolynomial.......................................277

9.3 CurveFittingwiththeExponentialFunction................................2799.4 MATLABā€™spolyfitFunction....................................................2819.5 CubicSplines.................................................................................2859.6 TheFunctioninterp1forCubicSplineCurveFitting...............2879.7 CurveFittingwithFourierSeries..................................................289Projects....................................................................................................291

10ā€‚ Optimization.......................................................................................29510.1 Introduction..................................................................................29510.2 UnconstrainedOptimizationProblems.........................................29610.3 MethodofSteepestDescent..........................................................29710.4 MATLABā€™sfminuncFunction...................................................30110.5 OptimizationwithConstraints.....................................................30210.6 LagrangeMultipliers.................................................................... 30410.7 MATLABā€™sfminconFunction...................................................307Exercises..................................................................................................316Projects....................................................................................................316Reference.................................................................................................322

11ā€‚ Simulink..............................................................................................32311.1 Introduction..................................................................................32311.2 CreatingaModelinSimulink.......................................................32311.3 TypicalBuildingBlocksinConstructingaModel.........................32511.4 TipsforConstructingandRunningModels.................................32811.5 ConstructingaSubsystem.............................................................32911.6 UsingtheMuxandFcnBlocks......................................................33011.7 UsingtheTransferFcnBlock........................................................33011.8 UsingtheRelayandSwitchBlocks................................................33111.9 TrigonometricFunctionBlocks.....................................................334Exercises..................................................................................................337Projects....................................................................................................337Reference.................................................................................................339

Appendix.A:.RLC.Circuits...........................................................................341

Appendix.B:.Special.Characters.in.MATLABĀ®.Plots...................................353

Page 11: Numerical and Analytical Methods with MATLAB for

ix

Preface

IhavebeenteachingtwocoursesincomputerapplicationsforengineersatFloridaAtlanticUniversity(FAU)formanyyears.Thefirstcourseisusuallytakeninthestudentā€™ssophomoreyear;thesecondcourseisusuallytakeninthestudentā€™sjuniororsenioryear.Bothcomputerclassesarerunaslecture-laboratorycourses,andtheMATLABĀ®softwareprogramisusedinbothcourses.Tofamiliarizestudentswithengineering-typeproblems,approximatelysixorsevenprojectsareassignedduringthesemester.Studentshave,dependingonthedifficultyoftheproject,eitheroneweekortwoweekstocompleteeachproject.Ibelievethatthebestsourceforstu-dentstocompletetheassignedprojectsineithercourseisthistextbook.

This book has its origin in a previous textbook, Numerical and Analytical Methods with MATLABĀ® by William Bober, Chi-Tay Tsai, and Oren Masory,alsopublishedbyCRCPress.Thepreviousbookwasprimarilyoriented towardmechanicalengineeringstudents.IandJonathanPlantofCRCPressenvisionedthatasimilartextwouldfillaneedinelectricalengineeringcurricula;asaresult,IenlistedDr.AndrewStevenstoreplacetheprojectsintheexistingtextbookwiththoseoriented towardelectrical engineering students.Thisnew textbook retainsthephilosophyofteachingthatexistsintheoriginaltextbook.

TheadvantageofusingtheMATLABsoftwareprogramoverotherpackagesisthatitcontainsbuilt-infunctionsthatnumericallysolvesystemsoflinearequa-tions,systemsofordinarydifferentialequations,rootsoftranscendentalequations,integrals,statisticalproblems,optimizationproblems,signal-processingproblems,andmanyothertypesofproblemsencounteredinengineering.AstudentversionoftheMATLABprogramisavailableatareasonablecost.However,tostudents,thesebuilt-in functionsareessentiallyblackboxes.Bycombininga textbookonMATLABwithbasicnumericalandanalyticalanalysis(althoughIamsurethatMATLAB uses more sophisticated numerical techniques than are described inthesetextbooks),themysteryofwhattheseblackboxesmightcontainissomewhatalleviated.ThetextcontainsmanysampleMATLABprogramsthatshouldprovideguidancetothestudentoncompletingtheassignedprojects.Manyoftheprojectsinthisbookarenon-trivialand,Ibelieve,willbegoodtrainingforagraduatingengineerenteringindustryorinanadvanceddegreeprogram.

Page 12: Numerical and Analytical Methods with MATLAB for

xā€ƒ ā—¾ā€ƒ Preface

Furthermore,Ibelievethatthereisenoughmaterialinthistextbookfortwocourses,especiallyifthecoursesarerunaslecture-laboratorycourses.Theadvan-tageofrunningthesecourses(especiallythefirstcourse)asalecture-laboratorycourseisthattheinstructoris inthecomputerlaboratorytohelpthestudentsdebugtheirprograms.Thisincludesthesampleprogramsaswellastheprojects.

ThecommoncoreofthebookistheintroductiontotheMATLABprogram-mingenvironmentinChapter2.Then,dependingontheindividualcurriculum(buttypicallysophomoreyear),acoursemightproceedwithmathematicaltech-niques for matrix algebra, root finding, integration, and differential equations(Chapters3through6).Amoreadvancedcourse(perhapsinjuniororsenioryear)might include transform techniques (Chapters 7 and8) and advanced topics incurvefittingandoptimization(Chapters9and10).MATLABā€™sgraphicaldesignenvironment,SimulinkĀ®,isintroducedinChapter11andcouldberelocatedelse-whereinthesyllabus.

We have tried to make each chapter stand alone so that each may be rear-rangedbasedonthepreferenceoftheinstructor.Inmanycases,wehaveusedtheresistor-inductor-capacitor(RLC)circuitasanexample,andwehaveputthebasicderivationofthiscircuitinAppendixAtominimizethechapterdependenciesandfacilitatereordering.Inallcases,wehaveattemptedtoprovideillustrativeexamplesusingmoderntopicsinelectricalengineering.

Allchapters(exceptforChapter1)containprojects,andsomealsocontainsev-eralexercisesthatarelessdifficultthantheprojectsandmightbeassignedpriortoaprojectassignment.Allprojectsrequirethestudenttowriteacomputerprogram,mostrequiringtheuseofMATLABbuilt-infunctionsandsolvers.

Additional materials, including down loadable copies of all examples in thetextbook,areavailablefromtheCRCpresswebsite:

http://www.crcpress.com/product/isbn/9781439854297MATLAB and Simulink are registered trademarks of The MathWorks,

Incorporated.Forproductinformation,pleasecontact

TheMathWorks,Inc.3AppleHillDriveNatick,MA01760-2098USATel:508-647-7000Fax:508-647-7001E-mail:[email protected]:www.mathworks.com

William.BoberFlorida Atlantic University

Department of Civil Engineering

Page 13: Numerical and Analytical Methods with MATLAB for

xi

Acknowledgments

WewishtothankJonathanPlantofCRCPressforhisconfidenceandencourage-mentinwritingthistextbook.Inaddition,wewouldliketoexpressthankstoChrisLeGoffforhelpinpreparingtheartworkandtoPatrickFarrellandMichaelRohanfortheirtechnicalexpertise.

WealsowishtoexpressourdeepgratitudetoSelmaBober,TheresaStevens,andEmmaStevensfortoleratingthemanyhourswespentonthepreparationofthemanuscript,thetimethatotherwisewouldhavebeendevotedtoourfamilies.

Page 14: Numerical and Analytical Methods with MATLAB for
Page 15: Numerical and Analytical Methods with MATLAB for

xiii

Aboutā€‚theā€‚Authors

William.Bober,.Ph.D., receivedhisB.S.degree in civil engineering from theCity College of New York (CCNY), his M.S. degree in engineering sciencefromPrattInstitute,andhisPh.D.degreeinengineeringscienceandaerospaceengineering from Purdue University. At Purdue University, he was on a FordFoundation Fellowship; he was assigned to teach one engineering course eachsemester. After receiving his Ph.D., he went to work as an associate engineer-ing physicist in the Applied Mechanics Department at Cornell AeronauticalLaboratoryinBuffalo,NewYork.AfterleavingCornellLabs,hewasemployedas anassociateprofessor in theDepartmentofMechanicalEngineeringat theRochester Institute of Technology (RIT) for the following twelve years. AfterleavingRIT,heobtained employment atFloridaAtlanticUniversity (FAU) intheDepartmentofMechanicalEngineering.Morerecently,hetransferredtotheDepartmentofCivilEngineering atFAU.While atRIT,hewas theprincipalauthor of a textbook, Fluid Mechanics, published by John Wiley & Sons. HehaswrittenseveralpapersforThe International Journal of Mechanical Engineering Education (IJMEE) and more recently coauthored a textbook, Numerical and Analytical Methods with MATLABĀ®.

Andrew.Stevens,.Ph.D.,.P.E.,receivedhisbachelorā€™sdegreefromMassachusettsInstituteofTechnology,hismasterā€™sdegreefromtheUniversityofPennsylvania,andhisdoctoratefromColumbiaUniversity,allinelectricalengineering.Hedidhis Ph.D. thesis work at IBM Research in the area of integrated circuit designforhigh-speedopticalnetworks.WhileatColumbia,helecturedacourseinthecoreundergraduatecurriculumandwontheIEEESolid-StateCircuitsFellowship.He has held R&D positions at AT&T Bell Laboratories in the development ofT-carriermultiplexersystemsandatArgonneNationalLaboratoryinthedesignofradiation-hardenedintegratedcircuitsforcollidingbeamdetectors.Since2001,hehasbeenpresidentofElectricalScience,anengineeringconsultingfirmspecializinginelectricalhardwareandsoftware.Hehaspublishedarticlesinseveralscientificjournalsandholdsthreepatentsintheareasofanalogcircuitdesignandcomputeruserinterfaces.

Page 16: Numerical and Analytical Methods with MATLAB for
Page 17: Numerical and Analytical Methods with MATLAB for

1

Chapter 1

Numericalā€‚Methodsā€‚forā€‚Electricalā€‚Engineers

1.1ā€‚ ā€‚IntroductionAlldisciplinesofscienceandengineeringusenumericalmethodsfortheanaly-sisofcomplexproblems.However,electricalengineeringparticularlylendsitselfto computational solutions due to the highly mathematical nature of the fieldand its close relationship with computer science. It makes sense that engineerswho design high-speed computers would also use the computers themselves toaidinthedesign(aprocessknownasbootstrapping).Infact,theentirefieldofcomputer-aideddesign(CAD) isdedicated to thecreationand improvementofsoftwaretoolstoenabletheimplementationofhighlycomplexdesigns.

Thisbookdescribesvariousmethodsand techniques fornumerically solvingavarietyofcommonelectricalengineeringapplications,includingcircuitdesign,electromagneticfieldtheory,andsignalprocessing.Classicalengineeringcurriculateachavarietyofmethodsforsolvingtheseproblemsusingtechniquessuchaslinearalgebra,differentialequations,transforms,vectorcalculus,andthelike.However,inmanycases,thesearchforaclosed-formsolutionleadstoextremecomplexity,whichcancauseustolosephysicalinsightintotheproblem.Insolvingthesesameproblemsnumerically,wewilloftenreverttofundamentalphysicalrelations,suchasthedifferentialrelationshipbetweencapacitorcurrentandvoltageortheelectricfieldofapointcharge.Often,aproblemthatseemsintractablewhensolvedsym-bolicallycanbecometrivialwhensolvednumerically.Andsometimes,thesimplernumericalsolutioncanbeelusivebecausewearesousedtothinkingintermsofadvancedcalculus(aclassiccaseofnotbeingabletoseetheforestbutforthetrees).

Page 18: Numerical and Analytical Methods with MATLAB for

2ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

1.2ā€‚ ā€‚Engineeringā€‚GoalsSomefundamentalgoalsinengineeringinclude

ā—¾ Designnewproductsorimproveexistingones

ā—¾ Improvemanufacturingefficiency

ā—¾ Minimizecost,powerconsumption,andnonreturnableengineering(NRE)cost

ā—¾ Maximizeyieldandreturnoninvestment(ROI)

ā—¾ Minimizetimetomarket

Theengineerwill frequentlyusethe lawsofphysicsandmathematics toachievethesegoals.

Manyelectricalengineeringprocessesinvolveexpensivemanufacturingstepsthatarebothdelicateandtimeconsuming.Forexample,thefabricationofintegratedcir-cuitscaninvolvethousandsofmanufacturingsteps,includingwaferpreparation,maskcreation,photolithography,diffusionandimplantation,dicing,testing,packaging,andmore.Thesestepscantakeweeksormonthstoperformatsubstantialexpenseandincleanrooms.Anydesignmistakesrequirerepeatingtheprocess;thus,itisourjobasdesignerstomodelandsimulatedesignsasmuchaspossibleinadvanceofmanufacturetoeliminateflawsandminimizetheiterationsnecessarytoproducethefinalproduct.

Usingintegratedcircuitdesignasanexample,wemightusecomputersforthe

a.Designstage:Solvemathematicalmodelsofphysicalphenomena(e.g.,pre-dictingthebehaviorofPNjunctions)

b.Testingstage:Storeandanalyzeexperimentaldata(e.g.,comparingthelabo-ratory-measuredactualbehaviorofPNjunctionstotheprediction)

c.Manufacturingstage:Controllingmachineoperationstofabricateandtestsiliconwafersanddice

1.3ā€‚ ā€‚Programmingā€‚Numericalā€‚SolutionsPhysicalphenomenaarealwaysdescribedbyasetofgoverningequations,andnumeri-calmethodscanbeusedtosolvethesetofgoverningequationsevenintheabsenceofaclosed-formsolution.Numericalmethodsinvariablyinvolvethecomputer,andthecomputerperformsarithmeticoperationsondiscretenumbersinadefinedsequenceofsteps.Thesequenceofstepsisdefinedintheprogram.Ausefulsolutionisobtainedif

a.Themathematicalmodelaccuratelyrepresentsthephysicalphenomena;thatis,themodelhasthecorrectgoverningequations.

b.Thenumericalmethodisaccurate. c.Thenumericalmethodisprogrammedcorrectly.

Thistextismainlyconcernedwithitems(b)and(c).

Page 19: Numerical and Analytical Methods with MATLAB for

Numerical Methods for Electrical Engineersā€ƒ ā—¾ā€ƒ 3

Theadvantageofusingthecomputeristhatitcancarryoutmanycalculationsinafractionofasecond;atthetimeofthiswriting,computerspeedsaremeasuredinteraflops(trillionsoffloatingpointoperationspersecond).However,toleveragethispower,weneedtowriteasetofinstructions,thatis,aprogram.Fortheproblemsofinterestinthisbook,thedigitalcomputerisonlycapableofperformingarithmetic,logical, andgraphicaloperations.Therefore, arithmeticproceduresmustbedevel-opedforsolvingdifferentialequations,evaluatingintegrals,determiningrootsofanequation,solvingasystemoflinearequations,andsoon.Thearithmeticprocedureusuallyinvolvesasetofalgebraicequations.Acomputersolutionforsuchproblemsinvolvesdeveloping a computerprogram thatdefines a step-by-stepprocedure forobtainingananswertotheproblemofinterest.Themethodofsolutioniscalledanalgorithm.Dependingontheparticularproblem,wemightwriteourownalgorithm,orasweshallsee,wecanalsousethealgorithmsbuiltintoapackagelikeMATLABĀ®toperformwell-knownalgorithmssuchas theRunge-Kuttamethodfor solvingasetofordinarydifferentialequationsoruseSimpsonā€™sruleforevaluatinganintegral.

1.4ā€‚ ā€‚Whyā€‚MATLAB?MATLABwasoriginallywrittenbyDr.CleveMoleratUniversityofNewMexicointhe1970sandwascommercializedbyMathWorksinthe1980s.Itisageneral-purposenumericalpackagethatallowscomplexequationstobesolvedefficientlyand subsequently generate tabular or graphical output. While there are manynumerical packages available to electrical engineers, many are highly focusedtowardaparticularapplication(e.g.,SPICEformodelingelectroniccircuits).Also,MATLABisnottobeconfusedwithCADsoftwareforschematiccapture,layout,orphysicaldesign,althoughthissoftwareoftenintegrateswithanaccompanyingnumericalpackage.

Originally,MATLABwasacommand-lineprogramthatranonMS-DOSandUNIXhosts.Ascomputershaveevolved,sohasMATLAB,andmoderneditionsoftheprogramruninwindowedenvironments.Asofthetimeofthiswriting,MATLABR2011brunsnativelyonMicrosoftWindows,AppleMacOS,andLinux.Inthistext,we assume that you are running MATLAB on your local machine in a MicrosoftWindowsenvironment.Itshouldbestraightforwardfornon-Windowsuserstotranslatetheusagedescriptionstotheirpreferredenvironment.Inanycase,thesedifferencesarelargelylimitedtothecosmeticsandpresentationoftheprogramandnottheMATLABcommandsthemselves.AllversionsofMATLAB(onanyplatform)usethesamecom-mandset,andtheCommandWindowonallplatformsshouldbehaveidentically.

MATLABisofferedwithaccompanyingā€œtoolboxesā€atadditionalcosttotheuser.Awidevarietyoftoolboxesareavailableinfieldssuchascontrolsystems,imagepro-cessing,radiofrequency(RF)design,signalprocessing,andmore.However,inthistext,welargelyfocusonfundamentalnumericalconceptsandlimitourselvestobasicMATLABfunctionalitywithoutrequiringthepurchaseofanyadditionaltoolboxes.

Page 20: Numerical and Analytical Methods with MATLAB for

4ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

1.5ā€‚ ā€‚Theā€‚MATLABā€‚Programmingā€‚LanguageTherearemanymethodologiesforcomputerprogramming,butthetasksathandboildowntothefollowing:

a.Studytheproblemtobeprogrammed. b.Listthealgebraicequationstobeusedintheprogrambasedontheknown

physicalphenomenaandgeometriesoftheproblem. c.Create a general design for the program flow and algorithms, perhaps by

creatingaflowchartorbywritinghigh-levelpseudocodetooutlinethemainprogrammodules.

d.Carryoutasamplecalculationbyhandtoprovethealgorithm. e.Writetheprogramusingthelistofalgebraicequationsandtheoutline. f.Debugtheprogrambyrunningitandfixinganysyntaxerrors. g.Testtheprogrambyrunningitusingparameterswithaknown(orintui-

tive)solution. h.Iterateoverthesestepstorefineandfurtherdebugthealgorithmandpro-

gramflow. i.Ifnecessary,revisetheprogramtoobtainfasterperformance.

Experienced programmers might omit some of these steps (or do them in theirhead),buttheoverallprocessresemblesanyengineeringproject:design,createaprototype,test,anditeratetheprocessuntilasatisfactoryproductisachieved.

MATLABmaybeconsideredaprogrammingorscriptinglanguageuntoitself,butlikeeveryprogramminglanguage,ithasthefollowingcorecomponents:

a.Datatypes,i.e.,formatsforstoringnumbersandtextintheprogram(e.g.,integers,double-precisionfloatingpoint,strings,vectors,matrices)

b.Operators(e.g.,commandsforaddition,multiplication,cosine,log) c.Controlflowdirectivesformakingdecisionsandperformingiterativeopera-

tions(e.g.,if,while,switch) d.Input/output(ā€œI/Oā€)commandsforreceivinginputfromauserorfileand

forgeneratingoutputtoafileorthescreen(e.g.,fprintf,fscanf,plot,stem,surf)

MATLABborrowsmanyconstructs fromother languages.Forexample, thewhile,switch,andfprintfcommandsare fromtheCprogramming lan-guage(oritsdescendentsC++,Java,andPerl).However,therearesomefundamen-taldifferencesaswell.Forexample,MATLABstores functions (known inotherlanguagesasā€œsubroutinesā€)inseparatefiles.Thefirstentryinavector(knowninmostotherlanguagesasanarray)isindexedbythenumber1andnot0.However,thebiggestdifferenceisthatallMATLABvariablesarevectors,thusprovidingtheabilitytomanipulatelargeamountsofdatawithatersesyntaxandallowingforthe

Page 21: Numerical and Analytical Methods with MATLAB for

Numerical Methods for Electrical Engineersā€ƒ ā—¾ā€ƒ 5

solutionofcomplicatedproblemsinjustafewlinesofcode.Inaddition,becauseMATLABisnormallyruninteractively,itisalsorichinpresentationfunctionstodisplaysophisticatedplotsandgraphs.

1.6ā€‚ ā€‚Conventionsā€‚inā€‚Thisā€‚BookWeusethefollowingtypographicalconventionsinthistext:

ā—¾ Allinput/outputtoandfromMATLABareintypewriterfont.

ā—¾ Incaseswhereyouaretypingdirectlyintothecomputer,thetypedtextisdisplayedinbold.

Weillustratethisinthefollowingexample,forwhichweuseMATLABtofindthevalue =

Ļ€sin4

x :

>>x = sin(pi/4) x= 0.7071

Inthiscase,>>representsMATLABā€™sprompt,x=sin(pi/4)representstexttypedintotheMATLABcommandwindow,andx=0.7071representsMATLABā€™sresponse.

1.7ā€‚ ā€‚Exampleā€‚ProgramsTheexampleprogramsinthisbookmaybedownloadedfromthepublisherā€™sWebsiteathttp://www.crcpress.com/product/isbn/9781439854297.Studentsmaythenruntheexampleprogramsontheirowncomputerandseetheresults.Italsomaybebeneficialforstudentstotypeinafewofthesampleprograms(alongwithsomeinevitablesyntaxandtypographicalerrors),therebygivingthemtheopportunitytoseehowMATLABrespondstoprogramerrorsandsubsequentlylearnwhattheyneedtodotofixtheproblem.

Page 22: Numerical and Analytical Methods with MATLAB for
Page 23: Numerical and Analytical Methods with MATLAB for

7

Chapter 2

MATLABā€‚Fundamentals

2.1ā€‚ ā€‚IntroductionMATLABā€¢ is a software program for numeric computation, data analysis, andgraphics.OneadvantagethatMATLABhasforengineersoverprogramminglan-guagessuchasCorC++ isthattheMATLABprogramincludesfunctionsthatnumericallysolvelargesystemsoflinearequations,systemsofordinarydifferentialequations,rootsof transcendentalequations, integrals, statisticalproblems,opti-mizationproblems,controlsystemsproblems,andmanyothertypesofproblemsencounteredinengineering.MATLABalsoofferstoolboxes(whichmustbepur-chasedseparately)thataredesignedtosolveproblemsinspecializedareas.

Inthischapter,thefollowingitemsarecovered:

ā—¾ TheMATLABdesktopenvironment

ā—¾ Constructingascript(alsocalledaprogram)inMATLAB

ā—¾ MATLAB fundamentals and basic commands, including clear, clc,colon operator, arithmetic operators, trigonometric functions, logarithmicandexponential functions, andotheruseful functions suchasmax,min,andlength

ā—¾ Input/outputinMATLAB,includingtheinputandfprintfstatements

ā—¾ MATLAB program flow, including for loops, while loops, ifandelseifstatements,andtheswitchgroupstatement

ā—¾ MATLABfunctionfilesandanonymousfunctions

ā—¾ MATLABgraphics,includingtheplotandsubplotcommands

Page 24: Numerical and Analytical Methods with MATLAB for

8ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ā—¾ Workingwithmatrices

ā—¾ Workingwithfunctionsofavector

ā—¾ Workingwithcharactersandstrings

ā—¾ InterpolationandMATLABā€™sinterp1function

ā—¾ MATLABā€™stextscanfunction

ā—¾ ExportingMATLABdatatoothersoftware,suchasMicrosoftExcel

ā—¾ Debuggingaprogram

Manyexamplescriptsare includedthroughoutthechapterto illustratethesevarioustopics.

2.2ā€‚ ā€‚Theā€‚MATLABā€‚WindowsUnderMicrosoftWindows,MATLABmaybestartedviatheStartmenuorclickingontheMATLABicononthedesktop.Onstartup,anewwindowwillopencontain-ingtheMATLABā€œdesktopā€(nottobeconfusedwiththeWindowsdesktop),andoneormoreMATLABwindowswillopenwithinthedesktop(seeFigure 2.1forthe

Figureā€‚2.1ā€‚ MATLABā€‚desktopā€‚windows.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 25: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 9

defaultconfiguration).ThemainwindowsaretheCommandwindow,CommandHistory,CurrentFolder,andWorkspace.YoucancustomizetheMATLABwindowsthatappearonstartupbyopeningtheDesktopmenuandchecking(orunchecking)thewindowsthatyouwishtoappearontheMATLABdesktop.Figure 2.1showstheCommandwindow(inthecenter),theCurrentFolder(ontheleft),theWorkspace(onthetopright),theCommandHistory(onthebottomright),andtheCurrentFolderbox(intheicontoolbar,secondfromthetop,justabovetheCommandwin-dow).Thesewindowsandthecurrentfolderboxaresummarizedasfollows:

ā—¾ Command Window:IntheCommandwindowyoucanentercommandsanddata, make calculations, and print results. You can write a program in theCommand window and execute the program. However, writing a programdirectlyintotheCommandwindowisdiscouragedbecauseitwillnotbesaved,andifanerrorismade,theentireprogrammustberetyped.Byusingtheuparrow(ā†‘)keyonyourkeyboard,thepreviouscommandcanberetrieved(andedited)forreexecution.

ā—¾ Command History Window: ThiswindowlistsahistoryofthecommandsthatyouhaveexecutedintheCommandwindow.

ā—¾ Current Folder Box: This box lists the active Current Folder (also calledtheCurrentDirectoryinolderversionsofMATLAB).To.run.a.MATLAB.script.(program),the.script.of.interest.needs.to.be.in.the.folder.listed.in.this.box..Byclickingonthedownarrowwithinthebox,adrop-downmenuwillappearthatcontainsnamesoffoldersthatyouhavepreviouslyused.Thiswillallowyoutoselectthefolderinwhichthescriptofinterestresides(seeFigure2.2).Ifthefoldercontainingthescriptofinterestisnotlistedinthedrop-downmenu,youcanclickontheadjacentlittleboxcontainingthreedots,whichallowsyoutobrowseforthefoldercontainingtheprogramofinterest(seeFigure2.3).

ā—¾ Current Folder Window (on the left):Thiswindow lists all thefiles in theCurrentFolder.Bydoubleclickingonafileinthiswindow,thefilewillopenwithinMATLAB.

ā—¾ Script Window (also called theEditorwindow inolderMATLABversions):Toopenthiswindow,usetheFilemenuatthetopoftheMATLABdesktopandchooseNewandthenScript(orinolderversionsofMATLAB,clickonNew M-File)(seeFigure 2.4).TheScriptWindowmaybeusedtocreate,edit,andexecuteMATLABscripts.Scripts are then savedasM-Files.Thesefileshavetheextension.m,suchascircuit.m.Toexecutetheprogram,youcanclicktheSave and Run icon (thegreenarrow) in theScriptwindowor return totheCommandwindowandtypeinthenameoftheprogram(withoutthe.mextension).

Page 26: Numerical and Analytical Methods with MATLAB for

10ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Figureā€‚2.3ā€‚ Drop-downā€‚menuā€‚forā€‚selectingā€‚folderā€‚containingā€‚programā€‚ofā€‚interest.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Figureā€‚2.2ā€‚ Drop-downā€‚menuā€‚ inā€‚ theā€‚Currentā€‚ Folderā€‚window.ā€‚ (Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 27: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 11

2.3ā€‚ ā€‚Constructingā€‚aā€‚Programā€‚inā€‚MATLABThislistsummarizesthestepsforwritingyourfirstMATLABprogram:

1.StarttheMATLABdesktopviatheWindowsStartmenuorbydoubleclick-ingontheMATLABicononthedesktop.

2.ClickonFile-New-Script.ThisbringsupanewScriptwindow. 3.TypeyourscriptintotheScriptwindow. 4.SavethescriptbyclickingontheSaveiconintheicontoolbarorclickingon

FileinthemenubarandselectingSaveinthedropdownmenu.Inthedialogboxthatappears,selectthefolderwherethescriptistoresideandtypeinafilenameofyourownchoosing.ItisbesttouseafolderthatcontainsonlyyourownMATLABscripts.

5.Beforeyoucanrunyourscript,youneedtogototheCurrentFolderboxatthe topof theMATLABdesktop, clickingon thedownarrowand in thedropdownmenu,selecting(orbrowsingto)thefolderthatcontainsyournewscript.

6.YoumayrunyourscriptfromtheScriptwindowbyclickingontheSave and Rungreenarrowintheicontoolbar(seeFigure2.5)oralternatively,fromthe

Figureā€‚2.4ā€‚ Openingā€‚upā€‚theā€‚Scriptā€‚window.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 28: Numerical and Analytical Methods with MATLAB for

12ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

commandwindowbytypingthescriptname(withoutthe.mextension)aftertheMATLABprompt (>>). For example, if theprogramhas been saved ascircuit.m, then typecircuit after theMATLABprompt (>>), as shownbelow:

>> circuit

Ifyouneedadditionalhelpgettingstarted,youcanclickonHelpinthemenubarintheMATLABwindowandthenselectProduct Helpfromthedrop-downmenu.ThiswillbringupthehelpwindowasshowninFigure 2.6.Byclickingonthelittleā€˜+ā€™boxnexttotheMATLABlistingintheleftcolumn,youwillgetaddi-tionalhelptopicsasshowninFigure 2.7.Onceyouselectoneofthehelptopics,thehelpinformationwillbeintheright-handwindow.Youcanalsotypeinatopicinthesearchwindowtoobtaininformationonthattopic.

2.4ā€‚ ā€‚MATLABā€‚Fundamentals

ā—¾ Variablenames

āˆ’ muststartwithaletter.

Save and Run button

Figureā€‚2.5ā€‚ Saveā€‚andā€‚runā€‚buttonā€‚inā€‚theā€‚scriptā€‚window.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 29: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 13

āˆ’ cancontainletters,digitsandtheunderscorecharacter.

āˆ’ canbeofanylength,butmustbeuniquewithinthefirst19characters.

Note:Donotuseavariablenamethatisthesamenameasthenameofafile,aMATLABfunction,oraselfwrittenfunction.

ā—¾ MATLABcommandnamesandvariablenamesarecasesensitive.Uselowercaselettersforcommands.

ā—¾ Semicolons are usually placed after variable definitions and programstatementswhenyoudonotwantthecommandechoedtothescreen.Inthe absence of a semicolon, thedefined variable appears on the screen.For example, if you entered the following assignment in the commandwindow:

>>A = [3 4 7 6]

Figureā€‚2.6ā€‚ Productā€‚helpā€‚window.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 30: Numerical and Analytical Methods with MATLAB for

14ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Inthecommandwindow,youwouldsee

A= 3476 >>

Alternatively,ifyouaddthesemicolon,thenyourcommandisexecutedbut there is nothing printed to the screen, and the prompt immediatelyappearsforyoutoenteryournextcommand:

>>A = [3 4 7 6]; >>

ā—¾ Percentsign(%)isusedforacommentline.

ā—¾ AseparateGraphicswindowopenstodisplayplotsandgraphs.

ā—¾ Thereareseveralcommandsforclearingwindows,clearingtheworkspaceandstoppingarunningprogram.

Figureā€‚2.7ā€‚ Gettingā€‚startedā€‚inā€‚productā€‚helpā€‚window.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 31: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 15

clc clearstheCommandwindow clf clearstheGraphicswindow clear removesallvariablesanddatafromtheworkspace Ctl-C abortsaprogramthatmayberunninginaninfiniteloop

ā—¾ thequitorexitcommandsterminateMATLAB.

ā—¾ thesavecommandsavesvariablesordataintheworkspaceofthecurrentdirectory.Thefilenamecontainingthedatawillhave.matextension.

ā—¾ User-definedfunctions(alsocalledself-writtenfunctions)arealsosavedasM-files.

ā—¾ ScriptsandfunctionsaresavedasASCIItextfiles.Thus,theymaybewritteneitherinthebuilt-inScriptwindow,Notepad,oranywordprocessor(savedasatextfile).

ā—¾ ThebasicdatastructureinMATLABisamatrix.

ā—¾ Amatrix is surroundedbybrackets andmayhave anarbitrarynumberof

rowsandcolumns;forexample,thematrix =1 3

6 5A maybeenteredinto

MATLABas

>>A = [1 3<enter> 6 5];<enter>

or

>>A = [1 3 ; 6 5];<enter>

where the semicolon within the brackets indicates the start of a new rowwithinthematrix.

ā—¾ Amatrixofonerowandonecolumnisascalar;forexample:

>>A = [3.5];

Alternatively,MATLABalsoacceptsA = 3.5(withoutbrackets)asascalar.

ā—¾ Amatrixconsistingofonerowandseveralcolumnsoronecolumnandsev-eralrowsisconsideredavector;forexample:

>>A = [2 3 6 5] (rowvector)

>>A = [2 365](columnvector)

Page 32: Numerical and Analytical Methods with MATLAB for

16ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Amatrixcanbedefinedbyincludingasecondmatrixasoneoftheelements;example:

>> B = [1.5 3.1]; >> C = [4.0 B]; (thusC=[4.01.53.1])

ā—¾ AspecificelementofmatrixCcanbeselectedbywriting

>>a = C(2);(thusa =1.5)

Ifyouwishtoselectthelastelementinavector,youcanwrite

>>a = c(end);.(thusa =3.1)

ā—¾ Thecolonoperator(:)maybeusedtocreateanewmatrixfromanexistingmatrix;forexample:

if

5 7 10

2 5 2

1 3 1

A=

then gives521

x= A(:,1) x =

ThecolonintheexpressionA(:,1)impliesalltherowsinmatrixA,andthe1 impliescolumn1.

gives =

7 10

5 2

3 1

x= A(:,2:3) x

ThefirstcolonintheexpressionA(:,2:3)impliesalltherowsinA,andthe2:3impliescolumns2and3.

Wecanalsowrite

y=A(1,:),whichgivesy=[5710]

The1impliesthefirstrow,andthecolonimpliesallthecolumns.

Page 33: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 17

ā—¾ Acoloncanalsobeusedtogenerateaseriesofnumbers.Theformatis:

n=startingvalue:stepsize:finalvalue.Ifomitted,thedefaultstepsizeis1.Forexample:

gives 1 2 3 4 5 6 7 8 .n = 1:8 n [ ]=

Toincrementinstepsof2,use

gives 1 3 5 7n=1:2:7 n [ ]=

Thesetypesofexpressionsareoftenusedinaforloop,whichisdiscussedlaterinthischapter.

ā—¾ Arithmeticoperators:

+ addition

- subtraction* multiplication/ division^ exponentiation

ā—¾ Todisplayavariablevalue,justtypethevariablenamewithoutthesemico-lon,andthevariablewillappearonthescreen.

Examples(trytypingthesestatementsintotheCommandwindow):

clc; x = 5; y = 10; z = x + y w = x ā€“ y z = y/x z = x*y z = x^2

Notethatinthearithmeticstatementz=x+y,thevaluesforxandywereassignedinthetwopriorlines.Ingeneral,allvariablesontheright-handsideofanarithmeticstatementmustbeassignedavaluebeforetheyareused.

ā—¾ Specialvalues:

pi Ļ€

i or j āˆ’1

inf āˆž

ans the last computed unassigned result to an expression typed in the Command window

Page 34: Numerical and Analytical Methods with MATLAB for

18ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Examples(trytypingthesestatementsinthecommandwindow):

x = pi; z = x/0(givesinf )

ā—¾ Trigonometricfunctions:

sin sinesinh hyperbolic sineasin inverse sineasinh inverse hyperbolic sinecos cosinecosh hyperbolic cosineacos inverse cosineacosh inverse hyperbolic cosinetan tangenttanh hyperbolic tangentatan inverse tangentatan2 four-quadrant inverse tangentatanh inverse hyperbolic tangentsec secant

sech hyperbolic secantasec inverse secantasech inverse hyperbolic secantcsc cosecantcsch hyperbolic cosecantacsc inverse cosecantacsch inverse hyperbolic cosecantcot cotangentcoth hyperbolic cotangentacot inverse cotangentacoth inverse hyperbolic cotangent

Theargumentsofthesetrigonometricfunctionsareinradians.However,theargumentscanbemadeindegreesifaā€œdā€ isplacedafterthefunctionname,suchassind(x).

Examples(trytypingthesestatementsintotheCommandwindow):

clc; x = pi/2; y = sin(x)

Page 35: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 19

z = atan(1.0) x = 30; w = sind(x) z = atand(1.0)

ā—¾ Exponential,squareroot,anderrorfunctions:

exp exponential

log natural logarithm

log10 common (base 10) logarithm

sqrt square root

erf error function

Examples(trytypingthesestatementsintotheCommandwindow):

clc; x = 2.5; y = exp(x) z = log(y) w = sqrt(x)

ā—¾ Complexnumbers:

Complexnumbersmaybewrittenintwoforms:Cartesian,suchasz=x+yj;orpolar,suchasz=r*exp(j*theta).Notethatweusejfor āˆ’1throughoutthistext.However,MATLABallowstheuseofifor āˆ’1aswell.Note:iandjarealsolegalMATLABvariablenameswhichareoftenusedwithinloops.Toavoidconfusion,programswhichinvolvecom-plexnumbersshouldnotuseiorjasvariablenames.

abs absolute value (magnitude)

angle phase angle (in radians)

conj complex conjugate

imag complex imaginary part

real complex real part

Examples(trytypingthesestatementsintotheCommandwindow):

clc; z1 = 1 + j; z2 = 2 * exp(j * pi/6) y = abs(z1)

Page 36: Numerical and Analytical Methods with MATLAB for

20ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

w = real(z2) v = imag(z1) phi = angle(z1)

ā—¾ Otherusefulfunctions:

length(X) Gives the number of elements in the vector X.

size(X) Gives the size (number of rows and the number of columns) of matrix X.

sum(X) For vectors, sum(X) gives the sum of the elements in X. For matrices, gives a row vector containing the sum of the elements in each column of the matrix.

max(X) For vectors, max(X) gives the maximum element in X. For matrices, max(X) gives a row vector containing the maximum in each column of the matrix. If X is a column vector, it gives the maximum value of X.

min(X) Same as max(X)except it gives the minimum element in X.

sort(X) For vectors, sort(X) sorts the elements of X in ascending order. For matrices, sort(X) sorts each column in the matrix in ascending order.

factorial(n) n ! = 1 Ɨ 2 Ɨ 3 Ɨ ā‹Æ Ɨ n

mod(x,y) modulo operator, gives the remainder resulting from the division of x by y. For example, mod(13,5)=3, that is, 13 Ć· 5 gives 2 plus remainder of 3 (the 2 is discarded). As another example,mod(n,2)gives zero if n is an even integer and one if n is an odd integer.

Examples(trytypingthesestatementsintotheCommandwindow):

clc; A = [2 15 6 18]; length(A) y = max(A) z = sum(A) A = [2 15 6 18; 15 10 8 4; 10 6 12 3]; x = max(A) y = sum(A) size(A) mod(21,2) mod(20,2)

ā—¾ Alistofthecompletesetofelementarymathfunctionscanbeobtainedbytypinghelp elfunintheCommandwindow.

Page 37: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 21

ā—¾ Sometimes,itisnecessarytopreallocateamatrixofagivensize.Thiscanbedonebydefiningamatrixofallzerosorones;forexample:

=

0 0 0

0 0 0

0 0 0

A = zeros(3)

0 0

0 0

0 0

B = zeros(3,2)=

1 1 1

1 1 1

1 1 1

C = ones(3)=

1 1 1

1 1 1D = ones(2,3)=

Thefunctiontogeneratetheidentitymatrix(maindiagonalofones;allotherelementsarezero)iseye;example:

1 0 0

0 1 0

0 0 1

I = eye(3)=

2.5ā€‚ ā€‚MATLABā€‚Input/Outputā—¾ Ifyouwishtohaveyourprogrampausetoacceptinputfromthekeyboard,

usetheinputfunction;forexample,toentera2by3matrix,use

Z=input('EntervaluesforZinbrackets\n');

thentypein:

[5.1 6.3 2.5; 3.1 4.2 1.3]

Page 38: Numerical and Analytical Methods with MATLAB for

22ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus,

=

5.1 6.3 2.5

3.1 4.2 1.3Z

Notethattheargumenttoinput()isacharacterstringenclosedbysinglequotationmarks,whichwillbeprintedtothescreen.The\n(newline)tellsMATLABtomove thecursor to thenext line.Alternatively,\t (tab) tellsMATLABtomovethecursorseveralspacesalongthesameline.

If youwish to enter textdata toinput, youneed to enclose the textwithsinglequotationmarks.However,youcanavoidthisrequirementbyentering a secondargumentof's' toinput as shown in the followingstatement:

response=input('Plotfunction?(y/n):\n','s');

Inthiscase,theusercanrespondwitheitherayorn(withoutsinglequo-tationmarks).

Examples(trytypingthesestatementsintotheCommandwindow):

z = input ('Enter a 2x3 matrix of your choosing\n')

name=input('Enter name enclosed by single quote marks:')

response = input('Plot function? (y/n):\n', 's');

ā—¾ Thedisp commandprints just the contentsof amatrixor alphanumericinformation;forexample(assumingthatmatrixXhasalreadybeenenteredintheCommandwindow):

>> x = [3.6 7.1]; disp(X); disp('volt');

Thefollowingwillbedisplayedonthescreen:

3.60007.1000 volt >>

ā—¾ Thefprintf commandprints formatted text to the screenor toafile;forexample:

>>I = 2.2; >>fprintf ('The current is %f amps \n', I);

Page 39: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 23

Thefollowingwillappearonthescreen:

Thecurrentis2.200000amps

The%freferstoaformattedfloatingpointnumber,andthedefaultissixdecimalplaces(althoughinearlierversionsofMATLAB,thedefaultfor%fformatwasfourdecimalplaces).

fprintfusesformatstringsbasedontheCprogramminglanguage[1].Thus,youcanspecifytheminimumnumberofspacesfortheprintedvariableaswellasthenumberofdecimalplacesusing

%8.2f

Thiswillalloweightspacesforthevariable,totwodecimalplaces.Youcanalsospecifyjustthenumberofdecimalplaces,forexample,saythreedecimalplaces,andthenletMATLABautomaticallydecidethenumberofspacesforthevariableusing

%.3f

However,tocreateneatlookingtables,itisbesttospecifythenumberofspacesintheformatstatementthatallowsforseveralspacesbetweenvariablesinadjacentcolumns.

Otherformatsareasfollows:

%i or %d used for integers

%e scientific notation (e.g., 6.02e23), with defaultsix decimal places

%g automatically use the briefest of %f or %e format

%s used for a string of characters

%c used for a single character

UnlikeC,theformatstringinMATLABā€™sfprintfmustbeenclosedbysinglequotationmarks(andnotdoublequotes).

Sometimes,theformatpartofthefprintfcommandmaybetoolongtofitonasinglelineinyourscript.Whenthishappens,youcanusethreedots(...) totellMATLABtocontinuethestatementonasecondline,asshownbythefollowingexample:

fprintf('resistance=%fvolts=%fcurrent=%f\n',... R,V,I);

Page 40: Numerical and Analytical Methods with MATLAB for

24ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ThreedotsmaybeusedtocontinueanyMATLABstatementontoaddi-tionallinestoimprovethereadabilityofyourscript,asshownbythefollow-ingstatement:

a=(-4*pi^2*omega^2*r^2*(cos(arg1))^2/sqrt(arg2)+... 4*pi^2*omega^2*r^2*(sin(arg1))^2/sqrt(arg2))*... exp(j*pi*omega);

Analternativetousingthethreedotstoextendalengthyarithmeticstate-mentontomorethanonelineistobreakupthestatementintoseveralsmallerstatementsandthencombinethem.Asanexample,wecouldbreakupthepreviousstatementintothreeshorterstatementstocalculatea:

a1=-4*pi^2*omega^2*r^2*(cos(arg1))^2/sqrt(arg2); a2=4*pi^2*omega^2*r^2*(sin(arg1))^2/sqrt(arg2); a=(a1+a2)*exp(j*pi*omega);

ā—¾ Printingtoafile:ItisoftenusefultoprinttheresultsofaMATLABpro-gramtoafile,possiblyforinclusioninareport.Inaddition,programoutputthat isprintedtoafilecansubsequentlybeeditedwithinthefile,suchasaligningoreditingcolumnheadingsinatable.Beforeyoucanprinttoafile,youneedtoopenafileforprintingwiththecommandfopen.Thesyntaxforfopenis

fo=fopen('filename','w')

Thus,foisapointertothefilenamedfilename,andthewindi-cateswriting.

Toprinttofilenameuse

fprintf(fo,'format',var1,var2,...);

wheretheformatstringcontainsthetextformatforvar1,var2,andsoon.Whenyouarefinishedwithallofyourprintstatements,youshouldclosethefilewiththefclosecommand,asshowninthefollowingexample.

Example(writethissimpleprogramintheScriptwindowandsaveitasio_example.m):

%io_example.m %Thisprogramisatestforprintingtoafile. clear;clc; V=120; I=2.2; fo=fopen('output.txt','w'); fprintf(fo,'V=%4ivolt,I=%5.2famp\n',V,I); fclose(fo);

Page 41: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 25

The extension on the output file should be .txt (otherwise, MATLABwillstarttheimportwizard).TheresultingoutputfilecanbeopenedfromeithertheScriptwindowortheCommandwindow.Toaccesstheoutputfile,clickonFile-Open,whichbringsupthescreenshowninFigure 2.8.IntheboxlabeledFile name,typein*.txt. Thiswillbringupallthefileswiththeextension.txt.Toopenthefileofinterest,doubleclickonthenameoftheoutputfile(inthisexample,thefilenameisoutput.txt). InearlierversionsofMATLAB,youwouldnotbeabletoopentheoutputfilewithoutincludingthefclose(fo) statement in theprogram.None the less it is still goodpracticetoincludethefclosestatementafteralltheoutputstatementsintheprogramorattheendoftheprogramitself.

ā—¾ Thefscanfcommandmaybeusedtoreadfromanexistingfileasfollows:

A=zeros(n,m); fi=fopen('filename.txt','r'); [A]=fscanf(fi,'%f',[n,m]);

wheren Ɨmisthenumberofelementsinthedatafile.Theā€˜rā€™inthefopenstatementindicatesthatthefileisforreadingdataintotheprogram.

Then Ɨmmatrixisfilledincolumnorder.Thus,rowsbecomecolumns,andcolumnsbecomerows.Tousethedatainitsoriginalorder,transposethe

Figureā€‚2.8ā€‚ Filesā€‚withā€‚extensionā€‚.txt.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 42: Numerical and Analytical Methods with MATLAB for

26ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

read-inmatrix.Totransposeamatrix AinMATLAB,simplytypeinA'.Thischangescolumnstorowsandrowstocolumns.

ā—¾ Anexistingdatafilecanalsobeenteredintoaprogrambytheloadcom-mand.Theload command,unlikethefscanfcommand,leavesrowsasrowsandcolumnsascolumns.

Forexample: loadfilename.txt x=filename(:,1); y=filename(:,2);

Theinputfilemusthavethesamenumberofrowsineachcolumn.

2.6ā€‚ ā€‚MATLABā€‚Programā€‚Flowā—¾ Thefor loopprovidesthemeanstocarryoutaseriesofstatementswithjust

afewlinesofcode.

Syntax:form=1:20

statement;ā‹®

statement; end

MATLABsetstheindexmto1,carriesoutthestatementsbetweentheforandendstatements,thenreturnstothetopoftheloop,changesmto2,andrepeatstheprocess.Afterthe20thiteration,theprogramexitstheloop.Anystatementthatisnottoberepeatedshouldnotbewithinthefor loop.Forexample,tableheadingsthatarenottoberepeatedshouldbeoutsidethefor loop.

Example(writethissimpleprogramintheScriptwindow,saveitasfor_loop_example.m,andrunthescript):

%for_loop_example.m clear;clc; %Tableheadings: fprintf('n y1 y2\n'); fprintf('-----------------------------------\n'); %Usingtheindexintheforloopinanarithmeticstatement forj=1:10 y1=j^2/10; y2=j^3/100; fprintf('%5i %10.3f%10.3f\n',j,y1,y2); end

Page 43: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 27

Note:Iftheindexinaforloopisusedtoselectanelementofamatrix,thenthe indexmustbean integer.However, ifyouarenotusing theforindexasamatrixindex,thentheforindexneednotbeanintegerasshowninthefollowingexample(writethissimpleprogramintheScriptwindow,saveitasfor_loop_example2.m,andrunthescript):

%for_loop_example2.m %Usingarangeofnon-integerxvaluesinaforloop. %Therangeofxisfrom-0.9to+0.9instepsof0.1. clear;clc; %printthetableheaderoutsideofthe'for'loop: fprintf('x y1 y2\n'); fprintf('-----------------------------------\n'); forx=-0.9:0.1:0.9 y1=x/(1-x); y2=y1^2; fprintf('%5.2f %10.3f%10.3f\n',x,y1,y2); end

ā—¾ Thewhile loop

Syntax: n=0; whilen<10 n=n+1; statement; ā‹® statement; end

Inthewhile loop,MATLABwillcarryout thestatementsbetweenthewhileandendstatementsaslongastheconditioninthewhilestatementissatisfied.Ifanindexintheprogramisrequired,theuseofthewhileloopstatement(unliketheforloop)requiresthattheprogramcreateitsownindex,asshownabove.Notethatthestatementā€œn=n+1ā€maynotmakesensealge-braicallybutdoesmakessenseintheMATLABlanguage.Theā€œ=ā€operatorinMATLAB(asinmanycomputerlanguages)istheassignmentoperator,whichtellsMATLABtofetchthecontentsofthememorycellcontainingthevariablen,putitsvalueintothearithmeticunitoftheCPU(centralprocessingunit),incrementby1,andputthenewvaluebackintothememorycelldesignatedforthevariablen.Thus,theoldvalueofnhasbeenreplacedbythenewvalueforn.

ā—¾ ifstatement

Syntax:iflogicalexpression

Page 44: Numerical and Analytical Methods with MATLAB for

28ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

statement; ā‹®statement;

else statement;

ā‹® statement;end

Ifthelogicalexpressionistrue,thenonlytheuppersetofstatementsisexecuted.Ifthelogicalexpressionisfalse,thenonlythebottomsetofstate-mentsisexecuted.

ā—¾ Logicalexpressionsareoftheform

a==b; a<=b;

a<b; a>=b;

a>b; a~=b; (a not equal to b)

ā—¾ Compoundlogicalexpressions

a>b && a~=c (a > b AND a ā‰  c)

a>b || a<c (a > b OR a < c)

ā—¾ Theif-elseifladder

Syntax:iflogicalexpression1

statement(s);elseiflogicalexpression2

statements(s);elseiflogicalexpression3

statement(s); else

statement(s);end

Theif-elseifladderworksfromtopdown.Ifthetoplogicalexpressionistrue,thestatementsrelatedtothatlogicalexpressionareexecuted,andthepro-gramwillleavetheladder.Ifthetoplogicalexpressionisnottrue,theprogrammovestothenextlogicalexpression.Ifthatlogicalexpressionistrue,theprogramwillexecutethegroupofstatementsassociatedwiththatlogicalexpressionandleavetheladder.Ifthatlogicalexpressionisnottrue,theprogrammovestothenextlogicalexpressionandcontinuestheprocess.Ifnoneofthelogicalexpres-sionsaretrue,theprogramwillexecutethestatementsassociatedwiththeelse

Page 45: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 29

statement.Theelsestatementisnotrequired.Inthatcase,ifnoneofthelogicalexpressionsaretrue,nostatementswithintheladderwillbeexecuted.

ā—¾ Thebreak commandmaybeusedwithina fororwhile looptoendtheloop;forexample:

form=1:20statement;

ā‹®statement;ifm>10

break;end

end

Inthisexample,whenmbecomesgreaterthan10,theprogramleavesthefor loopandmovesontothenextstatementintheprogram.

ā—¾ Theswitchgroup

Syntax:switch(var)

casevar1statement(s);

casevar2statement(s);

casevar3statement(s);

otherwisestatement(s);

end

wherevartakesonthepossiblevaluesvar1,var2,var3,andsoon. Ifvar equalsvar1, those statementsassociatedwithvar1areexecuted,

andtheprogramleavestheswitchgroup.Ifvardoesnotequalvar1,thepro-gramtestsifvarequalsvar2,andifyes,theprogramexecutesthosestatementsassociatedwithvar2andleavestheswitchgroup.Ifvardoesnotequalanyofvar1,var2,andsoon,theprogramexecutesthestatementsassociatedwiththeotherwisestatement.Ifvar1,var2,andsoonarestrings,theyneedtobeenclosedbysinglequotationmarks.Itshouldbenotedthatvarcannotbealogi-calexpression,suchasvar1>=80.Forexample(writethissimpleprogramintheScriptwindow,saveitasswitch_example.m,andruntheprogram):

% switch_example.m %Thisprogramisatestoftheswitchstatement. clear;clc;

Page 46: Numerical and Analytical Methods with MATLAB for

30ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

var='a'; x=5; switch(var) case'b' z=x^2; case'a' z=x^3; end fprintf('z=%6.1f\n',z);

Additionalexampleprogramsfollowthatdemonstrate theuseof thefor loop,nestedfor loops,thewhile loop,theif statement,theif-elseif statements, thebreak statement, theinput statement, and thefprintf statement.SinceanumberofthesesampleprogramsinvolvedeterminingexbyaTaylorseriesexpansion,westartwithadiscussionoftheseriesexpansionofex.

Exampleā€‚2.1:ā€‚ Calculationā€‚ofā€‚ex

The Taylor series expansion of ex to n terms is

= + + + + + +

n

e xx x x x

nx

n

Term index: 1 2 3 4

12! 3! 4! !

2 3 4

There are several possible programming algorithms to calculate this series. The simplest method is to start with sum=1 and then evaluate each term using exponentiation and MATLABā€™s factorial function and add the obtained term to sum. An alternative approach would be to evaluate each term individually, save them in an array, and then use MATLABā€™s sum function to add them all. However, for some series expressions it is best to compute each term in the series based on the value of the preceding term. For example, in the above series, we can see that the third term in the series can be obtained from second term by multiplying the second term by x and dividing by 3; that is, term3 = term2 ā‹… x/3. In general, term (n) = term(nā€“1) ā‹… x/n.

%Example_2_1.m%Thisprogramcalculatese^xbyseriesandbyMATLAB's%exp()function.The'for'loopendswhenthetermonly%affectstheseventhsignificantfigure.%Note:e^x=1+x+x^2/2!+x^3/3!+x^4/4!+...clear;clc;x=5.0;s=1.0;forn=1:100term=x^n/factorial(n);s=s+term;

Page 47: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 31

if(abs(term)<=s*1.0e-7)break;endendex1=s;ex2=exp(x);fprintf('x=%3.1fex1=%8.5fex2=%8.5f\n',x,ex1,ex2);------------------------------------------------------------

Exampleā€‚2.2:ā€‚ Nestedā€‚Loops

%Example_2_2.m%Thisprogramillustratestheuseofnestedloops,i.e.%aninner'for'loopinsideanouter'for'loop.%Theprogramcalculatese^xbybothMATLAB's'exp'%command(variable'ex2'),andbyaTaylorseries%expansion(variable'ex1'),where-0.5<x<0.5.%Theouter'for'loopisusedtodeterminethex%values.TheinnerloopisusedtodeterminetheTaylor%seriesmethodforevaluatinge^x.Inthisexample,%term(n+1)isobtainedbymultiplyingterm(n)byx/n.%Thevariable'term'isestablishedasavectorsothat%MATLAB'sbuilt-in'sum'functioncanbeusedtosum%allthetermscalculatedintheTaylorseriesmethod.%Amaximumoffiftytermsisusedintheseries.%Programoutputissentbothtothescreenandtoa%file.Byprintingtheoutputtoafile,youcaneasily%edittheoutputfiletolineupcolumnheadings,%etc.(whichyoucan'tdowhenprintingtothescreen).%Note:e^x=1+x+x^2/2!+x^3/3!+x^4/4!+...clear;clc;xmin=-0.5;dx=0.1;fo=fopen('output.txt','w');%Tableheadingsfprintf('xex1ex2\n');fprintf('-------------------------------------\n');fprintf(fo,'xex1ex2\n');fprintf(fo,'-------------------------------------\n');fori=1:11x=xmin+(i-1)*dx;ex2=exp(x);term(1)=1.0;forn=1:49term(n+1)=term(n)*x/n;ifabs(term(n+1))<=1.0e-7break;endendex1=sum(term);fprintf('%5.2f%10.5f%10.5f\n',x,ex1,ex2);fprintf(fo,'%5.2f%10.5f%10.5f\n',x,ex1,ex2);endfclose(fo);------------------------------------------------------------

Page 48: Numerical and Analytical Methods with MATLAB for

32ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Note: In this example, the two statements

fori=1:11 x=xmin+(i-1)*dx;

could be replaced with the following single statement:

forx=-0.5:0.1:0.5

This approach is acceptable when the for loop index is not used to select an element of a matrix. In MATLAB, the variable selecting an element of a matrix must be an integer.

Exampleā€‚2.3:ā€‚ Whileā€‚Loop

%Example_2_3.m%Calculationofe^xbybothMATLAB'sexpfunctionand%theTaylorseriesexpansionofe^x.Theinput()%functionisusedtoestablishtheexponentx.%A'while'loopisusedindeterminingtheseries%solution.A'break'statementisusedtoendtheloop%ifthenumberoftermsbecomesgreaterthan50.The%displaystatementisusedtodisplaythevaluesofx,%exandex2inthecommandwindow.%Note:e^x=1+x+x^2/2!+x^3/3!+x^4/4!+...clear;clc;x=input('Enteravaluefortheexponentx\n');n=1;ex=1.0;term=1.0;whileabs(term)>ex*1.0e-6term=x^n/factorial(n);ex=ex+term;n=n+1;ifn>50break;endendex2=exp(x);disp(x);disp(ex);------------------------------------------------------------

2.7ā€‚ ā€‚MATLABā€‚Functionā€‚FilesMATLABfunctionsareuseful ifyouhaveacomplicatedprogramandwish tobreakitdownintosmallerparts.Also,ifaseriesofstatementsistobeusedmanytimes,itisconvenienttoplacetheminafunction.Functionsareequivalenttosub-routinesinmostprogramminglanguages,butinMATLABtheyareusuallystoredinseparatefilesinsteadofinthemainprogram(althoughsmallfunctionscanbedefinedinthesamefileasyourmainscript.Thisisdescribedinthenextsection).

Page 49: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 33

ā—¾ Thefunctionfilenamemustbesavedasfunction_name.m.

ā—¾ MATLABhasa template forwritinga function (seeFigure 2.9).Thefirstexecutablestatementinthefunctionfilemustbefunction.AscanbeseenfromFigure 2.9,thefunctiontemplateisoftheform:

function[outputarguments]= Untitled(inputarguments)

seeabovefigure

SomeexamplefunctiondefinitionsareshowninTable 2.1. Ifthefunctionhasmorethanoneoutputvalue,thentheoutputvariables

mustbeinbrackets.Ifthereisonlyoneoutputvalue,thennobracketsarenecessary.Iftherearenooutputvalues,useemptybrackets.

ā—¾ AfunctiondiffersfromascriptinthatthereturnargumentsmaybepassedtoanotherfunctionortotheCommandwindow.Variablesdefinedandmanip-ulatedinsidethefunctionarelocaltothefunction.

Table 2.1ā€‚ Exampleā€‚ofā€‚Functionā€‚Usage

Function Definition Line Function File Name

function[P,V]=power(i,v) power.m

functionex=exf(x) exf.m

function[]=output(x,y) output.m

Figureā€‚2.9ā€‚ Functionā€‚template.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 50: Numerical and Analytical Methods with MATLAB for

34ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ā—¾ ManyofMATLABā€™sā€œbuilt-inā€functionsareactuallyimplementedas.mfiles.For example,factorial is implemented in thefile factorial.m.Youcanfindfactorial.mbytypingwhich factorialintheCommandwindow.

Exampleā€‚2.4:ā€‚ MATLABā€‚Functionā€‚Definition

%exf1.m(Example2.4)%Defineafunction,'exf1',thatevaluatese^x.%Thisfunctiontakes'x'asaninputargumentandis%calledeitherfromtheCommandWindoworfromanother%program.Theresultingoutput,'ex',isavailableto%beusedinanotherprogramorintheCommandWindow.%Inthisexample,term(n+1)isobtainedfromterm(n)%bymultiplyingterm(n)byx/n.%Note:e^x=1+x+x^2/2!+x^3/3!+x^4/4!+...functionex=exf1(x)term(1)=1.0;forn=1:99term(n+1)=term(n)*x/n;ifabs(term(n+1))<=1.0e-7break;endendex=sum(term);------------------------------------------------------------

To test out this function, run it from the Command window. Some examples follow:

>>exf1(1.0) ans=

2.7183>>y = exf1(5.0)y=

148.4132

Exampleā€‚2.5:ā€‚ Usingā€‚aā€‚MATLABā€‚Function

%Example_2_5.m%Thisprogramusesthefunctionexf1(definedin%Example2.4)inseveralarithmeticstatements,i.eto%calculatew,yandz.Inthisprogram,theoutputis%senttoafile.clear;clc;fo=fopen('output.txt','w');fprintf(fo,'xywz\n');fprintf(fo,'----------------------------------\n');forx=0.1:0.1:2.0y=exf1(x);w=5*x*exf1(x);z=10*x/y;fprintf(fo,'%4.2f%8.3f%8.3f%8.3f\n',x,y,w,z);endfclose(fo);--------------------------------------------------------

Page 51: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 35

Thefollowingexampledemonstratesthatthenamesoftheargumentsinthecall-ingprogramneednotbethesameasthoseinthefunction.Itisonlytheargumentlistinthecallingprogramthatneedstobeinthesameorderastheargumentlistdefinedinthefunction.Thisfeatureisusefulwhenafunctionistobeusedwithseveraldifferentscripts,eachscripthavingdifferentvariablenamesbutwitheachofthevariablenamescorrespondingtovariablesinthefunction.

Exampleā€‚2.6:ā€‚ Definingā€‚andā€‚Usingā€‚aā€‚MATLABā€‚Function

%Example_2_6.m%Thisprogramusesthefunctionexf2tocalculate%q=e^w/z.wandzareinputvariablestofunction%exf2.Thefunctionexf2calculatesqandreturnsit%tothisprogram.Theinputvariablestofunctionexf2%neednotbethesamenamesasthoseusedinthe%callingprogram.Forone-to-onecorrespondence,the%argumentpositionsinthecallingprogramhavetobe%thesameastheargumentpositionsinthefunction.%Note:functionexf2(definedbelow)mustbecreated%beforethisprogramisexecutedbecausethefunction%exf2calculatesexyandreturnsittothecallingprogram.%qissetequaltoexy.clear;clc;z=5;forw=0.1:0.1:2.0q=exf2(w,z);fprintf('Valuesofw,zandqfrommainprogram:');fprintf('w=%.2fz=%.0fq=%.5f\n',w,z,q);end---------------------------------------------------------------------%exf2.m%ThisscriptisusedwithscriptExample_2_6.mandcreatesa%function'exf2'thatevaluatese^x/y.Inthis%function,xandyareinputvariablesthatneedtobe%definedinanotherprogram.Theoutputvariableinthe%functionexf2issentbacktothecallingprogram.%Thisexampledemonstratesthatthenamesofthe%argumentsinthecallingprogramneednotbethesame%asthoseinthefunction.Itistheorderlistinthe%callingprogramthatneedstobethesameastheorder%listinthefunction.%Inthisexample,term(n+1)isobtainedfromterm(n)by%multiplyingterm(n)byxanddividingbyindexn.The%programdoesitsownsummingofterms.%Note:e^x=1+x+x^2/2!+x^3/3!+x^4/4!+...functionexy=exf2(x,y)%Note:xandyaresetequaltowandzrespectively.s=1.0;term=1.0;forn=1:100term=term*x/n;s=s+term;ifabs(term)<=s*1.0e-5break;end

Page 52: Numerical and Analytical Methods with MATLAB for

36ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

endexy=s/y;%Thesefprintfstatementsdemonstratetheequivalence%betweenfunctioninputvariables(x,y)andcalling%programvariables(w,z)intheprogramExample_2_6.m.%Comparetheprintoutofx,yandexywithw,zandq.fprintf('Valuesofx,yandexyfromexf2():');fprintf('x=%.2fy=%.0fexy=%.5f\n',x,y,exy);---------------------------------------------------------------------

2.8ā€‚ ā€‚Anonymousā€‚FunctionsSometimes, it ismoreconvenient todefinea function insideyour script ratherthaninaseparatefile.Forexample,ifafunctionisbrief(perhapsasingleline)andunlikelytobeusedinotherscripts,thentheanonymousformofafunctioncanbeused.Thiswillsaveyoufromhavingtocreateanother.mfile.Anexampleis

fh=@(x,y)(y*sin(x)+x*cos(y));

MATLABdefinesthe@signasafunction handle.Afunctionhandleisequiva-lenttoaccessingafunctionbycallingitsfunctionname,whichinthiscaseisfh.The (x,y) defines the input arguments to the function, and the (y*sin(x)+x*(cos(y))istheactualfunction.Anonymousfunctionsmaybeusedinascriptorinthecommandwindow.

Forexample,intheCommandwindow,typeinthefollowingtwolines:

>>fh = @(x,y)(y*sin(x)+x*cos(y));>>w = fh(pi,2*pi)w= 3.1416

Additional informationon anonymous functions canbeobtainedby typinghelp function _ handleintheCommandwindow.

2.9ā€‚ ā€‚MATLABā€‚Graphicsā—¾ Plotcommands:

plot(x,y) linear plot of y versus x

semilogx(x,y) semilog plot (log scale for x axis, linear scale for y axis)

semilogy(x,y) semilog plot (linear scale for x axis, log scale for y axis)

loglog(x,y) log-log plot (log scale for both x and y axes)

Page 53: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 37

ā—¾ Multipleplots:

plot(x,y,w,z) gives multiple plots on the same axes: in this case y versus x and z versus w.

Forexample,suppose

=

1 1 1 1

2 2 2 2A

t y z wt y z w

t y z wn n n n

LetT =A(:,1),Y =A(:,2),Z=A(:,3),andW=A(:,4),giving

= = = =

1

2

1

2

1

2

1

2T

tt

t

Y

yy

y

Z

zz

z

W

ww

wn n n n

Then,toplotYversusT,ZversusT,andWversusTallonthesamefig-ure,write

plot(T,Y,T,Z,T,W);

Ofcourse,wecouldhaveavoidedtheadditionalstepbywriting

plot(A(:,1),A(:,2),A(:,1),A(:,3),A(:,1),A(:,4))

ā—¾ Customizingplots:

Youcanaddagridtotheplotwiththecommand,

grid

Tolabelthexandyaxesandtoaddatitletotheplot,addthefollowingcommandstoyourprogram:

xlabel('T'); ylabel('Y,Z,W'); title('Y,Z,WvsT');

Page 54: Numerical and Analytical Methods with MATLAB for

38ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Youcanalsoaddtexttotheplotwiththecommand

text(xposition,yposition,'textstatement');

Greeklettersandmathematicalsymbolscanbeusedinxlabel,ylabel,title,andtextbyspellingouttheGreekletterandprecedingitwithaā€˜\ā€™(backslashcharacter).Thus,todisplayĻ‰,use\omega,andtodisplayĪ³,use\gamma.Forexample:

ylabel('\omega'),title('\omegavs.\gamma'),text(10,5,'\Phi');

For a complete list ofGreek symbols and additional special characters,seeAppendixB.Youmayalsooccasionallyneedtoprintaā€œ'ā€characterinyourlabelortitle.Inthiscase,useadouble'toā€œescapeā€thesingle-quotecharacterinyourstring.Thus,togeneratetheplottitleā€œSignal'A'vs.Signal'B'ā€,youwouldtype

title('Signal''A''vs.Signal''B''')

Inmostcases,youcanletMATLABselectthescalingforthexandyaxesofatwo-dimensionalplot.However,ifyouareunsatisfiedwithMATLABā€™sautomatic selection, thenyoucanuse theaxis command to set theplotlimitsexplicitly:

axis([xminxmaxyminymax])

wherexminandxmaxsetthescalingforthexaxis,andyminandymaxsetthescalingfortheyaxis.

ā—¾ Interactivelyannotatingplots: As analternative to adding thexlabel,ylabel, andtitle com-

mands to yourprogram,you can create theplot, then clickon the InsertmenuintheplotwindowandchooseX Labelfromthedrop-downmenu.This will highlight a box in which you can type in the abscissa variablename.YoucanrepeatthisprocessfortheY Label andtheTitleoftheplot.OtheroptionsavailableintheInsertmenuareTextBox, Text Arrow, Arrow,andothers.Whenyouclickanyoneoftheseoptions,acrosshairwillappear,andyoucanthenmovetheitemtothelocationwhereyouwantittoappear,thenleftclickthemousetofixthelocation.Youcanthentypeinthedesiredtext.ToremovetheoutlinesofaTextBox,placethecursorintheTextBoxandrightclickthemouse.Thiswillbringupadrop-downmenu;selectLine Styleandthenleftclickonnone.

ā—¾ Savingplots: Tosaveaplot,clickonFile intheplotwindowandselecttheSaveoption

fromthedrop-downmenu.Thisproducesawindowwhereyoucanenterafilename.Thedisadvantageofthismethodisthatifyoudecidetorerunthe

Page 55: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 39

script,theitemsthatyoumanuallyinsertedwillnotbesaved.Ifyouwishtocopythefigureintoareport,youcanclickonEditintheplotwindow,thenselectCopy Figurefromthedrop-downmenu.Youcanthenpastethefigureintoyourreport. Ifyouneedamonochromeversionofyourplot (forbestreproductiononaphotocopier), youcanmakeallofyourcurvesblackbychoosingtheFilemenuandthenselectingExport Setupfromthedrop-downmenu.ThiswillopenawindowinwhichyouneedtoclickonRenderingandchangetheColorspacetoblack and white.

Therearemanymoreoptionsavailableintheplotwindow;however,weleaveituptothestudenttoexplorefurther.

Exampleā€‚2.7:ā€‚ Creatingā€‚Plots

%Example_2_7.m%Thisprogramcreatesasimpletableandasimpleplot.%First,thevectorsy1,y2andtarecalculated.%Nextatableofy1=n^2/10andy2=n^3/100iscreated.%Theny1andy2areplotted.clear;clc;forn=1:10t(n)=n;y1(n)=n^2/10;y2(n)=n^3/100;end%Bymakingt,y1andy2asvectors,theirvaluescanbe%printedoutoutsidethe'for'loopthatcreatedthem.%Printcolumnheadingsfprintf('ty1y2\n');fprintf('--------------------------------------\n');forn=1:10fprintf('%8.1f%10.2f%10.2f\n',...t(n),y1(n),y2(n));end%Createtheplot.y1isred,y2isingreen.plot(t,y1,'r',t,y2,'g');xlabel('t'),ylabel('y1,y2'),grid;title('y1andy2vs.t');%Plotidentificationisalsoestablishedbyaddingtext%totheplot.text(6.5,2.5,'y1');%Intheabovestatement,6.5istheabscissaposition%and2.5istheordinatepositionwherethe'y1'label%willbepositioned.text(4.2,2.4,'y2');%OtherMATLABplotoptions:%Availablecolortypes:%blue'b'%green'g'%red'r'%cyan'c'%yellow'y'%Curvesy1andy2canalsobedistinguishedbyusing

Page 56: Numerical and Analytical Methods with MATLAB for

40ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%differenttypesoflinesaslistedbelow.%Availablelinetypes:%solid(default)%dashed'--'%dashed-dot'-.'%dotted':'%Alternatively,youcancreateamarkerplotof%discretepoints(withoutaline)byusingoneofthese%markerstyles:%point'.'%plus'+'%star'*'%circle'o'%x-mark'x'%The'legend'commandmayalsobeusedinplaceofthe%textcommandtoidentifythecurves.Thelegendbox%maybemovedbyclickingontheboxanddraggingitto%thedesiredposition.----------------------------------------------------------------------------

The resulting plot is shown in Figure 2.10.

Exampleā€‚2.8:ā€‚ Theā€‚Subplotā€‚Command

Suppose you want to plot each of the curves in the previous example as a separate plot, but all on the same page. The subplot command provides

1 2 3 4 5 6 7 8 9 100

1

2

3

4

5

6

7

8

9

10

t

y1,y

2y1 and y2 vs. t

y1y2

Figureā€‚2.10ā€‚ Exampleā€‚plotā€‚generatedā€‚withā€‚theā€‚plotā€‚command.

Page 57: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 41

the means to do so. The command subplot(m,n,p) breaks the page into an m by n matrix of small plots, and p selects the matrix position of the plot. The following example demonstrates the use of the subplot command:

%Example_2_8.m%Thisprogramisanexampleoftheuseofthesubplot%commandandtheelseifladder.Valuesofy1,y2,y3%andy4areconstructedasvectors.Separateplotsof%y1vs.t,y2vs.tandy3vs.tareplottedonthe%samepage.clc;clear;forn=1:11t(n)=n-1;y1(n)=t(n)^2/10;y2(n)=sin(pi*t(n)/10);y3(n)=exp(t(n)/2);y4(n)=sqrt(t(n));endforn=1:4subplot(2,2,n)ifn==1plot(t,y1),grid,title('y1vs.t');xlabel('t'),ylabel('y1');elseifn==2plot(t,y2),grid,title('y2vs.t');xlabel('t'),ylabel('y2');elseifn==3plot(t,y3),grid,title('y3vs.t');xlabel('t'),ylabel('y3');elseifn==4plot(t,y4),grid,title('y4vs.t');xlabel('t'),ylabel('y4');endend----------------------------------------------------------------------------

Exampleā€‚2.9:ā€‚ Theā€‚sprintfā€‚Function

Sometimes, we might wish to enter formatted data into the xlabel, yla-bel, or title of a graph. We can do this with the sprintf command, which allows data to be formatted using a similar mechanism as fprintf but sends the result to a function or variable instead of to the screen or a file. This is shown in the following example:

%Example_2_9.m%Thisprogramdemonstratestheuseofsprintfcommand%topassformatteddatatoylabelandtitleinagraph.%Thesubplotcommandisalsodemonstrated.clear;clc;%Definethedatatoplotx=-10:2:10;m=2:5;b=[1101001000];%Createtableandplotfori=1:4

Page 58: Numerical and Analytical Methods with MATLAB for

42ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

fprintf('m=%i\n',m(i));%printtableheadingsfprintf('xyc\n');fprintf('----------------------\n');%(xtopowerm(i))dividedbyb(i)forj=1:length(x)yc(j)=x(j)^m(i)/b(i);fprintf('%5.0f%8.2f\n',x(j),yc(j));endfprintf('\n\n');%plotsubplot(2,2,i);plot(x,yc);xlabel('x');ylabel(sprintf('(xtopower%d)/%.0f',m(i),b(i)));grid,title(sprintf('m=%d,b=%d',m(i),b(i)));end-------------------------------------------------------------------------

See Figure 2.11 for the resulting plot.

ā€“10 ā€“5 0 5 100

20

40

60

80

100

x

(x to

pow

er 2

) / 1

m = 2, b = 1

ā€“10 ā€“5 0 5 10ā€“100

ā€“50

0

50

100

x

(x to

pow

er 3

) / 1

0

m = 3, b = 10

ā€“10 ā€“5 0 5 100

20

40

60

80

100

x

(x to

pow

er 4

) / 1

00

m = 4, b = 100

ā€“10 ā€“5 0 5 10ā€“100

ā€“50

0

50

100

x

(x to

pow

er 5

) / 1

000

m = 5, b = 1000

Figureā€‚2.11ā€‚ Exampleā€‚subplotsā€‚andā€‚exampleā€‚useā€‚ofā€‚theā€‚sprintfā€‚commandā€‚inā€‚theā€‚plotā€‚titlesā€‚andā€‚labels.

Page 59: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 43

Exampleā€‚2.10:ā€‚ Theā€‚Stemā€‚Plot

In discrete-time signal processing, a stem plot is often used to display signal sequences. Given a signal x[n] that is defined for integer values of n, the com-mand stem(n,x) will plot x as vertical ā€œlollipopsā€ stemming from the horizon-tal axis. The following script generates a stem plot for the following data:

x[0] = 2.4, x[1] = 3.8, x[2] = āˆ’1.8, x[3] = 2.1, x[4] = 1.9

x[5] = 0.8, x[6] = 0.0, x[7] = āˆ’0.8, x[8] = 1.5

%Example_2_10.m%Thisscriptusesthe'stem'commandtoplotdiscrete%data.clc;clear;x=[2.43.8-1.82.11.90.80.0-0.81.5];n=[012345678];stem(n,x);xlabel('n'),ylabel('x[n]');axis([-19-35]);------------------------------------------------------------------------

The resulting plot is shown in Figure 2.12.

ā€“1 0 1 2 3 4 5 6 7 8 9ā€“3

ā€“2

ā€“1

0

1

2

3

4

5

n

x[n]

Figureā€‚2.12ā€‚ Aā€‚stemā€‚plot.

Page 60: Numerical and Analytical Methods with MATLAB for

44ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚2.11:ā€‚ Creatingā€‚aā€‚Dataā€‚Fileā€‚toā€‚beā€‚Usedā€‚inā€‚anā€‚Externalā€‚Program

%Example_2_11.m%Thisprogramisusedtocreateadatafilethatcanbe%loadedinanotherprogramforuseinavarietyofways.clear;clc;forn=1:20t(n)=n;y1(n)=n^2/10;y2(n)=n^3/100;y3(n)=n^4/1000;endfo=fopen('ydata.txt','w');fori=1:20fprintf(fo,'%6.1f%10.5f%10.5f%10.5f\n',...t(i),y1(i),y2(i),y3(i));end%Runningtheprogramcreatesthedatafile'ydata.txt':fprintf('Dataissavedtofile''ydata.txt''\n');%Addingtheclearstatementremovesalldatafromthe%workspace:clear;-------------------------------------------------------------------------

Exampleā€‚2.12:ā€‚ Loadingā€‚Dataā€‚Createdā€‚inā€‚anā€‚Externalā€‚Program

%Example_2_12.m%Thisprogramdemonstratestheuseoftheloadcommand.%Adatafilenamedydata.txt(createdinExample_2_11.m)%isloadedintothisprogram.Then,variablest,y1,y2,y3%areextractedfromtheloadeddataandplottedallon%onegraph.clear;clc;fprintf('Readingdatafrom''ydata.txt''\n');loadydata.txtt=ydata(:,1);y1=ydata(:,2);y2=ydata(:,3);y3=ydata(:,4);plot(t,y1,t,y2,'--',t,y3,'-.');xlabel('t'),ylabel('y1,y2,y3'),title('y1,y2andy3vs.t'),grid;legend('y1','y2','y3');-----------------------------------------------------------------

An alternative to the load command is the dlmread command. This command will read an ASCII delimited file. All data in the file must be numeric. In Example 2.12, we could replace the lines starting with loadydata.txt and ending with y3=ydata(:,4) with

Y=dlmread('ydata.txt'); t=Y(:,1); y1=Y(:,2); y2=Y(:,3); y3=Y(:,4);

Page 61: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 45

Exampleā€‚2.13:ā€‚ Semilogā€‚Plots%Example_2_13.m%Thisprogramisademonstrationofasemilogplot%commandclc;clear;x=1:0.5:5;fori=1:length(x)y(i)=3.0*exp(x(i));endsemilogy(x,y),title('Semilogplotofyvs.x');xlabel('x'),ylabel('y'),grid;---------------------------------------------------------

Exampleā€‚2.14:ā€‚ Plottingā€‚Trigonometricā€‚Functions%Example_2_14.m%Thisscriptcalculatesfunctionssin(2x/3)andcos(3x+pi)%for-pi<=x<=pi.Thexdomainissubdividedinto50%subdivisions.Thefunctionsateachdatapointis%calculatedandstoredinthevectors'fsin'and'fcos'.%Thenthetwovectorsareprintedasatabletoafile%named'output.txt'.Plotsofbothfunctionsonthesame%axisarecreated.Finally,themaximumvaluesof%'fsin'and'fcos'aredeterminedandprinted.clear;clc;xmin=-pi;dx=2*pi/50;fori=1:51x(i)=xmin+(i-1)*dx;arg1=2*x(i)/3;arg2=3*x(i)+pi;fsin(i)=sin(arg1);fcos(i)=cos(arg2);endfo=fopen('output.txt','w');%Tableheadingsfprintf(fo,'xfsinfcos\n');fprintf(fo,'--------------------------------------\n');fori=1:51fprintf(fo,'%10.5f%10.5f%10.5f\n',...x(i),fsin(i),fcos(i));endfprintf(fo,'--------------------------------------\n\n');%Printmaximumvalues:fsin_max=max(abs(fsin));fcos_max=max(abs(fcos));fprintf(fo,'fsin_max=%10.5f\n',fsin_max);fprintf(fo,'fcos_max=%10.5f\n',fcos_max);%Plotdata:plot(x,fsin,x,fcos,'--');xlabel('x'),ylabel('fsin,fcos'),grid,title('fsinandfcosvs.x');legend('fsin','fcos');-------------------------------------------------------------------------

Page 62: Numerical and Analytical Methods with MATLAB for

46ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

2.10ā€‚ ā€‚Workingā€‚withā€‚MatricesAdditionalexamplesfollowdemonstratingtheuseof

1.nested for loops forenteringa3Ɨ3matrixfromthekeyboard. 2.theinputcommand. 3. theloadcommand. 4. anexampleofaself-writtenfunction. 5.thefscanfcommand.

Exampleā€‚2.15:ā€‚ Interactiveā€‚Keyboardā€‚Inputā€‚ofā€‚aā€‚Matrix

%Example_2_15.m%Inputa3by3matrixfromthekeyboard.%Nestedloopsareusedtocreatea3by3matrix.%Anelementinthematrixisestablishedbytheindices%ofboththeinnerandouterloops.clear;clc;forn=1:3form=1:3fprintf('n=%im=%i',n,m);a(n,m)=input('Entera(n,m):');fprintf('\n');endend%Printtheresultingmatrix:a-----------------------------------------------------------

Exampleā€‚2.16:ā€‚ Loadingā€‚aā€‚Matrixā€‚fromā€‚aā€‚File

%Example_2_16.m%MatricesAandBareloadedfromafilenamed%data216.txt,thenprintedtothescreen.MatricesAand%BarecombinedintomatrixC,whichissenttofunction%signal_out.ThisfunctionsubdividesmatrixCbackinto%matricesAandBandprintsthemouttothescreen.%Note:Beforerunningthisprogram,thedatafile%data216.txtandfunctionfilesignal_out.mneedtobe%created(seebelow).clear;clc;n=5;loaddata216.txtA=data216(:,1:n);B=data216(:,n+1);fprintf('MatrixAelements:\n');Afprintf('\n');fprintf('MatrixBelements:\n');BC=[AB];signal_out(C);-----------------------------------------------------------

Page 63: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 47

%Datafile'data216.txt'(donotincludethisheaderline)8.772.405.661.551.0-32.044.931.214.481.101.0-20.073.531.462.921.211.0-8.535.054.042.512.011.0-6.303.541.043.471.021.0-12.04-----------------------------------------------------------%signal_out.m%ThisfunctionacceptsmatrixA&matrixBandprints%themtothescreenandisusedwithExample2.16.function[]=signal_out(C)n=5;A=C(:,1:n);fprintf('Thisoutputisfromsignal_out:\n\n');fprintf('MatrixAelements:\n')fori=1:nforj=1:nfprintf('%8.3f',A(i,j));endfprintf('\n');endfprintf('\n\nMatrixBelements:\n');B=C(:,n+1);fori=1:nfprintf('%8.3f\n',B(i));end----------------------------------------------------------

Exampleā€‚2.17:ā€‚ Loadingā€‚aā€‚Matrixā€‚withā€‚fscanf

%Example_2_17.m%ThisprogramusesthefscanfcommandtoenteranMbyN%matrixintoMATLAB.TheMbyNmatrixisenteredin%columnorder.Thus,rowsbecomecolumnsandcolumns%becomerows.ThescriptcreatesmatricesAandBand%thenprintsthemouttothescreen.%Note:Beforerunningthisprogram,thedatafile%data217.txtneedstobecreated(seedatabelow).clear;clc;n=5;A=zeros(n);B=zeros(5,1);fin=fopen('data217.txt','r');[A]=fscanf(fin,'%f',[n,n]);fprintf('MatrixAelements:\n');A[B]=fscanf(fin,'%f',[n]);fclose(fin);fprintf('\n');fprintf('MatrixBelements:\n');Bfprintf('\n');fprintf('MatrixCelements:\n');C=[A'B]%Comparingthedata217datafilewithmatricesAandB,

Page 64: Numerical and Analytical Methods with MATLAB for

48ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%weseethatthedata217datafilehasbeentransposed%(rowsbecomecolumnsandcolumnsbecomerows).----------------------------------------------------------%Datafile'data217'(donotincludethisheaderline)8.772.405.661.551.04.931.214.481.101.03.531.462.921.211.05.054.042.512.011.03.541.043.471.021.0-32.04-20.07-8.53-6.30-12.04----------------------------------------------------------

2.11ā€‚ ā€‚Workingā€‚withā€‚Functionsā€‚ofā€‚aā€‚VectorMATLABallowsfunctionstohavevectorsasarguments.Thereturnvaluecanalsobeavector.Forexample(writethissimplescriptinthescriptwindow,saveitasvector_function.m,andrunthescript):

%vector_function.m clear;clc; %Definevectorx; x=0:30:360; %Lety1bethesineofavectorxwherexisindegrees. %Runningsindonavectorwillreturnavector: y1=sind(x); %Lety2(n)bethesineofthenthelementofx.Wewill %useaforlooptocalculateeachvaluey2(n)andthen %comparey1andy2. forn=1:length(x) y2(n)=sind(x(n)); end %Tableheadings fprintf('x y1 y2 \n'); fprintf('------------------------------------------------\n'); forn=1:length(x) fprintf('%5.1f %8.5f %8.5f\n',x(n),y1(n),y2(n)) end

Inthegeneratedoutput,doesy1=y2?Weseethatinsomescripts,wecouldreplacetheuseofaforloopbytaking

afunctionofavector,whichproducesavector,thusreducingthenumberoflinesinthescript.Thisconceptisdemonstratedaboveinthescriptvector_function.m.However,ifthescriptrequiresamathematicaloperationoftwofunctions(suchasaproductoftwovectorfunctions),thentheoperationwillrequireanelement-by-elementoperation.Element-by-elementoperationsarediscussedinChapter3.

Page 65: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 49

2.12ā€‚ ā€‚Additionalā€‚Examplesā€‚Usingā€‚Charactersā€‚andā€‚StringsAdditionalexamplesfollowthatdemonstrate

ā—¾ printingastringofcharacters

ā—¾ theuseoftheswitchstatement

ā—¾ theuseoftheif-elseifladder

ā—¾ theuseofafor looptoselecttheproperintervalinamatrixforestablishingagradeorforinterpolation.

Exampleā€‚2.18:ā€‚ Printingā€‚aā€‚Characterā€‚Stringā€‚Matrixā€‚fromā€‚aā€‚Loop

%Example_2_18.m%Sometimesyoumightwishtoprintoutastringof%charactersinaloop.Thiscanbedonebydeclaringa%2-Dcharacterstringmatrixasshowninthisexample.%Notethatallrowcharacterstringsmusthavethesame%numberofcolumnsandthatcharacterstringsmustbe%enclosedbysinglequotationmarks.clear;clc;parts=['Internalmodem''Graphicsadapter''CDdrive''DVDdrive''Floppydrive''Harddiskdrive'];fori=1:5fprintf('%16s\n',parts(i,1:16));end------------------------------------------------------------

Exampleā€‚2.19:ā€‚ ā€‚Printingā€‚Stringsā€‚toā€‚theā€‚Screenā€‚orā€‚toā€‚aā€‚Fileā€‚Basedā€‚onā€‚Userā€‚Input

%Example_2_19.m%ThisexampleisamodificationofExample2.18.The%programaskstheuseriftheywanttohavetheoutput%gotothescreenortoafile.Thisexampleillustrates%theuseoftheswitchstatement.clear;clc;char=['Internalmodem''Externalmodem''Graphicscircuitboard''CDdrive''Harddiskdrive'];fprintf('Choosewhethertosendtheoutputtothe\n');fprintf('screenortoafilenamed''output.txt''.\n');fprintf('\n');fprintf('Enter''s''forscreenorā€˜'f''forfile\n');var=input('(withoutquotes):','s');switch(var)

Page 66: Numerical and Analytical Methods with MATLAB for

50ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

case's'fori=1:5fprintf('%22s\n',char(i,1:22));endcase'f'fo=fopen('output.txt','w');fori=1:5fprintf(fo,'%22s\n',char(i,1:22));endfclose(fo);otherwisefprintf('Youdidnotenteran''s''oran');fprintf('''f'',tryagain.\n');end------------------------------------------------------------

Exampleā€‚2.20:ā€‚ Theā€‚if-elseifā€‚Ladder

%Example_2_20.m%Thisexampleusestheif-elseifladder.%Theprogramdeterminesalettergradedependingonthe%scoretheuserentersfromthekeyboard.clear;clc;gradearray=['A';'B';'C';'D';'F'];score=input('Enteryourtestscore:');fprintf('Scoreis:%i\n',score);ifscore>100fprintf('Error:scoreisoutofrange.\n');fprintf('Rerunprogram.\n');break;elseif(score>=90&&score<=100)grade=gradearray(1);elseif(score>=80&&score<90)grade=gradearray(2);elseif(score>=70&&score<80)grade=gradearray(3);elseif(score>=60&&score<70)grade=gradearray(4);elseif(score<60)grade=gradearray(5);endfprintf('Gradeis:%c\n',grade);------------------------------------------------------------

Exampleā€‚2.21:ā€‚ Interactiveā€‚Userā€‚Inputā€‚Establishingā€‚aā€‚Grade

%Example_2_21.m%Thisprogramdeterminesalettergradedependingonthe%scoretheuserentersfromthekeyboard.Thisversion%usesalooptodeterminethecorrectintervalof%interest.Foralargenumberofintervals,thismethod%ismoreefficient(fewerstatements)thanthemethodin%Example2.20clear;clc;gradearray=['A';'B';'C';'D';'F'];

Page 67: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 51

sarray=[100908070600];score=input('Enteryourtestscore:');fprintf('Scoreis:%i\n',score);%Thefollowing2statementsareneededforthecase%whenscore=100.ifscore==100grade=gradearray(1);elsefori=1:5if(score>=sarray(i+1)&&score<sarray(i))grade=gradearray(i);endendendfprintf('Gradeis:%c\n',grade);------------------------------------------------------------

Exampleā€‚2.22:ā€‚ Printingā€‚Stringā€‚Arrays

%Example_2_22.m%Thisprogramdeterminesthelettergradesofseveral%students.Student'snamesandtheirtestscoresare%enteredintheprogram.Thisexampleusesnested'for'%loopsandan'if'statementtodeterminethecorrect%lettergradeforeachstudent.clear;clc;gradearray=['A';'B';'C';'D';'F'];sarray=[100908070600];Lname=['Smith''Lambert''Kurtz''Jones''Hutchinson''Diaz'];Fname=['Joe''Jane''Howard''Martin''Peter''Carlos'];score=[84;72;93;64;81;75];%Thescore=100istreatedseparately.forj=1:6ifscore(j)==100grade(j)=gradearray(1);elsefori=1:5ifscore(j)>=sarray(i+1)&&score(j)<sarray(i)grade(j)=gradearray(i);endendendendfprintf('LastnameFirstnameGrade\n');fprintf('----------------------------------\n');forj=1:6

Page 68: Numerical and Analytical Methods with MATLAB for

52ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

fprintf('%12s%10s%c\n',...Lname(j,1:12),Fname(j,1:10),grade(j));end------------------------------------------------------------

Exampleā€‚2.23:ā€‚ Aā€‚Self-Writtenā€‚Functionā€‚andā€‚Stringā€‚Arrays

An important building block in program development is the self-written function. In the following, we construct the function func _ grade to determine the grade in the previous example. The input to func _ grade is the score, and the output is the corresponding grade. Remember that a user-defined function is saved in a separate .m file.%Example_2_23.m%Thisprogramusesfunc_grade.m(definedbelow)to%determinethegradeofastudent.Theinputtothe%functionisscoreandthefunctionreturnsthegrade%tothecallingprogram.clear;clc;Lname=['Smith''Lambert''Kurtz''Jones''Hutchinson''Diaz'];Fname=['Joe''Jane''Howard''Martin''Peter''Carlos'];%Thescoresofthestudentsnamedabovearegiveninthe%vectorscoreintheorderlistedinLname.score=[84;72;93;64;81;75];fprintf('LastnameFirstnameGrade\n');fprintf('--------------------------------\n');forj=1:6grade(j)=func_grade(score(j));fprintf('%12s%10s%c\n',...Lname(j,1:12),Fname(j,1:10),grade(j));end------------------------------------------------------------%func_grade.m%ThisfunctionworkswithExample_2_23.mfunctiongrade=func_grade(score)gradearray=['A';'B';'C';'D';'F'];sarray=[100908070600];ifscore==100grade=gradearray(1);elsefori=1:5if(score>=sarray(i+1)&&score<sarray(i))grade=gradearray(i);endendend------------------------------------------------------------

Page 69: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 53

2.13ā€‚ ā€‚Interpolationā€‚andā€‚MATLABā€™sā€‚interp1ā€‚FunctionFormanyphysicalphenomena,wefrequentlyfindthatapropertyofagivenmate-rialwillbecomputedasafunctionofsomeothervariable.Forexample,themobil-ityof electrons in silicon isdependenton temperatureand isoftenpresentedasatableoflaboratorymeasurementsforafewdistincttemperatures.Ifwewishtodeterminetheelectronmobilityatatemperaturethatisnotinthetable,weneedtointerpolate.Thegenerallinearinterpolationformulais

= +

āˆ’ Ɨ āˆ’āˆ’

( ) ( )1

1 2 1

2 1

T TT T

whereT2andT1aretheclosestsurroundingmeasuredtemperaturestoT,andĪ¼2andĪ¼1aretheelectronmobilitiesattemperaturesT2andT1,respectively.Thenextexample illustrates thecomputationofthemobility foranarbitrarytemperaturebasedonatableofknownvaluesatknowntemperatures.

Exampleā€‚2.24:ā€‚ Interpolationā€‚Usingā€‚anā€‚Anonymousā€‚Function

%Example_2_24.m%Thisprogramusesananonymousfunctiontolinearly%interpolatetheelectronmobilityofsilicon.Measured%valuesofthemobility(cm^2/V-s)vstemperature(K)%aregiven[2].clear;clc;%Anonymousfunction(avoidscreatinganextra.mfile):Muf=@(T,T1,T2,Mu1,Mu2)(Mu1+(T-T1)*(Mu2-Mu1)/(T2-T1));%TablevaluesTt=[100150200250300350400450];Mut=[196507427372321801407972.0705.5531.8];fprintf('Thisprograminterpolatesfortheelectron\n');fprintf('mobility(Mu)ataspecifiedtemperatureT.\n');fprintf('Thevalidtemperaturerangeis100-450K.\n\n');T=input('EnterTatwhichMuistobedetermined:');%Determiningtheclosestsurroundingtemperaturesto%temperatureT.forn=1:length(Tt)-1ifT>=Tt(n)&&T<=Tt(n+1)T1=Tt(n);T2=Tt(n+1);Mu1=Mut(n);Mu2=Mut(n+1);endendMu=Muf(T,T1,T2,Mu1,Mu2);fprintf('T=%.1f(K)Mu=%.3f(cm^2/V-s)\n',T,Mu);------------------------------------------------------------

MATLABhasafunctionnamedinterp1thatperformsinterpolation.Thenextexampledemonstratestheuseofthisfunctionforinterpolatingforelectronmobility.Inaddition,MATLABā€™sinterp1functioncandomultipleinterpola-tionsbyjustcallingthefunctiononce.

Page 70: Numerical and Analytical Methods with MATLAB for

54ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thesyntaxforinterp1is:

Yi=interp1(X,Y,Xi)

whereXandYareasetofknownx,ydatapoints,andXiisthesetofxvaluesatwhichthesetofyvaluesYiaretobedeterminedbylinearinterpolation.ArraysX andYmustbeofthesamelength.Thefunctioninterp1canalsobeusedforinterpolationmethodsotherthanlinearinterpolation,andthisiscoveredinChapter9oncurvefitting.

Exampleā€‚2.25:ā€‚ ā€‚Interpolationā€‚Usingā€‚interp1ā€‚andā€‚Savingā€‚toā€‚aā€‚.matā€‚File

%Example_2_25.m%ThisprogramusesMATLAB'sfunctioninterp1to%interpolatefortheelectronmobilityofsilicon.%Measuredvaluesofthemobility(cm^2/V-s)vs%temperature(K)aregiven[2].Tablevaluesfor%temperaturearespecifiedinmatrixT_data.Table%valuesformobilityarespecifiedinMu_data.The%temperatureatwhichtheelectronmobilityistobe%determinedisenteredfromthekeyboard.clear;clc;T_data=[100150200250300350400450];Mu_data=[196507427372321801407972.0705.5531.8];fprintf('Thisprograminterpolatesfortheelectron\n');fprintf('mobility(Mu)ataspecifiedtemperatureT.\n');fprintf('Thevalidtemperaturerangeis100-450K.\n\n');T=input('EnterTatwhichMuistobedetermined:');Mu=interp1(T_data,Mu_data,T);fprintf('T=%.1f(K)Mu=%.3f(cm^2/V-s)\n\n',T,Mu);%ThedataT_dataandMu_datacanbesavedinadatafile%andloadedlaterinanotherprogram.Bytheuseofthe%'clear'commandthedatafileisremovedfromthe%workspace.Anotherscriptcanbringsthedatabackinto%theworkspacebytheloadcommand.Thescriptcanthen%usethedataforsomeotherpurpose.WewantT_dataand%Mu_datatobecolumnvectors,sosavethetranspose.T_Mu_data=[T_data'Mu_data'];saveT_Mu_data;%T_Mu_dataissavedina.matfileandwillbeused%inExample2.25.fprintf('Mobilityvs.temperaturedatasavedtofile');fprintf('T_Mu_data.mat\n');clear;%T_Mu_datahasbeenremovedfromtheworkspace%T_Mu_datawillbeusedinExample_2_26.------------------------------------------------------------

If we wish to interpolate for electron mobility at several different tem-peratures, we can modify Example 2.25 by replacing all lines after (and including) the lines

Page 71: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 55

fprintf('Thisprograminterpolatesfortheelectron\n');fprintf('mobility(mu)ataspecifiedtempratureT.\n');

with the following lines:

T2=[432182343210385];fprintf('Thisprograminterpolatesfortheelectron\n')fprintf('mobility(Mu)ataspecifiedtempratureT.\n');fprintf('specifiedtemperatures,T2.\n');fprintf('Theallowabletemperaturerangeis100-450K.\n\n');Mu=interp1(T_data,Mu_data,T2);fprintf('T2(K)Mu(cm^2/V-s)\n');fprintf('---------------------------\n');fori=1:5 fprintf('%6.1f %9.3f\n',T2(i),Mu(i));end------------------------------------------------------------

Exampleā€‚2.26:ā€‚ Interpolatingā€‚Dataā€‚Storedā€‚inā€‚aā€‚.matā€‚File

%Example_2_26.m%Thisscriptisasampleofaplotprogramloadingdata%obtainedinanotherprogram.MakesureyourunExample%2.25beforerunningthisexample.clear;clc;fprintf('Loadingdatafromfile"T_Mu_data.mat"\n');loadT_Mu_dataT=T_Mu_data(:,1);Mu=T_Mu_data(:,2);plot(T,Mu);xlabel('T'),ylabel('Mu'),title('Muvs.T'),grid;------------------------------------------------------------

2.14ā€‚ ā€‚MATLABā€™sā€‚textscanā€‚FunctionThere may be occasions when you wish to read a data file into a program thatcontainsbothnumericaldataandastringofcharacters.MATLABā€™stextscanfunctionisbestsuitedforthisoperation.

Syntax: C=textscan(fid,format)

ThefunctionwillreaddatafromanopentextfileidentifiedbyfidintoacellarrayC.Theformatisoftheform%f,%d,%c,%s,andsoon.Thenumberoffor-

matspecifiersdeterminesthenumberofcellsinthecellarrayC.Eachcellwillcon-tainthenumberoflinescontainedinthedatafileandbeofthetypespecifiedbytheformatstatement.Stringspecifiersalsoinclude%q,whichisastringenclosedbydoublequotationmarks.Forasinglecharacter,use%c.

Note:Toreferencethecontentsofacell,enclosethecellnumberwith.Seethefollowingexamples.

IfyouwishtoreadinNlinesfromtheopendatafile,use

C=textscan(fid,format,N)

Page 72: Numerical and Analytical Methods with MATLAB for

56ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚2.27:ā€‚ ā€‚Loadingā€‚Mixedā€‚Textā€‚andā€‚Numericalā€‚Dataā€‚fromā€‚aā€‚File

%Example_2_27.m%Loadtheproductdatafrominv4.txtintothearrays%'sku','desc',and'cost',andprint.%sku,descandcoststandsforitem#,%itemdescriptionanditemcostrespectively.clear;clc;%Note:inventory227.txtisdefinedbelow.fid=fopen('inventory227.txt');C=textscan(fid,'%d%14c%f',5);%ContentsofcellblockCcontains1rowand3columnssku=C1;desc=C2;cost=C3;fclose(fid);count=length(sku)fori=1:countfprintf('%5i%14s%6.2f\n\n',...sku(i),desc(i,1:14),cost(i));end------------------------------------------------------------%inventory227.txtfile(donotincludethisheaderline)1'hammer'2.582'plier'1.203'screwdriver'1.564'solderingiron'3.705'wrench'2.60------------------------------------------------------------

Exampleā€‚2.28:ā€‚ ā€‚Anotherā€‚Exampleā€‚ofā€‚Loadingā€‚Mixedā€‚Textā€‚andā€‚Numericalā€‚Dataā€‚fromā€‚aā€‚File

%Example_2_28.m%Readproductinventoryintoamatrixusingtextscan.%Thefile'inventory228.txt'islistedbelow.clc;clear;fid=fopen('inventory228.txt');C=textscan(fid,'%d%q%f');%NeedtodesignatecontentsincellC2ascharacters.sku=C1;desc=char(C2);cost=C3;count=length(sku);fprintf('sku#descriptioncost\n');fprintf('-----------------------------------\n');fori=1:countfprintf('%4i%14s%6.2f\n\n',...sku(i),desc(i,1:14),cost(i));endfclose(fid);------------------------------------------------------------%inventory228.txtfile(Donotincludthisheaderline)1"hammer "2.582"plier "1.20

Page 73: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 57

3"screwdriver "1.564"solderingiron"3.705"wrench "2.60------------------------------------------------------------

2.15ā€‚ ā€‚Exportingā€‚MATLABā€‚Dataā€‚toā€‚ExcelMATLAB can write its data directly to spreadsheet software such as MicrosoftExcel.Todothis,followthesesteps:

1.InyourMATLABprogram,createamatrixoftheoutputdata,sayM. 2.WritethedatatoanExcelfilewiththefollowingstatement: xlswrite('filename.xls',M);

ThiswillcreateanExcelfilenamedfilename.xlsofyourdata,M,whichyoucantheneditwithinExcel(seeFigure 2.13).

3.You can now use all of the formatting and data manipulation commandsavailable inExcel.For example, to add tableheadings,open theExcelfile,placethecursorinthetopleftcell(cellA1),andtypeintableheadingsineach

Figureā€‚2.13ā€‚ Exampleā€‚ofā€‚sendingā€‚outputā€‚toā€‚Excel.

Page 74: Numerical and Analytical Methods with MATLAB for

58ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ofthecellcolumns.Toaddupthesecondcolumn,placethecursorincellB13andtype=SUM(B3:B12).Youcanalsoapplybold,italics,andcellborders.

2.16ā€‚ ā€‚Debuggingā€‚aā€‚ProgramItiscommonwhenwritingaprogramtomaketypographicalerrors,suchasomittingaparenthesis,forgettingacommainatwo-dimensionalarray,andsoon.Thistypeofbugiscalledasyntax error.Whenthisoccurs,MATLABwillprovideanerrormessagepointingoutthelineinwhichtheerrorhasoccurred.However,therearecaseswhentherearenosyntaxerrors,buttheprogramstillfailstorunorgivesanobviousincorrectanswer.Whenthisoccurs,youcanutilizethedebugfeatureinMATLAB.Thedebugfeatureallowsyoutosetbreakpointsinyourprogram.Theprogramwillrunuptothelinecontainingthebreakpoint.Tosetabreakpoint,leftclickthemouseinthenarrowcolumnnexttothelinenumberthatyouwishtobeabreakpoint.AsmallredcirclewillappearnexttothebreakpointlineasshowninFigure 2.14.Thescriptwillnowrunupto,butnotincluding,thelinecontainingthebreakpoint,asshowninFigure 2.15(atthecommandtoprintmatrixA).TheK>>promptindicatesthatyouareinthedebugmode.YoucanthenclickonthedebuglistingintheMATLABtoolbarandselectfromseveraloptionsinthedrop-downmenu(seeFigure 2.16).Iftheprogramcontainsself-writtenfunctions,youcancontinueexecutiononelineatatimeinthefunction.Todothis,youfirstneedtoclearallthebreakpointsinthemainprogram,thenselecttheStep Inoptioninthedebugdrop-downmenu(seeFigure 2.16).TheStep Outoptionreturnsthecontrol

Debugging breakpoint

Figureā€‚2.14ā€‚ Settingā€‚aā€‚breakā€‚point.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 75: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 59

Figureā€‚2.15ā€‚ Programā€‚executionā€‚isā€‚haltedā€‚whenā€‚theā€‚breakā€‚pointā€‚isā€‚reachedā€‚inā€‚theā€‚program.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Figureā€‚2.16ā€‚ Theā€‚Debugā€‚drop-downā€‚menu.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 76: Numerical and Analytical Methods with MATLAB for

60ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

tothemainprogram.SelectingClear Breakpoints in All Fileswillremoveallbreakpointsfromtheprogram.

2.17ā€‚ ā€‚Theā€‚Parallelā€‚RLCā€‚CircuitTheresistance,inductor,capacitor(RLC)circuitisafundamentalprobleminelec-trical engineering that we revisit several times in this text (see Figure 2.17 andAppendixA).Thissectionderivesthegoverningequationsdescribingthevoltagesandcurrentsforthecircuitcomponents.ThecircuitisdrivenbyacurrentsourceIo(t)viaaswitchthatisopenedattimet =0.Wedonot(forthemoment)concernourselveswith thedefinitionof Io(t) other than that it is used todetermine theinitialconditionsofthecircuitelements.Westarttheanalysiswiththeconstituentvoltage-currentrelationsforresistors,inductors,andcapacitors:

Resistor(Ohmā€™slaw):vR=RiR (2.1)

=Inductor: v L

d idtL

L (2.2)

=Capacitor: i C

dvdtCC (2.3)

whereR,L,andCarethecomponentvaluesfortheresistor(inohms), inductor(inhenries),andcapacitor(infarads),respectively,andthevoltagesvandcurrentsiareasdefinedintheFigure 2.17.Inaddition,weassumethatthestatefulcircuitelementsLandChaveknowninitialconditionsiL(0)andvC(0)atthemomentthattheswitchisopened.

Kirchhoffā€™s current law (KCL) states that the sumof currents at any circuitnodeiszero.ApplyingKCLatthetoprightnodeinthecircuitgives

+ + = 0i i iR L C (2.4)

CIo(t)

āˆ’

+vR

āˆ’

+vL

āˆ’

+vC

iL iCiR

LR

t = 0

Figureā€‚2.17ā€‚ Parallelā€‚RLCā€‚circuit.

Page 77: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 61

Also,theparalleltopologyofthecircuitgives

= = ā‰”v v v vR L C (2.5)

SubstitutingEquation(2.5)intoEquation(2.2)gives

=

1didt L

vL (2.6)

andsubstitutingEquations(2.1)and(2.3)intoEquation(2.4)gives

= āˆ’ āˆ’

1 1dvdt RC

vCiL (2.7)

Equations(2.6)and(2.7)areasystemoftwofirst-orderdifferentialequationswith two unknowns. We can combine these into one second-order differentialequationbydifferentiatingbothsidesofEquation(2.7):

= āˆ’ āˆ’

1 12

2d vdt RC

dvdt C

didtL (2.8)

SubstitutingEquation(2.6)intoEquation(2.8)givesthesecond-orderdiffer-entialequation

+ + =

1 1 02

2d vdt RC

dvdt LC

v (2.9)

Tosolvethissecondorderhomogeneousdifferentialequation,weseekafunc-tionv(t)suchthatthederivatives ( )v t and ( )v t reproducetheformofv(t).Afunction that satisfies this condition is Ī±Ae t ,whereA andĪ± are arbitrary con-stants.Ifweassumethat = Ī±v Ae t ,then

= Ī± = Ī±Ī± Ī±( ) and ( ) 2v t Ae v t Aet t

SubstitutingthesetermsintothedifferentialEquation(2.9)gives

Ī± + Ī± + =Ī±1 1 02

RC LCA e t (2.10)

Since ā‰ Ī± 0e t ,solvingthisequationinvolvessolvingthequadraticpart

Ī± + Ī±+ =

1 1 02

RC LC (2.11)

Page 78: Numerical and Analytical Methods with MATLAB for

62ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thesolutionsare

Ī± = āˆ’ Ā± āˆ’

12

12

12

RC RC LC (2.12)

Thus,therearetwosolutionsthatsatisfythedifferentialequationforthetwovaluesofĪ±inEquation(2.12).ThegeneralsolutiontoEquation(2.9)isthesumofallknownsolutions:

exp 12

12

1 exp 12

12

1

or equivalently

exp 12

exp 12

1 exp 12

1

2 2

2 2

v ARC

tRC LC

t BRC

tRC LC

t

vRC

t ARC LC

t BRC LC

t

= āˆ’ + āˆ’ + āˆ’ āˆ’ āˆ’

= āˆ’ āˆ’ + āˆ’ āˆ’

(2.13)whereexp(x)=ex,andAandBareconstantsthataredependentontheinitialcon-ditionsofthecircuit.

Notethatthissolutionhastworegionsofinterest:

a) Overdamped: If >1

212

RC LC,thenthesolutionsaredecayingexponen-

tialsovertime.

b) Underdamped: If <1

212

RC LC,thenthesolutionsaredecayingsinusoids

overtime.

Fortheunderdampedcase,wecanshowthesinusoidalbehaviorbyapplyingtheidentities = +cos sine x j xjx and = āˆ’āˆ’ cos sine x j xjx toEquation(2.13),giving

= āˆ’ āˆ’ + āˆ’exp 12

cos 1 12

sin 1 12

2 2

vRC

t ALC RC

t BLC RC

t

(2.14)wherethecoefficientsAā€²andBā€²aretobedeterminedbyinitialconditions.

If =1

21 ,

2

RC LCthenthesquareroottermiszero,andthesystemissaid

tobecritically damped.Forthiscase[3],thesolutionis

= + āˆ’( )exp 1

2v A B t

RCt (2.15)

Page 79: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 63

The equations developed in this section are used in projects starting withProject2.7.

ExercisesExercise2.1 ShowthattheTaylorseriesexpansionofcos xaboutx=0is

= āˆ’ + āˆ’ +cos( ) 1

2! 4! 6!. . .

2 4 6

xx x x

Exercise2.2 ShowthattheTaylorseriesexpansionofsin xaboutx=0is

= āˆ’ + āˆ’ +sin( )

3! 5! 7 !. . .

3 5 7

x xx x x

Exercise2.3 UsingtheTaylorseriesexpansionofexaboutx=0(seeExample2.1),showthat = +cos sine x j xjx andthat = āˆ’āˆ’ cos sine x j xjx ,where = āˆ’1.j

ProjectsProject.2.1

UsingtheTaylorseriesexpansionofcos xaboutx =0(seeExercise2.1)developacomputerprogramin MATLABthatwillevaluatecosxfrom.āˆ’Ļ€ ā‰¤.x ā‰¤.Ļ€.instepsof0.1Ļ€.Computetheseriesbydeterminingeachtermaccordingtotheequation

term(k+1)=term(k)Ɨamultiplicationfactor

wherethemultiplicationfactorneedstobedetermined.Useasmanyas50terms;however,stopaddingtermswhenthelasttermonlyaffectsthesixthdecimalplaceintheanswer.Also,computethevalueofcos xusingMATLABā€™sbuilt-incos()functionoverthesameintervalandstepsize.PrintatableofyourresultstoafileusingthetableformatinTableP2.1.Usesixdecimalplacesforcos x.

Also,createaplotofcos xforā€“Ļ€ ā‰¤ x ā‰¤ Ļ€.

Tableā€‚P2.1ā€‚ Tableā€‚Formatā€‚forā€‚Projectā€‚2.1

xcos x by cos()

cos x by series

Terms in the series

ā€“1.0ā€‚Ļ€

ā€“0.9ā€‚Ļ€

ā€“0.8ā€‚Ļ€

ā‹®

0.9 Ļ€

1.0ā€‚Ļ€

Page 80: Numerical and Analytical Methods with MATLAB for

64ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.2.2

UsingtheTaylorseriesexpansionofsin xaboutx =0(seeExercise2.2),developacomputerprogramin MATLABthatwillevaluatesinxfrom.āˆ’Ļ€ ā‰¤.x ā‰¤.Ļ€.instepsof0.1Ļ€.ComputetheseriesbyusingMATLABā€™sfactorialfunctionanduseasmanyas50terms.However,stopaddingtermswhenthelasttermonlyaffectsthesixthdecimalplaceintheanswer.

Also, compute the valueof sin x usingMATLABā€™sbuilt-insin() functionoverthesameintervalandstepsize.CreateatablesimilartothetableshowninProject2.1,exceptreplacecos xwithsin x.Createaplotofsin xforā€“Ļ€ ā‰¤ x ā‰¤ Ļ€.

Project.2.3

DevelopacomputerprograminMATLABthatwillevaluatethefollowingfunc-tionforā€“0.9ā‰¤xā‰¤0.9instepsof0.1by:

1. anarithmeticstatement.2. aseriesallowingforasmanyas50terms.However,stopaddingtermswhenthe

lasttermonlyaffectsthesixthdecimalplaceintheanswer.

Thefunctionanditsseriesexpansion,validforx2<1,is

= + = āˆ’ +

ā‹…ā‹…

āˆ’ā‹… ā‹…ā‹… ā‹…

+ā‹… ā‹… ā‹…ā‹… ā‹… ā‹…

āˆ’ +āˆ’( ) (1 ) 1 12

1 32 4

1 3 52 4 6

1 3 5 72 4 6 8

2 1/2 2 4 6 8f x x x x x x

Printoutatable(toafile)intheformatshowninTableP2.3;usesixdecimalplacesforf(x).

Project.2.4

DevelopacomputerprograminMATLABthatwillevaluatethefunction

= +( ) (1 )1/3f x x

forā€“0.9ā‰¤xā‰¤0.9instepsof0.1by

Tableā€‚P2.3ā€‚ Tableā€‚Formatā€‚forā€‚Projectā€‚2.3

x

f(x)(arithmetic statement)

f(x)(by series)

No. of Terms Used in the Series

ā€“0.9

ā€“0.8

ā€“0.7

ā‹®

0.7

0.8

0.9

Page 81: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 65

1. anarithmeticstatement.2. seriesallowingforasmanyas50terms.However,stopaddingtermswhenthe

lasttermonlyaffectsthesixthdecimalplaceintheanswer.

ByusingaTaylorseriesexpansion,itcanbeseenthattherelationshipbetweensuccessivetermsis

+ = Ɨ āˆ’ āˆ’ Ɨterm( 1) term( ) 1

3( 1)k k k

xk

fork=1,2,3,....Printoutatable(toafile)intheformatshowninProject2.3;usesixsignificant

figuresforf(x).

Project.2.5

Thebinomialexpansionfor +(1 )x n ,wherenisaninteger,isasfollows:

(1 ) 1 ( 1)2!

( 1)( 2)3!

( 1)( 2)...( 2)( 1)!

2 3

1

x n x n n x n n n x

n n n n r xr

x

n

rn

+ = + +āˆ’

+āˆ’ āˆ’

+ +

āˆ’ āˆ’ āˆ’ +āˆ’

+ +āˆ’

ConstructaMATLABprogramthatwillevaluate +(1 )x n byboththepreced-ingseriesandanarithmeticstatementforn=10and1.0ā‰¤x ā‰¤10.0instepsof0.5.PrintouttheresultsinatableasshowninTableP2.5.

Tableā€‚P2.5ā€‚ Tableā€‚Formatā€‚forā€‚Projectā€‚2.5

x

(1 + x)n

(arithmetic statement)

(1 + x)n

(by series)

1.0

1.5

2.0

2.5

ā‹®

9.5

10.0

Page 82: Numerical and Analytical Methods with MATLAB for

66ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.2.6

Thisprojectexaminesa340Vpeak-to-peaksinusoidalwaveformat60HzthathasnoDCcomponent(i.e.,itiscenteredaround0V).

1. PlotthiswaveforminMATLABbyusingthesin()function.Plotovertheinterval0ā‰¤t ā‰¤50msecinstepsof0.2msec.

2. Computeandprinttothescreentheroot-mean-square(RMS)voltageforthiswaveformbyperformingthefollowingoperationsinMATLAB:

a. Squaringit. b. Computingthemeanvalueofthesquaredwaveformbyaveragingit

overthe100-msectimeinterval. c. Takingthesquarerootoftheaverage.

3. In North America, residential electrical service is usually delivered as two340Vpeak-to-peaksinusoids,each180Ā°outofphasewitheachother(FigureP2.6a),referredtoasone-phaseservice.Forhigh-powerappliances(e.g.,airconditionersandstoves),thecurrentisdrawnfrombothā€œlegsā€oftheservice.

ā€“170

170

t

v Phase A

Phase B

1 sec60

(a)

ā€“170

170

t

120Ā°

v Phase A Phase B Phase C

120Ā°

(b)

Figureā€‚P2.6ā€‚ (a)ā€‚One-phaseā€‚powerā€‚isā€‚deliveredā€‚asā€‚twoā€‚sinusoidsā€‚thatā€‚areā€‚outā€‚ofā€‚phaseā€‚byā€‚180Ā°.ā€‚(b)ā€‚Three-phaseā€‚powerā€‚isā€‚deliveredā€‚asā€‚threeā€‚sinusoidsā€‚thatā€‚areā€‚outā€‚ofā€‚phaseā€‚byā€‚120Ā°.

Page 83: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 67

a. Plotthedifferencewaveformbetweenthetwolegsofone-phaseservice. b. Compute andprint to the screen theRMSvalueof thedifference

waveform(asinpart2).4. Inmanycommercialandindustrialbuildings,three-phaseelectricalserviceis

deliveredasthree340Vpeak-to-peaksinusoids,witheachleg120Ā°outofphasewiththeothers(seeFigureP2.6b).

a. Plotthewaveformofthevoltagedifferencebetweenanytwoofthethreelegs

b. ComputeandprinttothescreentheRMSvalueofthiswaveform.Mosthigh-voltageappliancesareratedtoworkateitheroftheRMSvoltagescomputedinpart3orpart4.

Project.2.7

Given the followingcomponentvalues in theparallelRLCcircuitdescribed inSection2.17

R=100Ī©,L =1mH,C =1Ī¼F

andthe following initialconditions,determine thecoefficientsA andB for thefollowingthreecases:

1. = =(0) 0.25A, (0) 6 Vi vL C

[Hint:convert (0)iL to (0)v withEquation(2.7).]

2. = āˆ’ =(0) 0.25A, (0) 6 Vi vL C

3. = =(0) 0, (0) 6 Vi vL C

For each case, determine an expression for A and B in terms of R, L, C,(0) and (0)v iC L andwriteaMATLABprogramthatwill

a. Determinev(t)for0ā‰¤t ā‰¤500Ī¼secinstepsof1Ī¼sec. b. Printoutatableofvversustevery10Ī¼sec.

c. Plotvversust forallthreecasesonthesamegraph.LabeleachcurvewiththevalueofiL(0).

Project.2.8

Theenvelopeof thevoltagewaveformfor theparallelRLCcircuitdescribed inSection2.17isgivenby

= Ā± ( )āˆ’( ) 2v t Aet

RC (P2.8)

Giventhefollowingcomponentvalues

R=5000Ī©,L =1Ī¼H,C =10pF

= =(0) 0 A, (0) 3.3Vi vL C

determinev(t)for0ā‰¤t ā‰¤50nsecinstepsof1nsec.Plotvversustforboththeoscillatingfunctionanditsenvelopeonthesamegraph.

Page 84: Numerical and Analytical Methods with MATLAB for

68ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.2.9

InsteadofusingvasthestatevariableintheanalysisoftheparallelRLCcircuit,wecanuseiLbydifferentiatingbothsidesofEquation(2.6)andcombiningwithEquation(2.7)toobtainthedifferentialequation

+ + =

1 1 02

2d idt RC

didt LC

iL LL (P2.9a)

NotethatEquation(P2.9a)hastheidenticalformasEquation(2.12)andthushassolutionsoftheidenticalform.Fortheunderdampedcase,

= āˆ’ Ī± āˆ’ +Ī² āˆ’exp 12

cos 1 12

sin 1 12

2 2

iRC

tLC RC

tLC RC

tL .(P2.9b)

where Ī±andĪ² are constants to be determined by initial conditions and haveamperesasunits.

ForthecomponentvaluesR=100Ī©,L =1mH,C =1Ī¼F,andinitialcondi-tions =(0) 0iL and =(0) 6 VvC ,

1. SolveforthecoefficientsĪ±andĪ². 2. PlotiL(t)for0ā‰¤t ā‰¤500Ī¼secinstepsof0.5Ī¼sec

3. PlotiL(t)andvC(t)(solvedinProject2.7)onthesameaxes.NotethatwhenvCisatamaximum,iLiszeroandviceversa.Thisillustrateshowtheenergyinthecircuitoscillatesbackandforthbetweenthecapacitorandinductor.

Project.2.10

Theclassicalformforasecond-orderdifferentialequationis

+ Ī¶Ļ‰ + Ļ‰ =2 0

2

22d y

dtdydt

yn n (P2.10a)

whereĪ¶isthedamping factor,andĻ‰nisthenatural frequency.WecanmatchthetermsofEquation(P2.9a)withEquation(P2.10a)tofindthedampingfactorandnaturalfrequencyfortheparallelRLCcircuit.Thus,

Ļ‰ = Ī¶ =

Ļ‰=

1 and 12 2LC RC

LCRCn

n (P2.10b)

NotethatforĪ¶ <1thecircuitisunderdamped,forĪ¶ >1thecircuitisoverdamped,andforĪ¶ =1,itiscriticallydamped.

For the component values L = 1 mH, C = 1 Ī¼F, and initial conditions=(0) 0.25iL Aand =(0) 6vC V:

1. DeterminetheresistorvalueRcritthatmakesthecircuitcriticallydamped.2. Plot the inductor current iL versus time for the three values of R: R = Rcrit,

R = 5 Rcrit,and = 12R Rcrit .Assumetheinterval0ā‰¤t ā‰¤500Ī¼secinstepsof0.5

Ī¼sec.Plotallofthewaveformsononegraph.

Page 85: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 69

Project.2.11

WewishnowtoconsidertheRLCcircuitdescribedinSection2.17tobesubjectedtoadrivingcurrentsuchthatinsteadofopeningtheswitchatt =0,weclosetheswitch.Inthiscase,thesumofthecurrentsatthetopleftnodeis

+ + āˆ’ = 0i i i IR L C o (P2.11a)

NotethattheIotermisnegativebecauseIoisarbitrarilydefinedinFigure 2.17asflowing into thenodeinsteadofaway fromthenode(as istruefortheotherthreecurrents).

Thegoverningequationthenbecomes

+ + =

1 12

2d idt RC

didt LC

i IL LL o (P2.11b)

Thecompletesolutionofthisdifferentialequationisequaltothehomogeneoussolution(foundinProject2.9)plusaparticular solution.

Letusassumethatthedrivingcurrentisasinusoidoftheform = Ļ‰( ) sin .I t A to o o To obtain the particular solution ip, we seek a solution whose first and secondderivativescanbesummedtoequaltheformofthedrivingcurrent.Thus,assume

= Ļ‰ + Ļ‰sin cosi A t B tp p o p o (P2.11c)

whereApandBpareconstants.Then,

=Ļ‰ Ļ‰ āˆ’ Ļ‰( cos sin )i A t B tp o p o p o

and

=Ļ‰ āˆ’ Ļ‰ āˆ’ Ļ‰( sin cos )2i A t B tp o p o p o

SubstitutingtheseexpressionsintoEquation(P2.11b)gives

āˆ’ Ļ‰ āˆ’ Ļ‰ + Ļ‰ + āˆ’ Ļ‰ + Ļ‰ + Ļ‰ = Ļ‰

1 1 sin 1 1 cos sin2 2ARC

BLC

A t BRC

ALC

B t A tp o o p p o p o o p p o o o

(P2.11d)

CollectingcoefficientsofthesineandcosinetermsontheleftsideofEquation(P2.11d)andequatingthemtothesineandcosinecoefficientsontherightsideofthatequationgives

āˆ’Ļ‰ āˆ’

Ļ‰=

1 2

LCA

RCB Ao p

op o

Ļ‰+ āˆ’Ļ‰ =

1 02

RCA

LCBo

p o p

Page 86: Numerical and Analytical Methods with MATLAB for

70ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

SolvingthesetwoequationsforAp andBPgives

= Ɨāˆ’Ļ‰

Ļ‰+ āˆ’Ļ‰

1

1

2

22

2A A LC

RC LC

p o

o

oo

(P2.11e)

=āˆ’ Ɨ

Ļ‰

Ļ‰+ āˆ’Ļ‰

122

B A RC

RC LC

p o

o

oo

(P2.11f)

SubstitutingEquations(P2.11e)and(P2.11f)intoEquation(P2.11c)gives

= ƗĻ‰

+ āˆ’Ļ‰

āˆ’Ļ‰ Ļ‰ āˆ’Ļ‰

Ļ‰11

1 sin cos22

22i A

RC LCLC

tRC

tp oo

o

o oo

o (P2.11g)

WecanrewriteEquation(P2.11g)usingthetrigonometricidentity

Ī±sinĻ‰t+Ī²cosĻ‰t=Ī³sin(Ļ‰tāˆ’ Ļ•)

where

Ī³ = Ī± +Ī²2 2

and

Ļ†=

Ī²Ī±

āˆ’tan 1

ApplyingtheserelationstoEquation(P2.11g)gives

= Ɨ

āˆ’Ļ‰ +Ļ‰

Ļ‰ āˆ’ Ļ†1

1sin( )

22 2

i A

LC RC

tp o

oo

o (P2.11h)

UsingthedefinitionsfromProject2.10fornaturalfrequencyĻ‰ =1LCn and

dampingfactor Ī¶=Ļ‰

12RC n

,wecanalgebraicallymanipulateEquation(P2.11h)into

=Ļ‰

āˆ’Ļ‰Ļ‰

+ Ī¶Ļ‰Ļ‰

Ļ‰ āˆ’Ļ†1

1 2

sin( )2 2

iA

tpo

no

n

o

n

o (P2.11i)

Page 87: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 71

Theterm

Ļ‰āˆ’Ļ‰Ļ‰

+ Ī¶Ļ‰Ļ‰

1

1 22 2

Ao

no

n

o

n

istheamplitudeoftheoscillation.ForagivenĻ‰Ao

n,

thelargerthetermāˆ’Ļ‰Ļ‰

+ Ī¶Ļ‰Ļ‰

1

1 22 2

o

n

o

n

,thelargeristheamplitude.

āˆ’Ļ‰Ļ‰

+ Ī¶Ļ‰Ļ‰

Let ampl = 1

1 22 2

o

n

o

n

1. ConstructaMATLABprogramtocreateaplotofamplversus Ļ‰Ļ‰

o

nfor

valuesofĪ¶=1.0,0.5,0.25,0.10,0.05,and <Ļ‰Ļ‰

<0 2o

ninstepsof0.01.

2. WhathappensasĻ‰ ā†’Ļ‰o n?

Project.2.12

ModifyExample2.25asfollows:

1. Useaself-writtenfunctionsavedasan.mfiletodotheinterpolation.Thelinearinterpolationformulafory(x)=f(x)expressionis

= +

āˆ’āˆ’

Ɨ āˆ’( )11

2 12 1y y

x xx x

y y

wherepoints(x1,x2)arethenearestsurroundingpointstox and(y1,y2)aretheyvaluesat(x1,x2),respectively.UseaglobalstatementtobringT1,T2,Ī¼1,andĪ¼2intotheself-writtenfunction,whereT1,T2aretheclosesttemperaturetablevaluestothetempera-tureatwhichĪ¼istobedeterminedandĪ¼1,Ī¼2aretheĪ¼valuesatT1,T2respectively.

2. Printoutthetabledatatothescreen,thenasktheuserifheorshewishestointer-polateforĪ¼atatemperatureotherthanthosetemperaturesgiveninthetable.Iftheanswerisyes,asktheusertoenterthetemperature,dotheinterpolation,andprintouttheresult.Usetheswitchgrouptodeterminewhethertodotheinterpolation.Iftheanswertoyourqueryisno,exittheprogram.

3. Iftheanswertothequeryinpart2isyes,thenasktheuserifheorshewishestoenteranothertemperature;ifyes,asktheusertoenterthetemperature,dotheinterpolation,andprintouttheresult.Theprocessistocontinueuntiltheanswertothequeryisno.Theuseristoenterthefollowingfivetemperatures(k),oneatatime:125,180,218,334,427.

Page 88: Numerical and Analytical Methods with MATLAB for

72ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.2.13

ThisprojectisamodificationofExample2.24inwhichtheā€œanonymousfunctionā€thatdoestheinterpolationistoconsistofargumentsof , , , ,1 2 1 2x x x y y .andusestheinterpolationformula

= +

āˆ’āˆ’

Ɨ āˆ’( )11

2 12 1y y

x xx x

y y

wherepoints(x1,x2)arethenearestsurroundingpointstox and(y1,y2)arethey values at (x1, x2) , respectively. In Example 2.6, it was shown that the inputvariablestoafunctionneednothavethesamenamesasthoseusedinthecallingprogram. For one-to-one correspondence, the argument positions in the callingprogrammustbethesameastheargumentpositionsinthefunction.TablevaluesforelectronmobilityĪ¼asafunctionoftemperatureTareasfollows:

T =[100150200250300350400450]

Ī¼ =[196507427372321801407972.0705.5531.8]

TheunitsforT are(K)andtheunitsforĪ¼are(cm2/V-s).

1. CreateaMATLABprogramthatcontainstheanonymousfunctionasdescribedandthatinterpolatesfortheelectronmobility Ī¼atthefollowingtemperaturesTT:

TT =[110165215365440]

2. PrintoutatableofvaluesofĪ¼attemperaturesTT.

Project.2.14

Indiscrete-timesignalprocessing,signalsarerepresentedasasequenceofdiscretenumericalvalues,asopposedtotheā€œsmoothā€waveformsincontinuous-timesig-nalprocessing.

FigureP2.14ashowsacontinuous-timewaveform(a1-kHzsinewave)anditsdiscrete-time counterpart,which is generatedby sampling the continuous-timesignalatarateof8000samples/sec(every125Ī¼sec).Thissamplingrateiscom-monlyusedforvoice-gradetelephonyequipment,andtheresultingdiscrete-timesequence might subsequently be transmitted by methods such as PAM (pulseamplitudemodulation)orPCM(pulsecodemodulation).

Now,supposewewanttousethissampledwaveforminamoviesoundtracktoberecordedonDVD.ThedigitalaudioonDVDstypicallyusesasamplingrateof48,000samples/sec(every20.8333Ī¼sec); thus,wewillneedtoupsampleour8000-sample/secwaveformtouseitonDVD.

Inupsampling,weaugmentagivendiscretewaveformbyaddingsamplestothe sequence to achieve the desired higher sampling rate. In this case, upsam-plingfrom8000to48,000samples/secwillrequireaddingfivenewsamplesforeveryoneintheoriginalwaveform.Therearemanymethodsfordoingthis,andonesimpleapproachistocomputevaluesfortheaddedsamplesbyinterpolatingbetweenadjacentvaluesoftheoriginalwaveform(FigureP2.14b).

Page 89: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 73

DevelopaMATLABprogramthatwill

1. Computethesignalvaluesoftheoriginal8000-samples/secwaveformovertheperiodof0<t ā‰¤2msec,foratotalof17samples.AssumesignalpeakvaluesofĀ±1forthesinewave.

2. Createatableconsistingofsamplenumber, sampletime,andsamplesignalvalue.

3. UseMATLABā€™sinterp1functiontocalculatetheupsampledwaveform(i.e.,atasamplerateof48,000samples/sec).Toavoidround-offerror,useĪ”t=20.833333Ī¼sec.Youshouldendupwithasamplesizeof97values.

t

v

1

ā€“1

1 msec

125 Āµsec

(a)

t

v

1

ā€“1

1 msec

20.833333 Āµsec

(b)

Figureā€‚P2.14ā€‚ (a)ā€‚Aā€‚1-kHzā€‚sineā€‚waveā€‚isā€‚sampledā€‚atā€‚8000ā€‚samples/sec.ā€‚(b)ā€‚Ifā€‚weā€‚wantā€‚toā€‚upsampleā€‚theā€‚sineā€‚waveā€‚toā€‚48,000ā€‚samples/sec,ā€‚weā€‚needā€‚toā€‚interpolateā€‚fiveā€‚additionalā€‚samplesā€‚betweenā€‚pointsā€‚ofā€‚theā€‚originalā€‚waveform.

Page 90: Numerical and Analytical Methods with MATLAB for

74ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

4. Plot theoriginaland theupsampledwaveformson the samegraph.For theoriginal sample waveform, use circles to display the data points. For theupsampledwaveform,useƗ stodisplaythedatapoints.

Project.2.15

This project involves determining the quality of the upsampled waveform ofProject2.14.This isaccomplishedbycomparingtheupsampledwaveformwithan ideal 1-kHz sinewave.A commonperformancemetric for audio systems isthetotal harmonic distortion(THD),whichisameasureofthenoiseatharmonicfrequenciesotherthanthefrequencyofinterest(1kHzinourcase).Becauseoursignalisperiodicandofknownfrequency,wecanassumethatalltheimperfec-tionswillcontributetotheTHD.DevelopaMATLABprogramthatwill

1. Compute the valuesof an ideal48,000-samples/secwaveformVideal over theperiodof0<t ā‰¤2msec,foratotalof97samples.AssumewaveformpeakvaluesofĀ±1forthesinewave.

2. Subtract this idealwaveformfromourupsampled48,000-samples/secwave-formtocalculate thewaveformerrorVerror for the interpolationmethodthatwasusedinProject2.14.

3. CalculatetheTHDoftheupsampledwaveformasfollows:

( )( )

=THD ,2

,2

V

Verror RMS

ideal RMS

(P2.15)

UsethemethoddescribedinProject2.6tocalculate( ),Verror RMS and( ),Videal RMS .

4. Printout ,Verror RMS , ,Videal RMS ,andTHD.

Project.2.16

Mathematician Joseph Fourier is credited with the theorem that any periodic waveformmaybeexpressedasasummationofpuresinesandcosines.Forexam-ple,thesquarewaveofFigureP2.16acanbewrittenasasumofsines:

āˆ‘

=Ļ€

Ļ€+

Ļ€Ļ€

+Ļ€

Ļ€+

=Ļ€

Ļ€

=

āˆž

( ) 4 sin2 4

3sin

6 45

sin10

4 sin2

1odd

v tt

Tt

Tt

T

kk t

Tkk

FigureP2.16bshowsthefirstthreetermsoftheseriesandtheirsummation.

1. Write a MATLAB script that implements a self-written functionsqwave(n,T,i),whichtakesthefollowingarguments:

n the number of terms of the Fourier series

T the period of the square wave in seconds

i the number samples per period

Page 91: Numerical and Analytical Methods with MATLAB for

MATLAB Fundamentalsā€ƒ ā—¾ā€ƒ 75

Thefunctionshouldreturntwoarrays,tandV,eachcontainingielements,where

t=anarrayofitimepoints.V=anarrayoficomputedvaluesofthenth-degree approximatedsquarewave

2. Run yoursqwave(n,T,i) function and plot the results for the followingarguments:

T=1msec,i=1001,n=1,3,10,100

3. Forn=100,printoutatableof(t,V)atevery20timepoints.

Project.2.17

Bobā€™sHardwareStorewishestocreateanonlineprogramtosellinventoryitemsinitsstore.YouaretocreateaninteractiveMATLABprogramforthispurpose.Thepro-gramistocontainthefollowingitems:adatafile,amainscriptandabillingfunction.

t

v

1

ā€“1

T = 1 ms(a)

t

v

2nd term

1st term

3rd term

Sum of 1st, 2ndand 3rd terms1

ā€“1

(b)

Figureā€‚P2.16ā€‚ (a)ā€‚Squareā€‚wave.ā€‚(b)ā€‚ Threeā€‚termsā€‚inā€‚aā€‚Fourierā€‚seriesā€‚ofā€‚aā€‚squareā€‚wave.

Page 92: Numerical and Analytical Methods with MATLAB for

76ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Datafile:Thedatafileistocontainadescriptionoftheinventoryitemsforsale,theircost,andthequantityavailableforsale.Thelistshouldcontainatleast10items.Thisdatafilewillbe read into themain script.Wheneveran item ispurchased, theinventoryavailableforsaleshouldbeupdatedinthedatafile.

Mainscript:1. Thescriptistoprinttothescreentheitemsforsale,theircost,andthequantity

availableforpurchase.2. Thescriptistoasktheuserifheorshewishestomakeapurchase.Ifyes,the

scriptistoasktheuserthelinenumberoftheitemheorshewishestopurchaseandthequantity.

3. Iftheuserdoesnotwishtomakeapurchase,exittheprogram.Iftheuserdoesnot respondcorrectly to thequery,printanerrormessage to the screenandinformtheusertorestarttheprogram.Then,exittheprogram.

4. Iftheuserdoesmakeapurchase,theprogramistocontinueaskingtheuserifheorshewishestomakeanotherpurchase.Ifyes,printtothescreenthelistofitems,theircost,andtheupdateditemsavailableforpurchase.Then,thescriptistoasktheuserthelinenumberoftheitemheorshewishestopurchaseandthequantity.Iftheanswerisno,exittheprogram.

Billingfunction:Whentheuserisfinishedmakingallofhisorherpurchases,themainscriptistocallthebillingfunctionthatprintsoutabillfortheitemspurchased.Thebillshouldcontainthenameandaddressofthestore,theuserā€™sfirstandlastnames,theuserā€™saddress,billheadings,alistofalltheitemspurchased,theitemsā€™unitprices,thetotalpriceforeachitempurchased,andfinallythetotalpriceofalltheitemspurchased.

References 1. Kernighan,B.W.,andRitchie,D.M.,The C Programming Language,2nded.,Prentice-

Hall,EnglewoodCliffs,NJ,1988. 2. Sze,S.M.,Physics of Semiconductor Devices,2nded.,Wiley,NewYork,1981. 3. Kreyszig,E.Advanced Engineering Mathematics,8thed.,Wiley,NewYork,1999.

Page 93: Numerical and Analytical Methods with MATLAB for

77

Chapter 3

Matrices

3.1ā€‚ ā€‚IntroductionInengineering,wearefrequentlyconfrontedwithmatricesoraprobleminvolvingasetoflinearequations.Inaddition,thebasicelementinMATLABĀ®isamatrix,anditisthereforeappropriatetohaveachapteronmatrices.First,wediscusssomebasicmatrixconceptsandoperationsandthetreatmentofmatricesinMATLAB,includingseveralsampleMATLABprogramsinvolvingmatrices.Thisisfollowedbyadiscussionofseveralmethodsforsolvingasystemoflinearequations,includ-ingtheuseofMATLABā€™sinvfunction,Gausselimination,andtheGauss-Jordanmethods.Anexampleoftheuseofmatricestosolveaprobleminresistivecircuitsisincluded.Finally,thematrixeigenvalueproblemisdiscussed,includinganapplica-tiontoaresonantcircuitproblem.

3.2ā€‚ ā€‚Matrixā€‚Operationsā—¾ Arectangulararrayofnumbersofthefollowingformiscalledamatrix.

=

11 12 1

21 22 2

1 2

A

a a aa a a

a a a

n

n

m m mn

Thenumbersaijinthearrayarecalledtheelementsofthem ƗnmatrixA.

Page 94: Numerical and Analytical Methods with MATLAB for

78ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ā—¾ Amatrixofmrowsandonecolumniscalledacolumnvector.

ā—¾ Amatrixofonerowandncolumnsiscalledarowvector.

ā—¾ Matricesobeycertainrulesofaddition,subtraction,andmultiplication.

ā—¾ Additionandsubtraction:IfmatricesAandBhavethesamenumberofrowsandcolumns,then

= + =

+ + ++ + +

+ + +

( ) ( ) ( )( ) ( ) ( )

( ) ( ) ( )

11 11 12 12 1 1

21 21 22 22 2 2

1 1 2 2

C A B

a b a b a ba b a b a b

a b a b a b

n n

n n

m m m m mn mn

= āˆ’ =

āˆ’ āˆ’ āˆ’āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

( ) ( ) ( )( ) ( ) ( )

( ) ( ) ( )

11 11 12 12 1 1

21 21 22 22 2 2

1 1 2 2

C A B

a b a b a ba b a b a b

a b a b a b

n n

n n

m m m m mn mn

ā—¾ AdditionandsubtractionofthematricesAandBareonlydefinedifAandBhavethesamenumberofrowsandcolumns.

ā—¾ Multiplication:TheproductABisonlydefinedifthenumberofcolumnsinAequalsthenumberofrowsinB.IfC.=.AB,where

= =and11 12 13

21 22 23

11 12

21 22

31 32

A Ba a aa a a

b bb bb b

then

=

+ + + +

+ + + +C

( ) ( )( ) ( )

11 11 12 21 13 31 11 12 12 22 13 32

21 11 22 21 23 31 21 12 22 22 23 32

a b a b a b a b a b a ba b a b a b a b a b a b

ā—¾ IfAhasmrowsandBhasKcolumns,thenC.=.ABwillhavemrowsandKcolumns.Ageneralexpressionfortheelementcijis

āˆ‘==1

c a bij ik kj

k

K

InMATLAB,themultiplicationofmatricesAandBisenteredasA * B.

Page 95: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 79

ā—¾ Transpose:Thetransposeofamatrixistheoperationofexchangingtherowsandcolumns.If

=

2 5 17 3 84 5 2116 3 10

A

then

=2 7 4 165 3 5 31 8 21 10

AT

InMATLAB,thetransposeofmatrixAisenteredasAā€™.

ā—¾ Summingtheelementsofavectororthecolumnsofamatrix:

= = + +If [ ], then sum( ) .1 2 3 1 2 3A Aa a a a a a

If

=11 12 13

21 22 23

31 32 33

Bb b bb b bb b b

then

= + + + + + +sum( ) [( ) ( ) ( )]11 21 31 12 22 32 13 23 33B b b b b b b b b b

InMATLAB,thesumofmatrixAisenteredassum(A).

ā—¾ Dotproduct:Thedotproductoftwovectorsisdefinedas

āˆ‘ā‹… =A B a bi i

Forexample,if = āˆ’[4 1 3]A and = āˆ’[ 2 5 2]B ,then

ā‹… = āˆ’ + āˆ’ + = āˆ’(4)( 2) ( 1)(5) (3)(2) 7A B

Page 96: Numerical and Analytical Methods with MATLAB for

80ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Theresultofadotproductisalwaysascalar(i.e.,asinglenumber). InMATLAB,thedotproduct ā‹…A B isenteredasdot(A,B).

ā—¾ Identity:TheidentitymatrixIisamatrixwherethemaindiagonalelementsarealloneandallotherelementsarezero.

= =IA AI A

Forexample,forthecaseofathree-by-threematrixA,

=

=+ + + + + ++ + + + + ++ + + + + +

1 0 00 1 00 0 1

( 0 0) (0 0) (0 0 )( 0 0) (0 0) (0 0 )( 0 0) (0 0) (0 0 )

11 12 13

21 22 23

31 32 33

11 12 13

21 22 23

31 32 33

AIa a aa a aa a a

a a aa a aa a a

InMATLAB,youcangenerateann Ɨnidentitymatrixwitheye(n).

ā—¾ Inverse:Theinverseofamatrix,denoted āˆ’A 1 ,isamatrixsuchthat

= = = Ɨāˆ’ āˆ’A A AA I1 0 00 1 00 0 1

(for a 3 3 matrix)1 1

InMATLAB,thematrixinverse āˆ’A 1 isenteredasinv(A).

ā—¾ Determinant:

Beforetheuseofcomputers,determinantsweredevelopedasamethodforobtainingasolutiontoasystemof linearequations.Computationally, it isonlypracticalforasysteminvolvingjustafewequations[1].However,deter-minantsdohaveanapplicationintheeigenvalueproblemthatisdiscussedattheendofthischapter.

Thedeterminantofa2Ɨ2matrixis

= = āˆ’

11 12

21 2211 22 12 21D

a a

a aa a a a

Notethatthedeterminantofamatrixiswrittenwithtwostraightlinesthatenclosethematrixelements.

Page 97: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 81

Thedeterminantofa3Ɨ3matrixis

= = āˆ’ +

11 12 13

21 22 23

31 32 33

11

22 23

32 3312

21 23

31 3313

21 22

31 32

D

a a a

a a a

a a a

aa a

a aa

a a

a aa

a a

a a

InMATLAB,thedeterminantofthematrixAisenteredasdet(A).

ā—¾ Dimensions:YoucanobtainthesizeofmatrixAbyrunningsize(A).Thiscommandisusefulwhenyourunascriptandyougetanerrormessagelikeā€œIndex exceeds matrix dimensions.ā€ Adding thesize()command in thescriptwillhelpyoudeterminetheproblem.

ā—¾ Element-by-elementoperations:Giventwomatricesofthesamedimensions,wecanperformelement-by-elementmultiplicationanddivisioninMATLABwiththe.*and./operators.

Given = 1 2 3A a a a and = 1 2 3B b b b ,then

= =. * 1 1 2 2 3 3C A B a b a b a b

= =. / 1

1

2

2

3

3D A B

ab

ab

ab

Also,notethedotproductcanbeexpressedasacombinationofanele-ment-by-elementmultiplicationandasum:

( )ā‹… = = = + +sum( . * ) sum 1 1 2 2 3 3 1 1 2 2 3 3A B A B a b a b a b a b a b a b

ā—¾ Productoffunctionsoftwovectors:

AsdescribedinChapter2,MATLABallowstakingafunctionofavectorandthattheresultisalsoavector.However,ifascriptrequiresamathemati-caloperationoftwofunctions(suchasaproductoftwovectorfunctions),thentheoperationwillrequireanelement-by-elementoperation.

In the followingexample,wecompute theproductof twovector func-tions,bothdirectlyandindirectly,byusingaforloopandmultiplyingtheelementsofeachfunction.Writethissimplescriptintoanewscriptwindow,saveitasmatrix_example.m,andrunthescript:

Page 98: Numerical and Analytical Methods with MATLAB for

82ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%matrix_example.m clear;clc; x=0:30:360; %y1istheproductoftwovectorfunctions y1=sind(x).*cosd(x); fprintf('x y1 y2\n'); fprintf('--------------------------------------\n'); forn=1:length(x); %y2(n)istheproductoftheelementsofthetwo %functions. y2(n)=sind(x(n))*cosd(x(n)); fprintf('%5.1f%8.5f%8.5f\n',x(n),y1(n),y2(n)); end -------------------------------------------------------

Dothetwodifferentmethodsforcomputingy1andy2givethesameanswer?

Exampleā€‚3.1:ā€‚ Matrixā€‚Operations

The following example illustrates several matrix operations, including addi-tion, dot product, element-by-element multiplication and division, sum, and transpose.

%Example_3_1.m%ThisprogramdemonstratesmatrixalgebrainMATLABclear;clc;a=[159]b=[2612]c=a+bd=dot(a,b)e=a.*bf=a./bg=sum(a.*b)h=a*b'---------------------------------------------------------------------------

3.3ā€‚ ā€‚Systemā€‚ofā€‚Linearā€‚EquationsInengineering,wearefrequentlyconfrontedwiththeproblemofsolvingasetoflinearequations.

Giventhesetofequations

+ + + + =

+ + + + =

+ + + + =

11 1 12 2 13 3 1 1

21 1 22 2 23 3 2 2

1 1 2 2 3 3

a x a x a x a x ca x a x a x a x c

a x a x a x a x c

n n

n n

n n n nn n n

(3.1)

Page 99: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 83

Thesetcontainsnequationsinnunknowns.Itisconvenienttoexpressthesetasamatrixequationoftheform

==AX C (3.2)

where

= = =, ,

11 12 1

21 22 2

1 2

1

2

1

2A X C

a a aa a a

a a a

xx

x

cc

c

n

n

n n nn n n

MatrixAhasnrowsandncolumns.MatrixXhasnrowsand1column.Note:ThenumberofcolumnsinAmustequalthenumberofrowsinX;other-

wise,matrixmultiplicationisnotdefined.MatrixChasnrowsand1columnInmatrixalgebra,Xcanbeobtainedbymultiplyingbothsidesby āˆ’A 1 ,thatis,

= = =ā€“1 ā€“1 ā€“1A AI

X A C IX X A C

MATLABoffersthefollowingfunctionsforsolvingasetoflinearequations:

ā—¾ Theinvfunction:

TosolveasystemoflinearequationsinMATLAB,youcanuse

X=inv(A)*C

Themethodofsolvingasystemoflinearequationsbyusingtheinvfunc-tionismorecomputationallycomplicatedthanamethodcalledGausselimi-nation,whichisdiscussednext.

ā—¾ TheGausseliminationfunction:

MATLABallowsforthesolutionofthelinearsystem,AX=C,byGausseliminationbywriting

X=A\C

Note theuseofMATLABā€™sbackslashoperator to solve forXbyGausselimination.

Page 100: Numerical and Analytical Methods with MATLAB for

84ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚3.2

The following example solves the three equation linear system shown and writes the results to a file:

+ āˆ’ =

āˆ’ + + =

āˆ’ āˆ’ = āˆ’

x x x

x x x

x x x

3 2 10

3 2 5

1

1 2 3

1 2 3

1 2 3

%Example_3_2.m%Thisprogramsolvesasimplelinearsystemofequations%byboththeuseofMATLAB'sinversematrixfunctionand%bytheGausseliminationmethod.clc;clear;A=[32-1;-132;1-1-1]C=[105-1]'%X1isthesolutionusingmatrixinversefunction:X1=inv(A)*C%X2isthesolutionusingGausseliminationmethod:X2=A\C%checksolution:A*X1%Usethesize()commandtodeterminethenumberofrows%andthenumberofcolumnsinmatrixA.[A_rowsA_cols]=size(A)%PrintmatrixA,matrixCandthesolutionofthelinear%systemofequationstothefileoutput.txt:fid=fopen('output.txt','w');fprintf(fid,'Amatrix:\n');fori=1:A_rowsforj=1:A_colsfprintf(fid,'%6.1f',A(i,j));endfprintf(fid,'\n');endfprintf(fid,'Cvector:\n');fori=1:length(C)fprintf(fid,'%6.1f',C(i));endfprintf(fid,'\n');fprintf(fid,'SolutionX1(usinginversematrix):\n');fori=1:length(X1)fprintf(fid,'%6.1f',X1(i));endfprintf(fid,'\n');fprintf(fid,'SolutionX2(usingGausselimination):\n');fori=1:length(X2)fprintf(fid,'%6.1f',X2(i));endfprintf(fid,'\n');fclose(fid);

Page 101: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 85

Exampleā€‚3.3:ā€‚ Anā€‚Exampleā€‚inā€‚Resistiveā€‚Circuits

A typical example involving a system of linear equations can be found in the resistive circuit of Figure 3.1. The goal is to solve for the node voltages v1, v2 , and v3 as functions of the input voltages V1 and V2 and the input current I1.

Using Ohmā€™s law (v = iR) and Kirchhoffā€™s current law (KCL), we can write expressions for the sum of currents at each node of interest. KCL states that the total current entering any circuit node must sum to zero. In Figure 3.1, the resistor currents are written as in and are arbitrarily defined in the directions as drawn. Writing three KCL equations for the currents entering each node (and noting that currents drawn as leaving the node are written mathemati-cally as negative numbers) gives

At node āž€: + + =i i i 01 2 3 (3.3)

At node āž: āˆ’ + =I i i 01 2 4 (3.4)

At node āž‚: āˆ’ āˆ’ + =i i i 03 4 5 (3.5)

We now rewrite these three equations in terms of voltages using Ohmā€™s law. Note that in these types of problems, it is often easier to write the equa-

+ā€“

+ā€“

R1

R2

R3

R4

R5i1

2

31

i2

i3

i4

i5

V1 V2I1

v1v2

v3

Figureā€‚3.1ā€‚ Resistiveā€‚circuit.

Page 102: Numerical and Analytical Methods with MATLAB for

86ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

tions in terms of conductances Gn instead of resistances (where =1/G Rn n), and Ohmā€™s law may be rewritten as i = vG. Thus,

=

āˆ’ā†’ = āˆ’i

V vR

i V v G( )11 1

11 1 1 1 (3.6)

=

āˆ’ā†’ = āˆ’i

v vR

i v v G( )22 1

22 2 1 2 (3.7)

=

āˆ’ā†’ = āˆ’i

v vR

i v v G( )33 1

33 3 1 3 (3.8)

=

āˆ’ā†’ = āˆ’i

v vR

i v v G( )43 2

44 3 2 4 (3.9)

=

āˆ’ā†’ = āˆ’i

V vR

i V v G( )52 3

55 2 3 5 (3.10)

Substituting these expressions for i1 through i5 into Equations (3.3) to (3.5) gives

āˆ’ + āˆ’ + āˆ’ =V v G v v G v v G( ) ( ) ( ) 01 1 1 2 1 2 3 1 3 (3.11)

āˆ’ āˆ’ + āˆ’ =I v v G v v G( ) ( ) 01 2 1 2 3 2 4 (3.12)

( ) ( ) ( )āˆ’ āˆ’ āˆ’ āˆ’ + āˆ’ =v v G v v G V v G 03 1 3 3 2 4 2 3 5 (3.13)

These expressions can be rearranged into a system of three equations with three unknowns:

+ + āˆ’ āˆ’

āˆ’ + āˆ’

āˆ’ āˆ’ + +

=

G G G G GG G G GG G G G G

vvv

VGI

V G

( )( )

( )

1 2 3 2 3

2 2 4 4

3 4 3 4 5

1

2

3

1 1

1

2 5

(3.14)

This equation has the form AXā€‚=ā€‚C and may be solved by Guass elimination as shown previously in Example 3.2.

The following script solves for the node voltages for the following circuit values:

= = = = =

= = =

R R R R R

V V I

2200 , 10 k , 6900 , 9100 , 3300

12V, 3.3 V, 2 mA

1 2 3 4 5

1 2 1

Page 103: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 87

%Example_3_3.mResistiveCircuit%Thisprogramsolvesfortheinternalnodevoltagesfor%thecircuitshowninFigure3.1.%TheconductancesGareinunitsofsiemens%ThenodevoltageVareinunitsofvolts%ThecurrentsIareinunitsofampsclear;clc;g1=1/2200;g2=1/10000;g3=1/6900;g4=1/9100;g5=1/3300;V1=12;V2=3.3;I1=.002;%PuttheproblemintostandardformAX=C:A=[g1+g2+g3-g2-g3;-g2g2+g4-g4;-g3-g4g3+g4+g5];C=[V1*g1;I1;V2*g5];X=A\C;%printtheresultsfprintf('V1=%9.1fV\nV2=%9.1fV\nI1=%9.1eA\n',V1,V2,I1);fprintf('g1=%9.5fS\ng2=%9.5fS\ng3=%9.5fS\n',g1,g2,g3);fprintf('g4=%9.5fS\ng5=%9.5fS\n',g4,g5);fprintf('\n');fprintf('Node#v(volts)\n');fprintf('-------------------------\n');forn=1:length(C)fprintf('%3i%9.1f\n',n,X(n));end---------------------------------------------------

3.4ā€‚ ā€‚Gaussā€‚EliminationAspreviouslydiscussed,theGausseliminationmethodiscomputationallymoreefficient than the inverse matrix method or the method of determinants withCramerā€™srule.WewishtousetheGausseliminationmethodtosolvethesystemoflinearequationsdescribedbyEquation(3.1)andrepresentedinmatrixformbyEquation(3.2).IntheGausseliminationmethod,theoriginalsystemisreducedtoanequivalenttriangularsetthatcanreadilybesolvedbybacksubstitution.Thereducedequivalent.setwouldappearlikethefollowingsetofequations:

+ + + + =

+ + + =

+ + =

=

+ =

=

āˆ’ āˆ’ āˆ’ āˆ’ āˆ’

11 1 12 2 13 3 1 1

22 2 23 3 2 2

33 3 3 3

1, 1 1 1, 1

,

a x a x a x a x c

a x a x a x c

a x a x c

a x a x c

a x c

n n

n n

n n

n n n n n n n

n n n n (3.15)

Page 104: Numerical and Analytical Methods with MATLAB for

88ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

wherethetilde(āˆ¼)variablesareanewsetofcoefficients (tobedetermined)andwherethenewcoefficientmatrix A isdiagonal(i.e.,allofthecoefficientsleftofthemaindiagonalarezero.Then,

=

= āˆ’āˆ’āˆ’ āˆ’

āˆ’ āˆ’1 ( )

etc.

,

11, 1

1 1,

x c a

xa

c a x

n n n n

nn n

n n n n

Todeterminethereducedequivalentset A and C ,itisconvenienttoaugmenttheoriginalcoefficientmatrixAwiththeCmatrixasshownbelow:

=AA

11 12 1

21 22 2

1 2

1

2

a a aa a a

a a a

cc

c

aug

n

n

n n nn n

(3.16)

Thefollowingprocedureisusedtoobtainthereducedequivalentset:

1.MultiplythefirstrowofEquations(3.1)bya21/a11andsubtractfromthesec-ondrow,giving

ā€¦= āˆ’ Ɨ = āˆ’ Ɨ = āˆ’ Ɨ, , , etc.21 21

21

1111 22 22

21

1112 23 23

21

1113a a

aa

a a aaa

a a aaa

a

and

= āˆ’ Ɨ2 2

21

111c c

aa

c

Thisgives = 021a

2.Forthethirdrow:multiplythefirstrowofEquations(3.1)by /31 11a a andsubtractfromrow3,giving

ā€¦= āˆ’ Ɨ = āˆ’ Ɨ = āˆ’ Ɨ, , , etc.31 31

31

1111 32 32

31

1112 33 33

31

1113a a

aa

a a aaa

a a aaa

a

Page 105: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 89

and

= āˆ’ Ɨ3 3

31

111c c

aa

c

Thisgives = 031a .

3.Thisprocessisrepeatedfortheremainingrows4,5,6,ā€¦,n.Theoriginalrow1iskeptinitsoriginalform.Allotherrowshavebeenmodifiedandthenewcoefficientsaredesignatedbya(ā€²).Exceptforthefirstrow,theresultingsetwillnotcontainx1.

4.Fortheprecedingsteps,thefirstrowofEquations(3.1)wasusedasthepivot row,anda11wasthepivot element.Wenowusethenewrow2asthepivotrowandrepeatsteps1ā€“3fortheremainingrowsbelowrow2.Thus,multiplythe

newrow2by 32

22

aa

andsubtractfromrow3,giving

ā€¦= āˆ’ Ɨ = āˆ’ Ɨ = āˆ’ Ɨ, , , etc.32 32

32

2222 33 33

32

2223 34 34

32

2224a a

aa

a a aaa

a a aaa

a

and

= āˆ’ Ɨ3 3

32

222c c

aa

c

Thisgives = 032a .

Similarly,multiplythenewrow2by 42

22

aa

andsubtractfromrow4,giving

ā€¦= āˆ’ Ɨ = āˆ’ Ɨ = āˆ’ Ɨ, , , etc.42 42

42

2222 43 43

42

2223 44 43

42

2224a a

aa

a a aaa

a a aaa

a

and

= āˆ’ Ɨ4 4

42

222c c

aa

c

Thisgives = 042a .

Thisprocessiscontinuedfortheremainingrows5,6,ā€¦,n.Exceptforthenewrow2,thesetdoesnotcontainx2.

Page 106: Numerical and Analytical Methods with MATLAB for

90ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

5.Thenextrowisnowusedasapivotrow,andtheprocessiscontinueduntilthe(n ā€“ 1)throwisusedasthepivotrow.Whenthisiscomplete,thenewsystemistriangularandcanbesolvedbybacksubstitution.

Thegeneralexpressionforthenewcoefficientsis

ā€¦ ā€¦= āˆ’ Ɨ = + + = + +for 1, 2, , and 1, 2, ,a a

aa

a i k k n j k k nij iji k

kkkj

wherekisthepivotrow.

Theseoperationsonlyaffectthe aij and c j .Thus,weneedonlyoperateontheAandCmatrices.

Exampleā€‚3.4:ā€‚ Given

āˆ’ + = āˆ’

āˆ’ + + = āˆ’

+ āˆ’ =

x x x

x x x

x x x

3 4

3 4 3 10

2 3 2 18

1 2 3

1 2 3

1 2 3

The augmented coefficient matrix is

=āˆ’

āˆ’āˆ’

āˆ’āˆ’

=āˆ’a

a

augA1 3 13 4 32 3 2

41018

multiply row 1 by31and subtract from row 221

11

Row 2 becomes (āˆ’3 + 3), (4āˆ’9), (3 + 3), (āˆ’10āˆ’12) = (0, āˆ’5, 6, āˆ’22)The new matrix is

=āˆ’āˆ’

āˆ’

āˆ’āˆ’

=aa

aug EquivA1 3 10 5 62 3 2

42218

multiply row 1 by21and subtract from row 3

,

31

11

Row 3 becomes (2āˆ’2), (3 + 6), (āˆ’2āˆ’2), (18 + 8) = (0, 9, āˆ’4, 26)The new matrix is

=āˆ’āˆ’

āˆ’

āˆ’āˆ’aug EquivA

1 3 10 5 60 9 4

42226

,

Page 107: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 91

We now use row 2 as the pivot row.

=āˆ’āˆ’

āˆ’

āˆ’āˆ’

= āˆ’aa

aug EquivA1 3 10 5 60 9 4

42226

multiply row 2 by95and subtract from row 3

,

32

22

Row 3 becomes

āˆ’ āˆ’ Ɨ āˆ’ + Ɨ āˆ’ Ɨ = āˆ’(0 0), 9

95

5 , 495

6 , 2695

22 0, 0,345

,685

The new matrix is

=

āˆ’

āˆ’

āˆ’

āˆ’

āˆ’

aug EquivA

1 3 1

0 5 6

0 0345

4

22

685

,

The system is now triangular, and the system can be rewritten as

=Equiv EquivA X C

which gives

āˆ’ + = āˆ’

āˆ’ + = āˆ’

= āˆ’

x x x

x x

x

3 4

5 6 22

345

685

1 2 3

2 3

3

Solving:

= āˆ’ = āˆ’

āˆ’ + āˆ’ = āˆ’ =

āˆ’ + āˆ’ = āˆ’ =

x x

x x

x x

345

685

2

5 6( 2) 22 2

3(2) ( 2) 4 4

3 3

2 2

1 1

Page 108: Numerical and Analytical Methods with MATLAB for

92ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

There are two important considerations:

1. If akk is zero, where k is the pivot row, then the process cannot be car-ried out.

2. Greater accuracy in the solution is obtained if the pivot element is the absolute maximum available from the set. That is; if the pivot row is k, one compares the aikā€™s for i = k + 1, k + 2, ā€¦ , n (see Figure 3.2). If ā†‘a ai k kk| | | |max , then the row containing the ai k| |max is interchanged with the kth row. This only affects the ordering of the equations and does not affect the solution.

If after row interchange is carried out and one of the akkā€™s remains zero, then the system is singular, and no solution can be obtained.

One last consideration: it can be shown that if the magnitude of the pivot element is much smaller than other elements in the matrix, the use of the small pivot element will cause a decrease in the accuracy of the solution. To check if this is the case, you can first scale the equations, that is, divide each equation by the absolute maximum coefficient in that equation. This makes the absolute maximum coefficient in that equation equal to 1.0. If akk << 1, then the solution is likely to be inaccurate.

3.5ā€‚ ā€‚Theā€‚Gauss-Jordanā€‚MethodTheGauss-JordanmethodisamodificationoftheGausseliminationmethodandcan be used to solve a system of linear equations of the form AX. =. C. In thismethod,theobjectiveistoobtainanequivalentcoefficientmatrixsuchthat,exceptforthemaindiagonal,allelementsarezero.Themethodstartsout,asintheGausselimination method, by finding an equivalent matrix that is triangular. It thencontinues,assumingthatAisann Ɨnmatrix,usingthenthrowasthepivotrow,multiplyingthenthrowby āˆ’1, ,a an n n n andsubtractingtheresultfromrownā€“1,thusmakingthenew =āˆ’ 01,an n .Theprocessisrepeatedforrowsn āˆ’2,n āˆ’3,ā€¦,1.

Comparefor

kth row

maxaik

Figureā€‚3.2ā€‚ Rowā€‚interchange.

Page 109: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 93

Exampleā€‚3.5

As an example, the Gauss-Jordan method is applied as follows: Starting with the triangular equivalent matrix of Example 3.4,

=

āˆ’

āˆ’

āˆ’

āˆ’

āˆ’

aug EquivA

1 3 1

0 5 6

0 0345

4

22

685

,

Multiply row 3 by = Ɨaa

6534

23

33 and subtract from row 2. Row 2 becomes

āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ Ɨ āˆ’ + Ɨ = āˆ’ āˆ’03034

0 , 53034

0 , 63034

345

, 223034

685

(0, 5, 0, 10)

Next, multiply row 3 by =aa

534

13

33 and subtract from row 1. Row 1

becomes

āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ Ɨ āˆ’ + Ɨ = āˆ’ āˆ’1

534

0 , 3534

0 , 1534

345

, 4534

685

(1, 3, 0, 2)

The new aug EquivA , becomes

=

āˆ’

āˆ’

āˆ’

āˆ’

āˆ’

aug EquivA

1 3 0

0 5 0

0 0345

2

10

685

,

Now, row 2 is used as the pivot row. Multiply row 2 by =aa

35

12

22 and

subtract from row 1. Row 1 then becomes

āˆ’ Ɨ āˆ’ + Ɨ āˆ’ Ɨ āˆ’ + Ɨ =135

0 , 335

5 , 035

0 , 235

10 (1, 0, 0, 4)

Page 110: Numerical and Analytical Methods with MATLAB for

94ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

The new aug EquivA , becomes

= āˆ’ āˆ’

āˆ’

aug EquivA

1 0 0

0 5 0

0 0345

4

10

685

,

Thus, the equivalent set of equations becomes

=

āˆ’ = āˆ’

= āˆ’

x

x

x

4

5 10

345

685

1

2

3

And thus =x 41 , =x 22 , and = āˆ’x 23 , which is the same answer that was obtained previously by the Gauss elimination method.

3.6ā€‚ ā€‚Numberā€‚ofā€‚SolutionsSupposeaGauss eliminationprogram is carriedoutand the following resultsareobtained:

+ + + + =

+ + + =

+ + =

=

+ + =

=

=

=

+

+

0

0

0

11 1 12 2 13 3 1 1

22 2 23 3 2 2

33 3 3 3

1

2

a x a x a x a x c

a x a x a x c

a x a x c

a x a x c

c

c

c

n n

n n

n n

rr r rn n r

r

r

n

Page 111: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 95

wherer <nand ā€¦, , ,11 12a a arr arenotzero.Therearetwopossiblecases:

1.Nosolutionexistsifanyoneofthe +1cr through cn isnotzero. 2.Infinitelymanysolutionsexistif +1cr through cn areallzero.

Ifr =nand ā€¦, , ,11 12a a ann arenotzero,thenthesystemwouldappearasfollows:

+ + + + =

+ + + =

+ + =

=

=

11 1 12 2 13 3 1 1

22 2 23 3 2 2

33 3 3 3

a x a x a x a x c

a x a x a x c

a x a x c

a x c

n n

n n

n n

nn n n

Forthiscase,thereisonlyonesolution.

3.7ā€‚ ā€‚Inverseā€‚MatrixGivenamatrixsystemofequationsofthegeneralform

AX=C

Wecansolvebyfront-multiplyingbothsidesoftheequationbythematrixinverse āˆ’A 1 :

- āˆ’āˆ’= = =A AX IX X A C1 1

MATLABā€™smethodofsolutionis

X=inv(A)*C (solvesby āˆ’1A )

or

X=A/C (solvesbyGausselimination)

Letusseewhatisinvolvedbydetermining āˆ’1A .

Page 112: Numerical and Analytical Methods with MATLAB for

96ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Let āˆ’B = A 1 .Then, =BA I.Wewilldemonstratefora3Ɨ3matrix:

=1 0 00 1 00 0 1

11 12 13

21 22 23

31 32 33

11 12 13

21 22 23

31 32 33

b b bb b bb b b

a a aa a aa a a

FirstrowofBA:

Element(1,1): + + = 111 11 12 21 13 31b a b a b a

Element(1,2): + + = 011 12 12 22 13 32b a b a b a

Element(1,3): + + = 011 13 12 23 13 33b a b a b a

Here, 11b , 12b , 13b aretheunknowns.Also,notethatthetransposematrix

=11 21 31

12 22 32

13 23 33

Aa a aa a aa a a

T

Let

=1

11

12

13

Bbbb

Then,

=100

1A BT

Solvefor 11b , 12b , 13b byGausselimination.SecondrowofBA:

Element(2,1): + + = 021 11 22 21 23 31b a b a b a

Element(2,2): + + = 121 12 22 22 23 32b a b a b a

Element(2,3): + + = 021 13 22 23 23 33b a b a b a

Page 113: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 97

Here, 21b , 22b , 23b aretheunknowns.

Let

=2

21

22

23

Bbbb

Then,

=010

2A BT

Solvefor 21b , 22b , 23b byGaussElimination.

ThirdrowofBA:

Element(3,1): + + = 031 11 32 21 33 31b a b a b a

Element(3,2): + + = 031 12 32 22 33 32b a b a b a

Element(3,3): + + = 131 13 32 23 33 33b a b a b a

Here, 31b , 32b , 33b aretheunknowns.

Let

=3

31

32

33

Bbbb

Then,

=001

3A BT

Solvefor 31b , 32b , 33b byGausselimination.

Analternative[1]tothemethoddescribedistoaugmentthecoefficientmatrixwith the identity matrix, then apply the Gauss-Jordan method, making the

Page 114: Numerical and Analytical Methods with MATLAB for

98ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

coefficientmatrixtheidentitymatrix.Theoriginalidentitymatrixthenbecomesāˆ’1A .Thestartingaugmentedmatrixfora3Ɨ3coefficientmatrixisasfollows:

1 0 00 1 00 0 1

11 12 13

21 22 23

31 32 33

a a aa a aa a a

Exampleā€‚3.6

This method is illustrated by the following example:

āˆ’ + = āˆ’āˆ’ + + = āˆ’

+ āˆ’ =

x x xx x xx x x

3 43 4 3 102 3 2 18

1 2 3

1 2 3

1 2 3

Writing the augmented matrix:

=āˆ’

āˆ’āˆ’

augA1 3 13 4 32 3 2

1 0 00 1 00 0 1

Multiply row 1 by āˆ’31

and subtract from row 2, giving

(āˆ’3+3Ɨ1), (4āˆ’3Ɨ3), (3+3Ɨ1), (0+3Ɨ1), (1+3Ɨ0), (0+3Ɨ0) = (0,āˆ’5, 6, 3, 1, 0)

Multiply row 1 by =21

2 and subtract from row 3, giving

(2āˆ’2Ɨ1), (3āˆ’2Ɨ(āˆ’3)), (āˆ’2āˆ’2Ɨ1), (0āˆ’2Ɨ1), (0āˆ’2Ɨ0), (1āˆ’2Ɨ0) = (0, 9, āˆ’4, āˆ’2, 0, 1)

=āˆ’āˆ’

āˆ’ āˆ’aug EquivA

1 3 10 5 60 9 4

1 0 03 1 02 0 1

,

Multiply row 2 by āˆ’95

and subtract from row 3, giving

+ Ɨ + Ɨ āˆ’ āˆ’ + Ɨ āˆ’ + Ɨ + Ɨ + Ɨ

=

095

0 , 995

( 5) , 495

6 , 295

3 , 095

1 , 195

0

0, 0,345

,175,95, 1

=

āˆ’āˆ’

aug EquivA

1 3 10 5 6

0 0345

1 0 03 1 0175

95

1,

Page 115: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 99

Multiply row 3 by 3034

and subtract from row 2, giving

āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ Ɨ āˆ’ Ɨ āˆ’ Ɨ

āˆ’ Ɨ = āˆ’ āˆ’ āˆ’

03034

0 , 53034

0 , 63034

345

, 33034

175

, 13034

95

,

03034

1 0, 5, 0, 0,2034

,3034

Multiply row 3 by 534

and subtract from row 1, giving

āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ Ɨ āˆ’ Ɨ āˆ’ Ɨ

āˆ’ Ɨ = āˆ’ āˆ’ āˆ’

1534

0 , 3534

0 , 1534

345

, 1534

175

, 0534

95

,

0534

1 (1, 3, 0,12,

934

,534

)

=

āˆ’

āˆ’

āˆ’ āˆ’

āˆ’ āˆ’aug EquivA

1 3 0

0 5 0

0 0345

12

934

534

02034

3034

175

95

1

,

Multiply row 2 by 35

and subtract from row 1, giving

āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ āˆ’ Ɨ āˆ’ Ɨ āˆ’ + Ɨ

āˆ’ + Ɨ =

135

0 , 335

( 5) , 035

0 ,12

35

0 ,934

35

2034

,

534

35

3034

1, 0, 0,12,334

,1334

= āˆ’ āˆ’ āˆ’aug EquivA

1 0 0

0 5 0

0 0345

12

334

1334

02034

3034

175

95

1

,

Divide row 2 by āˆ’5 and row 3 by 345

, giving

=aug EquivA

1 0 0

0 1 0

0 0 1

12

334

1334

0434

634

12

934

534

,

Page 116: Numerical and Analytical Methods with MATLAB for

100ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus,

=āˆ’A

12

334

1334

0434

634

12

934

534

1

It is left as a student exercise to show that =āˆ’AA I1 .

3.8ā€‚ ā€‚Theā€‚Eigenvalueā€‚ProblemOneapplicationoftheeigenvalueproblemisinresonantcircuits.ConsidertheLCnetworkshowninFigure 3.3.Usingtheconstituentrelationsforvoltageacrossan

inductor =v Ldidt

andcurrentthroughacapacitor =i Cdvdt

,thegoverning

differentialequationsdescribingthetwonodevoltages 1v and 2v are

= āˆ’ +

1 1212

1 11

1 12

d vdt LC

vLC

v (3.17)

= āˆ’ +

1 1 1222

1 21

1 2 2 22

d vdt LC

vLC L C

v (3.18)

Wewishtodeterminethemodesofoscillationsuchthatbothvoltagesoscillateatthesamefrequency.Toobtainsuchasolution,set

= Ļ‰1 1v K e j t (3.19)

= Ļ‰2 2v K e j t (3.20)

L1

L2C1 C2

v1 v2

Figureā€‚3.3ā€‚ LCā€‚circuit.

Page 117: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 101

whereK1andK2areconstantstobedetermined.SubstitutingEquations(3.19)and(3.20)intoEquations(3.17)and(3.18)gives

āˆ’Ļ‰ āˆ’ =

1 1 01 1

21

1 12LC

KLC

K (3.21)

āˆ’ + + āˆ’Ļ‰ =

1 1 1 01 2

11 2 2 2

22LC

KLC L C

K (3.22)

Equations (3.21)and (3.22)are twohomogeneous linearalgebraic equationsintwounknowns.Linearalgebratellsusthattheonlywayfortwohomogeneouslinearalgebraicequationsintwounknownstohaveanontrivialsolutionisforthedeterminantofthecoefficientmatrixtobezero.Thus,

āˆ’Ļ‰ āˆ’

āˆ’ + āˆ’Ļ‰

=

1 1

1 1 101 1

2

1 1

1 2 1 2 2 2

2

LC LC

LC LC L C

(3.23)

Now,letĻ‰ = Ī»2 andalsolet

=āˆ’

āˆ’ +

1 1

1 1 11 1 1 1

1 2 1 2 2 2

ALC LC

LC LC L C

RewritingEquation(3.23)intermsofĪ»andtheindividualelementsai j ofAgives

Ī» āˆ’ + Ī» + āˆ’ =( ) ( ) 0211 22 11 22 12 21a a a a a a (3.24)

ThesolutionofEquation(3.24)givestheeigenvalues Ī»1 and Ī»2 ofmatrixA,whichrepresentthesquareofthetwonaturalfrequenciesforthissystem.Theratiooftheamplitudesoftheoscillationofthetwovoltagescanbeobtainedbysubstitut-ingthevaluesofĪ»intoEquation(3.21)or(3.22),whichgives

( )= āˆ’ āˆ’ Ī» = āˆ’ Ī»12

111 1 12 1 1 1

KK

a a LC

forthefirstmode,and

= āˆ’ āˆ’ Ī» = āˆ’ Ī»( ) 12

111 2 12 1 1 2

KK

a a LC

forthesecondmode.

Page 118: Numerical and Analytical Methods with MATLAB for

102ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Theeigenvector V1 associatedwith Ī»1 is

āˆ’ āˆ’Ī»( )

1

1 11 1 12

KK a a

andtheeigenvector V2 associatedwith Ī»2 is

āˆ’ āˆ’Ī»( )

1

1 11 2 12

KK a a

Since 1K isarbitrary,wecanselect = 11K ,andthus

=

āˆ’ āˆ’Ī»1

( )111 1 12

V a a (3.25)

and

=

āˆ’ āˆ’Ī»1

( )211 2 12

V a a (3.26)

IfVisaneigenvectorofamatrixA correspondingtoaneigenvalueĪ»,thensoisbV,wherebisanonzeroconstant[1].

MATLABhasabuilt-infunctionnamedeigthatfindstheeigenvaluesofasquarematrix.MATLABā€™sdescriptionofthefunctionfollows:

E=EIG(X)isavectorcontainingtheeigenvaluesofasquarematrixX. [V,D]=EIG(X)producesadiagonalmatrixDofeigenvaluesanda

fullmatrixVwhosecolumnsarethecorrespondingeigenvectorssothatX*V=V*D.

Forthisproblem,thematrixArepresentsX.Thus,running

[V,D]=eig(A)

givestheeigenvectorsassociatedwith Ī»1 and Ī»2 .V(:,1)correspondsto Ī»1 ,andV(:,2)correspondsto Ī» .2

Page 119: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 103

Exampleā€‚3.7

Suppose in Figure 3.3 the following parameters were given:

= = = =L L C C15mH, 25mH, 1 F, 33 F1 2 1 2

We wish to create a MATLAB script that will determine

1. the eigenvalues of the system by Equations (3.21) and (3.22) by MATLABā€™s eig function.

2. the eigenfunctions by both Equations (3.21) and (3.22) and MATLABā€™s [V,D] output.

The program follows.

%Example_3_7.m:Eigenvaluesandeigenvectors.%L=eig(A)isavectorcontainingtheeigenvaluesofa%squarematrixA.%[M,D]=eig(A)producesadiagonalmatrixDof%eigenvaluesandafullmatrixMwhosecolumnsarethe%correspondingeigenvectorssuchthatA*L=M*D.%UnitsareinSIunits.clear;clc;L1=15e-3;L2=25e-3;%henriesC1=1e-6;C2=33e-6;%faradsA(1,1)=1/(L1*C1);A(1,2)=-1/(L1*C1);A(2,1)=-1/(L1*C2);A(2,2)=1/(L1*C2)+1/(L2*C2);%Solveforeigenvaluesandeigenvectorsusingderivation%inEqn3.25:%lambda^2-(A(1,1)+A(2,2))%*lambda+(A(1,1)*A(2,2)-A(1,2)*A(2,1))=0%Solveforlambdausingquadraticformula:b=-(A(1,1)+A(2,2));c=A(1,1)*A(2,2)-A(1,2)*A(2,1);lambda1=(-b+sqrt(b^2-4*c))/2;lambda2=(-b-sqrt(b^2-4*c))/2;%FromEqns3.26and3.27:eigenvector1=[1;-(A(1,1)-lambda1)/A(1,2)];eigenvector2=[1;-(A(1,1)-lambda2)/A(1,2)];fprintf('EigenvaluessolvedviaEquation3.25:');fprintf('lambda1=%.0flambda2=%.0f\n',lambda1,lambda2);fprintf('EigenvectorssolvedviaEquation3.26');fprintf('and3.27:\n');eigenvector1eigenvector2%SolveforeigenvaluesandeigenvectorsusingMATLAB's%eigfunction.Callingeigandreturningresulttoa%scalarwillgivetheeigenvalues.L=eig(A);fprintf('EigenvaluesviaMATLABeigfunction:');fprintf('L(1)=%.0fL(2)=%.0f\n',L(1),L(2));%Callingeigandreturningresulttotwovariableswill%givetheeigenvectorsandadiagonalmatrixofthe%eigenvalues.[VD]=eig(A);

Page 120: Numerical and Analytical Methods with MATLAB for

104ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

fprintf('EigenvectorsviaMATLABeigfunction:\n');V1=V(:,1)V2=V(:,2)D

The following results were generated by MATLAB:

EigenvaluessolvedviaEquation3.25:lambda1=68723140lambda2=1175850EigenvectorssolvedviaEquation3.26and3.27:eigenvector1=1.0000ā€“0.0308eigenvector2=1.00000.9824EigenvaluesviaMATLABeigfunction:L(1)=68723140L(2)=1175850EigenvectorsviaMATLABeigfunction:V1=0.9995-0.0308V2=0.71340.7008D=1.0e+007*6.8723 0 0 0.1176

Examining the results, it can be seen that lambda1=D(1,1) and lambda2=D(2,2). Also, eigenvector1 is a scalar multiple of V1 and eigenvec-tor2 is a scalar multiple of V2.

Exercises

Exercise.3.1

UseGausseliminationtosolvethefollowingsystemsofequations:

a.+ āˆ’ =āˆ’ + = āˆ’+ + =

2 3 204 3 14

5 21

1 2 3

1 2 3

1 2 3

x x xx x xx x x

b.+ + =

āˆ’ āˆ’ + =+ + =

4 8 82 3 2 14

3 4 30

1 2 3

1 2 3

1 2 3

x x xx x xx x x

c.

+ + āˆ’ =āˆ’ + āˆ’ =āˆ’ + āˆ’ =+ āˆ’ + = āˆ’

2 3 15 2 5 4 5

2 3 3 33 8 1

1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

x x x xx x x xx x x xx x x x

Page 121: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 105

ProjectsProject.3.1

ForthecircuitofFigure 3.1,solveforthefiveunknowncurrentsinsteadofthethreeunknownvoltages.SolvealgebraicallybyusingEquations(3.3),(3.4),and(3.5)andbyusingKirchhoffā€™svoltage law(KVL)towritetwoadditionalequations.KVLstatesthatthesumofthevoltagedropsaroundanyloopinthecircuitmustbezero.WriteKVLequationsforthesetwocircuitloops: ā†’ ā†’ ā†’ ā†’ ā†’1 1 2 4 5 2V R R R R V and ā†’ ā†’3 4 2R R R .Youshouldwindupwithasystemoffiveequationsandfiveunknowns.SolvewithMATLABusingtheinversematrixtechniqueandconfirmthatyouranswermatchestheresultsfoundinExample3.3.

Project.3.2

FigureP3.2showsaresistivecircuitknownasaā€œladdernetwork.ā€

1. UsingOhmā€™slawandKirchhoffā€™scurrentlaw,writeasystemofequationsforthesecond-orderandthird-ordernetworksofFiguresP3.2aandP3.2b.Inaddition,writetheequationsforafourth-orderladdernetwork.

2. Youshouldseeapatternemergingfromyoursolutionsinpart1.Usethispat-terntowritethematrixforaeighth-orderladdernetwork.SolveforallcircuitvoltagesusingMATLABforVref=5Vandthefollowingresistorvalues:

= =

= =

= =

= =

= =

= =

= =

= =

2200 , 2200

1200 , 6800

3900 , 2200

3300 , 5700

1800 , 5100

4700 , 3900

5700 , 6800

1200 , 2700

11 12

21 22

31 32

41 42

51 52

61 62

71 72

81 82

R R

R R

R R

R R

R R

R R

R R

R R

3. WriteaMATLABprogramtosolvethisproblemautomaticallyforarbitrarynandR0(asshowninFigureP3.2c)underthefollowingconditions:

= = = = = =

= = = = =

āˆ’

āˆ’2

0 11 21 31 ( 1) 1

0 12 22 32 ( 1)2

R R R R R R

R R R R R

n n

n

Findsolutionsforthefollowingtwocases:

n=16, R0=1000Ī©, Vref=10

n=24, R0=100Ī©, Vref=1

Page 122: Numerical and Analytical Methods with MATLAB for

106ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.3.3

One very important application of the eigenvalue problem is in the theory ofmechanicalvibrations.Considerthesystemoftwomasses(m1andm2)andthreesprings(withspringconstants 1k , 2k ,and 3k )showninFigureP3.3.

Thegoverningdifferentialequationsdescribingthemotionofthetwomassesare

= āˆ’ āˆ’( )1 1 2 2 1 1 1m x k x x k x (P3.3a)

=āˆ’ āˆ’ āˆ’( )2 2 2 2 1 3 2m x k x x k x (P3.3b)

UsingMATLABā€™seigfunction,determinethemodesofoscillationsuchthateachmassundergoesharmonicmotionatthesamefrequency.Usethefollowingvalues:

m1=m2=1500kg,k1=3250N/m,k2=3500N/m,k3=3000N/m

+ā€“

R11

R12

R21

R22Vref

v1 v2

(a)

+ā€“

R11

R12

R21

R22

R31

R32

v1 v2 v3

Vref

(b)

+ā€“

R11

R12

R21

R22

R31

R32

Rn1

Rn2

vnv3v1 v2

Vref

(c)

Figureā€‚P3.2ā€‚ (a)ā€‚Second-orderā€‚resistorā€‚ ladderā€‚network.ā€‚ (b)ā€‚Third-orderā€‚resistorā€‚ladderā€‚network.ā€‚(c)ā€‚Anā€‚nth-orderā€‚resistorā€‚ladderā€‚network.

Page 123: Numerical and Analytical Methods with MATLAB for

Matricesā€ƒ ā—¾ā€ƒ 107

Project.3.4

Suppose a manufacturer wishes to purchase a piece of equipment that costs$40,000.Heplanstoborrowthemoneyfromabankandpayofftheloanin10years in120 equalpayments.Theannual interest rate is 6%.Eachmonth, theinterestchargedwillbeontheunpaidbalanceoftheloan.Hewishestodeterminewhathismonthlypaymentwill be.Thisproblemcanbe solvedby a systemoflinearequations.

Letxjbetheamountinthejthpaymentthatgoestowardpayingofftheprin-cipal.Then,theequationdescribingthejthpaymentis

āˆ‘= = + āˆ’=

= āˆ’

th payment1

1

j M x P x Ij n

n

n j

(P3.4a)

where M=themonthlypayment P=theamountborrowed I=themonthlyinterestrate=one-twelfthoftheannualinterestrate

Thetotalnumberofunknownsis121(120xjvaluesandM).ApplyingEquation(P3.4a)toeachmonthgives120equations.The121stequation

is

āˆ‘==

=

1

120

P xnn

n

(P3.4b)

DevelopaMATLABprogramthatwill:

1. Ask the user to enter from the keyboard the amount of the loan P, theannualinterestrateI,andthetimeperiodY(inyears).

2. Setupthesystemoflinearequations,using ,An m asthecoefficientmatrixofthesystemoflinearequations.Thenrepresentstheequationnumber,andmrepresentsthecoefficientof xm inthatequation.Set =121x M .

m1 m2k1 k2 k3

x1 x2

m2m1k1x1 k3x2k2(x1 āˆ’ x2)

Figureā€‚P3.3ā€‚ Mechanicalā€‚vibrationā€‚problemā€‚withā€‚twoā€‚degreesā€‚ofā€‚freedom.

Page 124: Numerical and Analytical Methods with MATLAB for

108ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

3. SolvethesystemoflinearequationsinMATLAB. 4. Printoutatableconsistingoffourcolumns.Thefirstcolumnshouldbethe

monthnumber,thesecondcolumnthemonthlypayment,thethirdcolumntheamountofthemonthlypaymentthatgoestowardpayingofftheprincipal,andthefourthcolumntheinterestpaymentforthatmonth.

Project.3.5

TheticandtoccommandsinMATLABallowyoutomeasuretheexecutiontimeforagivenseriesofcommands.Theticandtocbehaveasastopwatch;ticstartsthestopwatch,andtocstopsitandprintstheelapsedtime.Anexam-pleusageis

tic; a=factorial(25); toc;

Runningthisscriptwillcompute25!andthenprintthetotalexecutiontime:

Elapsedtimeis0.005509seconds.

Ofcourse,thetimethatyouseewilldependonthespeedofyourcomputer.

1. Write a program in MATLAB that creates a random n Ɨ n matrix Awhereeachelementisarandomintegerbetween āˆ’ maxE and maxE .UseMATLABā€™s rand and round functions to accomplish this. To learnhowtousethesefunctions,typehelp randandhelp round intothe MATLAB Command window. Initially, assume that n = 100 and

= 100maxE . 2. Also,createa1ƗncolumnvectorCwithrandomelements,usingthesame

valuesfornand maxE above. 3. SolvetheequationAX.=.CforXintwoways:(a)byfinding āˆ’A 1 (withinv)

andmultiplyingitbyCand(b)byusingGausselimination(theMATLABā€˜\ā€™operator).Useticandtoctomeasuretheamountoftimeittakesforeachmethod.Dotheresultsmakesense?

4. Rerunyourprogram10timesandobtainanaverageexecutiontimeforthetwosolutionmethods.Alsofindaverageexecutiontimesforthefollowingval-uesofn:3,10,30,300,1000.Plottheexecutiontimesversusnonlog-logaxes.

Reference 1. Kreyszig,E.,Advanced Engineering Mathematics,8thed.,Wiley,NewYork,1999.

Page 125: Numerical and Analytical Methods with MATLAB for

109

Chapter 4

Rootsā€‚ofā€‚Algebraicā€‚andā€‚Transcendentalā€‚Equations

4.1ā€‚ ā€‚IntroductionIn the analysisof various engineeringproblems,weoftenare facedwithaneedtofindrootsofequationswhosesolutionisnoteasilyfoundanalytically.Typicalexamplesincludenthdegreepolynomialsandtranscendentalequationscontainingtrigonometricfunctions,exponentials,orlogarithms.Inthischapter,wereviewsev-eralmethodsforsolvingsuchequationsnumericallywithmathematicaltechniquesofvaryingcomplexityandaccuracy.Alsoincludedisasectiononthefzerofunc-tionofMATLABĀ®,whichmaybeusedtoobtaintherootsofequationsofthetypementionedpreviously.

4.2ā€‚ ā€‚Theā€‚Searchā€‚MethodTheequationwhoserootsaretobedeterminedshouldbeputintothefollowingstandardform: f(x)=0 (4.1)

Weproceedasfollows:First,asearchismadetoobtainintervalsinwhichrealrootslie.ThisisaccomplishedbysubdividingthexdomainintoNequalsubdivisions,giving

ā€¦ = ++ +, , , and1 2 3 1 1x x x x x x xN i i

Page 126: Numerical and Analytical Methods with MATLAB for

110ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Then,locatewheref(x)changessign(seeFigure 4.1).Thisoccurswhenthesignsoftwoconsecutivevaluesoff(x)aredifferent,thatis,

<+( ) ( ) 01f x f xi i

Thesignchangeusuallyindicatesthatarealroothasbeenpassed.However,itmayalsoindicateadiscontinuityinthefunction.(Example:tanxisdiscontinuousatx=Ļ€/2.)

Oncetheintervalsinwhichtherootsliehavebeenestablished,wecanusesev-eraldifferentmethodsforobtainingtherealroots.

4.3ā€‚ ā€‚Bisectionā€‚Method

Supposeithasbeenestablishedthatarootliesbetween xi and +1xi .Then,cuttheintervalinhalf(seeFigure 4.2),andthus

= ++ 2

12

x xx

i i

f (x)

xx1 x2

x3

f (x1)

f (x2)

f (x3)

xN+1xNxNā€“1x4

f (x4)

Figureā€‚4.1ā€‚ Selectingā€‚theā€‚intervalā€‚inā€‚whichā€‚aā€‚rootā€‚lies.ā€‚Inā€‚thisā€‚case,ā€‚f(x2)f(x3)ā€‚<ā€‚0,ā€‚andā€‚thusā€‚theā€‚rootā€‚liesā€‚betweenā€‚x2ā€‚andā€‚x3.

Page 127: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 111

Nowcompute +( ) ( )12

f x f xi i :

Case1:If <+( ) ( ) 012

f x f xi i ,thentherootliesbetween xi and + 12

xi .

Case2:If >+( ) ( ) 012

f x f xi i ,thentherootliesbetween + 12

xi and +1xi .

Case3:If =+( ) ( ) 012

f x f xi i ,then xi or + 12

xi isarealroot.

Forcases1and2,selecttheintervalcontainingtherootandrepeattheprocess.

Continue repeating theprocess, say r times, then =( )2

xx

f r ,whereĪ”x is theinitialsizeoftheintervalcontainingtherootbeforethebisectionprocessand( )x f isthesizeoftheintervalcontainingtherootafterr bisections.If ( )x f issufficientlysmall,thenaverygoodapproximationfortherootisanywherewithinthelastbisectedinterval,saythemidpointoftheinterval.

Example:For20bisections,

= ā‰ˆ Ɨ Ɨ āˆ’( )2

1.0 10206x

xxf

Programmethod:

=

=

= +

+

Set

12( )

1

x x

x x

x x x

A i

B i

C A B

f (x)

xxi+1xi xi+1/2

Figureā€‚4.2ā€‚ Selectingā€‚theā€‚intervalā€‚containingā€‚theā€‚rootā€‚inā€‚theā€‚bisectionā€‚method.

Page 128: Numerical and Analytical Methods with MATLAB for

112ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

If <( ) ( ) 0f x f xA C (indicatingthattherootliesbetweenxAandxC ),

=

= +

Then set

12( )

x x

x x x

B C

C A B

andrepeattheprocess.

Otherwise,if >( ) ( ) 0f x f xA C (indicatingthattherootliesbetween xB and xC),

=

= +

Then set

12( )

x x

x x x

A C

C A B

andrepeattheprocess.

If =( ) ( ) 0f x f xA C ,theneither xA or xC isaroot.

4.4ā€‚ ā€‚Newton-Raphsonā€‚MethodTheNewton-Raphsonmethodusesthetangenttothecurvef(x)=0toestimatetheroot.

Weneedtoobtainanexpressionfor ( )f x andmakeaninitialguessfortheroot,say 1x (seeFigure 4.3). ( )1f x givestheslopeofthetangenttothecurveat 1x .

f (x1)

x1x2

f (x)

x

f (x2)

Slope = f '(x1)

Figureā€‚4.3ā€‚ Predictingā€‚rootā€‚inā€‚theā€‚Newton-Raphsonā€‚method.

Page 129: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 113

Onthetangenttothecurve,

āˆ’āˆ’

=( ) ( ) ( )1 2

1 21

f x f xx x

f x (4.2)

Ournextguess(oriteration)fortherootisobtainedbysettingf(x2)=0andsolvingforx2,thatis,

= āˆ’

( )( )2 1

1

1x x

f xf x

(4.3)

Checkif < Īµ( )2f x ,whereĪµistheerrortolerance.Iftrue,thenquit. 2x istheroot,soprint 2x .Ifnottrue,thenset =1 2x x andrepeattheprocess.Continue repeating the process until < Īµ( )f xn , where n is the number of

iterations.Analternateconditionforconvergenceis

< Īµ

( )( )

1

1

f xf x

(4.4)

Usually,Īµ shouldbeavery smallnumber, suchas10ā€“4,but it canbeeitherlargerorsmallerdependingonhowcloseyouwishtogettotherealroot.Youcanalwaystesttheaccuracyoftheobtainedrootbysubstitutingtheobtainedrootintothefunctionf(x)toseeifitissufficientlyclosetozero.

TheNewton-Raphsonmethodiswidelyusedforitsrapidconvergence.However,therearecaseswhereconvergencewillnotoccur.Thiscanhappenif

a. ( )f x changessignneartheroot. b.Theinitialguessfortherootistoofarfromthetrueroot.

If we combine the Newton-Raphson method with the search method forobtainingasmallintervalinwhichtherealrootlies,convergenceisgenerallynotaproblem.

4.5ā€‚ ā€‚MATLABā€™sā€‚fzeroā€‚andā€‚rootsā€‚FunctionsMATLABhasbuilt-infunctionstodeterminetherealrootsofafunctionofonevariable, such as a transcendental equation or an nth-degree polynomial. Thefzerofunctionisusedfortranscendentalequations,andtherootsfunctionisusedforpolynomialequations.First,wediscussthefzerofunction.

Page 130: Numerical and Analytical Methods with MATLAB for

114ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

4.5.1 The fzero FunctionTogetstarted,clickintheCommandwindowandtypein

>>help fzero

Thisgivesseveraldifferentdescription,thefirsttwoarepresentedhere.

FZEROSingle-variablenonlinearzerofinding. X=FZERO(FUN,X0)triestofindazeroofthefunctionFUN

nearX0,ifX0isascalar.ItfirstfindsanintervalcontainingX0wherethefunctionvaluesoftheintervalendpointsdifferinsign,thensearchesthatintervalforazero.FUNisafunctionhandle.FUNacceptsrealscalarinputXandreturnsarealscalarfunctionvalueF,evaluatedatX.ThevalueXreturnedbyFZEROisnearapointwhereFUNchangessign(ifFUNiscontinuous),orNaNifthesearchfails.

X=FZERO(FUN,X0),whereX0isavectoroflength2,assumesX0isafiniteintervalwherethesignofFUN(X0(1))differsfromthesignofFUN(X0(2)).Anerroroccursifthisisnottrue.CallingFZEROwithafiniteintervalguaranteesFZEROwillreturnavaluenearapointwhereFUNchangessign.

Asdescribed,fzerohas severaldifferentusagesdependingonwhetheryouhaveasingleinitialguessofX0(i.e.,X0isascalar)orifyouhaveaknownintervalforthezero(i.e.,X0isavectoroflength2).Thefirstusageisappropriateifyouhavesomeideaofwheretherootlies.Thesecondusageismoreappropriatewhenthereismorethanoneroot,andallrootsneedtobeobtained.Thesecondusageshouldbeusedincombinationwiththesearchmethoddescribedpreviously.

Thefirstusageoffzerofunctionis

X=FZERO(FUN,X0)

FUNisfunction handleforthefunctiontobesolvedandcanbethenameofafunc-tionfile(withthe.mextension)orcanbeananonymousfunction(asdescribedinSection2.8).X0istheinitialguessfortheroot,andXisthesolutioncalculatedbyMATLAB.Thus,supposethenameofthefunctionfilewhoserootistobeobtainedismyfun.m,andourguessfortherootis3.0.Then,wewouldwrite

X=fzero('myfun',3.0)

Page 131: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 115

Analternativeandequivalentwaytorunthecommandis

X=fzero(@myfun,3.0)(nosinglequotationmarksneeded)

Ifnorootisfound,fzeroreturnsNaN(notanumber).Inthesecondusageoffzero,X0isavectoroflength2thatdefinesaninterval

overwhichFUNchangessign,thatis,thevalueofFUNatX0(1)isoppositeinsigntothevalueatX0(2).MATLABgivesanerrorifthisconditionisnotmet.

Insomeinstances,wewouldliketofindthezeroofafunctionoftwoargu-ments,sayXandP,wherePisaparameterandisfixed.Tosolvewithfzero,Pmustbedefinedinthecallingprogram.Forexample,supposemyfunisdefinedinanM-fileasafunctionoftwoarguments:

functionf=myfun(X,P) f=cos(P*X);

Thefzerostatementwouldneedtobeinvokedasfollows:

P=1000; root=fzero(@(X)myfun(X,P),X0)

whererootisthezerooffunctionmyfunwhenP=1000.NotethatPneedstobedefinedbeforethefzerofunctioniscalled.

An alternative to adding parameterP as an argument tomyfun is to useMATLABā€™sglobalstatementtodefineparameterP infunctionmyfunasanexternallyassignedvariable.Theglobalstatementneedstobeusedinboththecallingprogramandthefunctionmyfun.

Example:Callingprogram:

globalP;P=1000;X0=10.0;root=fzero(@myfun,X0);

-----------------------------------------------------

Thefilemyfun.m:

functionf=myfun(x)globalP;f=cos(P*x);

-----------------------------------------------------

Examplesofbothmethodsfollow.

Page 132: Numerical and Analytical Methods with MATLAB for

116ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚4.1:ā€‚ ā€‚Usingā€‚theā€‚fzero functionā€‚toā€‚Findā€‚theā€‚Firstā€‚Rootā€‚ofā€‚aā€‚Transcendentalā€‚Function

In Section 2.17, the governing equation for the voltage v(t) of a parallel RLC

circuit was derived. For the case when <RC LC1

212

, the system is under-

damped, and the solution for v(t) has the form

= āˆ’ āˆ’ + āˆ’v tRC

t ALC RC

t BLC RC

t( ) exp1

2cos

1 12

sin1 1

2

2 2

ā€‚ ā€‚ (4.5)

Determine the the smallest time when v(t) is zero, that is, find the first zero crossing of v(t) on the t axis. Assume the following parameters:

= = = = = āˆ’āˆ’ āˆ’R L C A B100 , 10 H, 10 F, 6.0V, 9.0V3 6

0 ā‰¤ t ā‰¤ 0.5 msec

%Example_4_1.m%Thisscriptdeterminestheinitialzerocrossingofthe%underdampedresponseofaparallelRLCcircuit.The%underdampedresponseis:%v(t)=exp(-t/(2RC))*(A*cos(sqrt(1/LC-(1/2RC)^2)t)%+B*sin(sqrt(1/LC-(1/2RC)^2)t))%Thecircuitcomponentvaluesandinitialconditions%are:%R=100ohms;L=1.0e-3henry;C=1.0e-6farads;%A=6.0volt,B=-9.0volt%Solveovertheinterval0<=t<=0.5e-3secclear;clc;R=100;L=1.0e-3;C=1.0e-6;A=6.0;B=-9;fprintf('Example4.1:Findfirstzerocrossingof');fprintf('underdampedRLCcircuit\n');tmin=0.0;tmax=0.5e-3;%splituptimespaninto100intervals:N=100;dt=(tmax-tmin)/N;%First,calculatetandv(t)ateachtimestepforn=1:N+1t(n)=tmin+(n-1)*dt;v(n)=func_RLC(t(n),A,B,R,L,C);fprintf('%10.4e%10.3f\nā€™,t(n),v(n));endplot(t,v),xlabel('t'),ylabel('v'),title('vvstforaRLCcircuit'),grid;%Next,usethesearchmethodtofindthefirsttimestep%wherethesignofv(t)changes.Whenfound,usefzero%tosolve.forn=1:N

Page 133: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 117

sign=v(n)*v(n+1);ifsign<=0.0root_interval(1)=t(n);root_interval(2)=t(n+1);%Solveforthezeroofthemulti-argument%functionfunc_RLC.mbyinvokingfunc_RLCasan%anonymousfunctionofonevariable.root=fzero(@(t)func_RLC(t,A,B,R,L,C),...root_interval);break;endendfprintf('\n\n');ifn<Nfprintf('Firstzerocrossingisatt=%10.4es\n',...root);elsefprintf('Norootsliewithin%g<=t<=%gs\n',...tmin,tmax);end%Checksolution.Puttingrootintofunc_RLCshould%producezero.v=func_RLC(root,A,B,R,L,C);fprintf('v=%8.6e\n',v);----------------------------------------------------------------------------%func_RLC.m%ThisfunctionworkswithExample_4_1.mfunctionv=func_RLC(t,A,B,R,L,C)arg1=1/(2*R*C);arg3=sqrt(1/(L*C)-1/(2*R*C)^2);%Equation(4.5):v=exp(-arg1*t)*(A*cos(arg3*t)+B*sin(arg3*t));----------------------------------------------------------------------------

PROGRAMā€‚RESULTS

Firstzerocrossingisatt=1.8831e-005s

We can modify Example 4.1 and use the global statement to bring the parameters into the function. To do this,

1. Add the following global statement immediately after the clear;clc; statements in the calling program and immediately after the function statement in the function program:

globalRLCAB;

2. Replace the function statement:

functionv=func_RLC(t,A,B,R,L,C)

Page 134: Numerical and Analytical Methods with MATLAB for

118ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

with

functionv=func_RLC(t)

3. Replace the following statement in the calling program:

v(n)=func_RLC(t(n),A,B,R,L,C);

with

v(n)=func_RLC(t(n));

4. Replace the following statement in the calling program:

root=fzero(@(t)func_RLC(t,A,B,R,L,C),root_inteval);

with

root=fzero('func_RLC',root_inteval);

Run each program and check to see if both programs give the same answer.

4.5.2 The roots FunctionMATLAB has a function to obtain the roots of a polynomial. The function isroots.Toobtaintheusageofthefunction,intheCommandWindowtype

>> help roots

Thisgives

ROOTSFindpolynomialroots. ROOTS(C)computestherootsofthepolynomialwhose

coefficientsaretheelementsofthevectorC.IfChasN+1components,thepolynomialisC(1)*X^N+...+C(N)*X+C(N+1).

Thus, to find the roots of the polynomial + + + + = 04 3 2Ax Bx Cx Dx E , runroots([ABCDE]).Therootsfunctionwillgivebothrealandimaginaryrootsofthepolynomial.

SomeadditionalusefulMATLABfunctionsare

poly(V) Finds the coefficients of the polynomial whose roots are V

real(X) Gives the real part of X

imag(X) Gives the imaginary part of X

Page 135: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 119

Exampleā€‚4.2:ā€‚ Usingā€‚rootsā€‚toā€‚Findā€‚theā€‚Zerosā€‚ofā€‚aā€‚Polynomial

%Example_4_2.m%Thisprogramdeterminestherootsofapolynomialusing%thebuiltinfunction'roots'.%Thefirstpolynomialis:f=x^3-4.7*x^2-35.1*x+85.176.%Therootsofthispolynomialareallreal.%Thesecondpolynomialis:f=x^3-9*x^2+23*x-65.The%rootsofthispolynomialarebothrealandcomplex.%Complexrootsmustbecomplexconjugates.%ToobtainmoreinfooncomplexnumbersinMATLAB,run%"helpcomplex"intheCommandWindow.clear;clc;%Definecoefficientsoffirstpolynomial(realroots)C(1)=1.0;C(2)=-4.7;C(3)=-35.1;C(4)=85.176;fprintf('Thefirstpolynomialcoefficientsare:\n');Cfprintf('Therootsare:\n');V=roots(C)fprintf('Therecalculatedcoefficientsofthe');fprintf('polynomialwhoserootsareVare:\n');C_recalc=poly(V)fprintf('\n\n');%Definecoefficientsofsecondpolynomial(realand%complexroots)D(1)=1.0;D(2)=-9.0;D(3)=23.0;D(4)=-65.0;fprintf('Thesecondpolynomialcoefficientsare:\n');Dfprintf('Therootsare:\n');W=roots(D)fprintf('Therealandimaginarypartsofthe');fprintf('rootsare:\n');re=real(W)im=imag(W)fprintf('Therecalculatedcoefficientsofthe');fprintf('polynomialwhoserootsareWare:\n');W_recalc=poly(W)

Projects

Project.4.1

Thecurrent-voltagerelationshipofasemiconductorPNdiodecanbewrittenasfollows:

= āˆ’1i I eD S

qkT

vD (P4.1a)

Page 136: Numerical and Analytical Methods with MATLAB for

120ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

whereiDandvDarethediodecurrentandvoltage,respectively,asdefinedinFigureP4.1;ISisaconstant(withunitsofamperes),whichisdeterminedbythesemicon-ductordopingconcentrationsandthedevicegeometry; = Ɨ āˆ’1.6 10 19q coulombistheunitelectriccharge; = Ɨ āˆ’1.38 10 23k joule/kelvinistheBoltzmannconstant;andTisabsolutetemperature(inkelvin).

Wewouldliketodeterminethecurrentandvoltagethroughthediodeforthiscircuit.UsingKirchhoffā€™svoltagelaw,weknowthatthesumofthevoltagedropsaroundthecircuitmustsumtozero:

āˆ’ āˆ’ = 0V v vin R D (P4.1b)

ApplyingOhmā€™slawforthecurrentthroughtheresistor =v i RR R andobserv-ing that the resistor current equals the diode current =i iR D , we can rewriteEquation(P4.1b)as

āˆ’ āˆ’ āˆ’ =1 0V I e R vin S

qkT

vD

D (P4.1c)

Let

= āˆ’ āˆ’ āˆ’( ) 1f v V I e R vD in S

qkT

vD

D

1. CreateaMATLABfunctionforf(vD)andplotfortheinterval Źŗ Źŗ0 0.8vD Vfor10mVsteps(80subdivisionsonthevDdomain).

2. Use the searchmethod to obtain a small intervalwithinwhich the root ofEquation(P4.1c)lies.

3. UseMATLABā€™sfzerofunctiontoobtainamoreaccuratevaluefortheroot.Usethefollowingparameters:

T =300K,IS=10ā€“14A,Vin = 5V,R =1000Ī©.

Project.4.2

WewishtodeterminetheDCtransfercharacteristicforthediodecircuitofFigureP4.1.WewillconsiderVinasaparameter,where 5V 12VVinŹŗ Źŗ instepsof1V.WewishtofindthevalueofvDforallvaluesofVin.

āˆ’

+

vR

iR

R

vD

+

āˆ’

iD

Vin

+

āˆ’

Figureā€‚P4.1ā€‚ Diode-resistorā€‚circuit.

Page 137: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 121

WriteaMATLABprogramthatwillfindtherootsof ( )f vd =0,where

= āˆ’ āˆ’ āˆ’( ) 1f v V I e R vD in S

qkT

vD

D

Yourprogramshould

1. UseaglobalstatementstobringvaluesofVinintothefunctionf(vD). 2. Take Źŗ Źŗ0.2 0.8vD Vwith60subdivisionsonthevDdomain. 3. Usethesearchmethodtofindasmallintervalinwhichtherootoff(vD)=0lies. 4. UsetheMATLABā€™sfzerofunctiontoobtainamoreaccuratevaluefortheroot. 5. ConstructatableconsistingofallvaluesofVinandthecorrespondingrootsof

f(vD)=0. 6. IfyoudidProject4.1,confirmthatyourprogramreturnsthesameresultasin

Project4.1when = 5Vin V.

Project.4.3

RepeatProject4.2,butthistimedonotuseglobalstatements.Instead,modifyyour ( )f vd functiontoincludetheargumentVin.Youwillalsoneedtomodifythefzerostatementappropriatelytouseafunctionwithmultiplearguments.

Project.4.4

Wewishtoconsiderthesettling time(describedinthefollowing)oftheinductorcurrentiLintheRLCcircuitofSection2.17andProject2.9.TheresistanceRcritthatmakesthecircuitcriticallydampedisgivenby

=

4R

LCcrit

For >R Rcrit ,thegoverningequationdescribingiLis

= āˆ’ āˆ’ + āˆ’exp 12

cos 1 12

sin 1 12

2 2

iRC

t ALC RC

t BLC RC

tL

ThecoefficientsAandBaredeterminedbytheinitialconditionsandthecom-ponentvalues.ThesolutionsforAandBare

=

=

āˆ’

Ɨ +

(0)

1

1 12

(0) (0)22

A i

B

LC RC

vL

iRC

L

L

Page 138: Numerical and Analytical Methods with MATLAB for

122ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thesettlingtimeofawaveformisthetimetsettlethatittakesthewaveform(iL)toreachwithinapercentageofsomespecifiedvalueandstaywithinthatrange(seeFigureP4.4).Forthisproblem,wewilltakethesettlingtimeforiL(t)tobewithinĀ±10%oftheinitialvalueiL(0)andstaywithinthatrange.WriteaMATLABprogramthatdeter-minesthesettlingtimeforthefollowingcircuitparameters:

= = = = = ā‰¤ ā‰¤4 , 1.0mH, 1.0 F, (0) 0.25A, (0) 6 V, 0 1000 sR R L C i v tcrit L

1. CreateaplotofiL(t)versust.Onthesameplot,createthelines0.1 (0)iL andāˆ’0.1 (0)iL .

2. Use the search method and MATLABā€™sfzero function to determine thesettlingtimeofiL(t).Hint:Use | ( )|i tL andthe 0.1 (0)iL linetofindthemaxi-mumroot,thusdeterminingthesettlingtime.

Project.4.5

An n-channel metal-oxide-semiconductor field-effect transistor (MOSFET) isshowninFigureP4.5a.TheMOSFEThasthreeterminals:gate, source,anddrain.(Actually,MOSFETsalsohaveafourthbulkterminal,whichwedonotdiscusshere.)InMOSFETcircuits,weareusuallyconcernedwiththedraincurrentiDas

0.05

ā€“0.05tsettle

t

iL

0.5

0

Figureā€‚P4.4ā€‚ Theā€‚settlingā€‚timeā€‚tsettleā€‚isā€‚definedā€‚asā€‚theā€‚timeā€‚itā€‚takesā€‚forā€‚iLā€‚toā€‚reachā€‚andā€‚stayā€‚withinā€‚someā€‚errorā€‚bandā€‚ofā€‚ itsā€‚finalā€‚value.ā€‚Thisā€‚problemā€‚usesā€‚anā€‚errorā€‚bandā€‚ofā€‚Ā±10%,ā€‚butā€‚errorā€‚bandsā€‚ofā€‚Ā±5%ā€‚orā€‚Ā±2%ā€‚areā€‚alsoā€‚common.

Page 139: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 123

iD

vGS+

āˆ’

vDS

+

āˆ’

Drainterminal

Sourceterminal

Gateterminal

(a)

Typical Output Characteristics

30Drain to Source Voltage VDS (V)

4020 5010

Dra

in C

urre

nt I D

(A)

0

2

4

6

8

10

VGS = 10 V TC = 25Ā°C

12

0

5

6

7

8

9

Pch = 100 W3

4

(b)

Figureā€‚P4.5ā€‚ (a)ā€‚Anā€‚n-channelā€‚MOSā€‚transistorā€‚andā€‚itsā€‚definedā€‚terminalā€‚param-eters.ā€‚(b)ā€‚Terminalā€‚characteristicsā€‚ofā€‚theā€‚2SK1056ā€‚powerā€‚MOSFET.ā€‚(Courtesyā€‚ofā€‚Renesasā€‚Electronicsā€‚Corporation.)

Page 140: Numerical and Analytical Methods with MATLAB for

124ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

afunctionoftheterminalvoltages.AcommonmathematicalmodelforthedraincurrentiDforann-channelMOSFET[1]isasfollows:

( )

( )

( )

=

ā‰¤

āˆ’ āˆ’ āˆ’ Ī» > ā‰¤ āˆ’

āˆ’ āˆ’ Ī» > > āˆ’

0 for

2 (1 ) for and ( )

1 for and ( )

2

2

i

v V

K v V v v v v V v v V

K v V v v V v v V

D

GS th

GS th DS DS DS GS th DS GS th

GS th DS GS th DS GS th

(P4.5a)

whereiDisdefinedinFigureP4.5a;vGSandvDS arethetransistorgate-to-sourceanddrain-to-sourcevoltages,respectively;Vthisthetransistorā€œthresholdvoltageā€;andKandĪ»areconstantsthataredependentonsilicondopinglevels,electronmobility,anddevicegeometry.FigureP4.5bshowsaplotoftypicaliDasafunctionofvDS(forvariousfixedvaluesofvGS)forthe2SK1056powerMOSFET.

1. CreateaMATLABfunctionid _ powerfetthattakestwoargumentsvds and vgs and computes the MOSFET current id as defined byEquation(P4.5a).Take

= = Ī» =0.2V, 0.2, 0.01V Kth

2. Plot iD as a function of vDS for Źŗ Źŗ0 50VvDS for values of=1,2, 3, 4, 5, 6, 7, and 8vGS V.Yourplotshouldlooksimilar(butnotidenti-

cal)totheoneinFigureP4.5b. 3. Becausethe2SK1056isratedforamaximumof100W,FigureP4.5bdoesnot

showvaluesofiDunderconditionswherethetotaldevicepower = ƗP i vD DS exceeds 100 W. Modify your function definition for id _ powerfet tocheckthedevicepowerandreturnNaN(notanumber)ifthepowerexceeds100W.RerunyourplotandconfirmthatitnowresemblesFigureP4.5b.

4. UsethefzerofunctiontofindthevalueofvGSwhenvDS=5VandiD=2A.Hint:Forthisproblem,youwillneedtosolveid _ powerfetasafunctionofvGSwith andv iDS D asfixedparameters.

Project.4.6

The simplest digital logic gate is the inverter (Figure P4.6a), which converts aBooleanā€œtrueā€intoā€œfalseā€andviceversa.Inelectronics,weoftenrepresentalogi-caltrueasahighvoltage(e.g.,+5V)andfalseasalowvoltage(e.g.,0V).Thus,fromanelectronicstandpoint,an inverter isacircuit thatacceptsa+5Vinputandoutputs0Vandacceptsa0Vinputandoutputs+5V.Asimplecircuitthatimplements these requirements is the resistor-MOSFETcircuitofFigureP4.6bandisaformofresistor-transistor logic(RTL).Inthiscase,ann-channelMOSFETisloadedwitha2-kĪ©resistor,VDDisthepowersupplyvoltage(typically5V),vinistheinput(andisequaltovGS),andvout istheoutput(andisequaltovDS).

UsingKirchhoffā€™svoltagelaw,wecanwriteanequationfortheoutputvoltageloop:

āˆ’ āˆ’ = 0V v vDD R DS (P4.6a)

Page 141: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 125

ByOhmā€™slaw,

=v i RR D (P4.6b)

SubstitutingEquation(P4.6b)intoEquation(P4.6a)gives

āˆ’ āˆ’ = 0V i R vDD D DS (P4.6c)

whereiDisdeterminedbyEquation(P4.5a).CreateaMATLABprogramthatusesMATLABā€™sfzerofunctiontodeter-

mine the roots of Equation (P4.6c). Use the following n-channel MOSFETparameters:VDD=5V,Vth=0.7V,K =0.0005,andĪ» =0.05.Take0ā‰¤vDSā‰¤5Vinstepsof0.1Vand0ā‰¤vGSā‰¤5Vinstepsof0.1V.Inactuality,arangeofvoltagesisconsideredavalidā€œlowā€oravalidā€œhighā€signal.FortheRTLinverterdescribedhere,assumethattherange0āˆ’1Vconstitutesavalidlowand4āˆ’5Vconstitutesavalidhigh.

1. Createatableofvoutversusvin(correspondingtovDSvs.vGS). 2. Plotvoutversusvin 3. Does thecircuitdescribedherebehave likean inverter; that is,doesahigh

inputproducealowoutputandviceversa? 4. Theinverternoise marginisdefinedastheamountofnoiseallowedonavalid

inputsuchthattheoutputremainsvalid.Forexample,ifvinraisedabovethelegalrangeforalow,sayto1.1V,doestheoutputremainavalidhigh?Findthehighestlowvinthatstillproducesavalidhighvout.Also,findthelowesthighvinthatstillproducesavalidlowvout.Printthesevaluestothescreen.

vin vout

(a)

R

iD

vGS+

āˆ’

vDS

+

āˆ’

vR+

āˆ’

vin

vout

VDD

(b)

Figureā€‚P4.6ā€‚ (a)ā€‚Logicā€‚inverter.ā€‚(b)ā€‚RTLā€‚inverterā€‚circuitā€‚usingā€‚anā€‚n-channelā€‚MOSā€‚transistor.

Page 142: Numerical and Analytical Methods with MATLAB for

126ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.4.7

TheRTLlogicfamilyofProject4.6wastypicallyusedinthe1950swhentransis-torswereexpensive(andpackagedindividually)andresistorswerecheap.Whenintegratedcircuitswereinventedinthe1960s,theoppositebecametrue:transis-torsbecameverycheap, and resistorsbecamecomparatively expensive (becausetheyareinefficienttoimplementonachip).

FigureP4.7ashowsacomplementary MOSFET(CMOS)inverter.Inthiscase,theresistorisreplacedbyap-channelMOSFET.Wecanmathematicallymodel

vGS,n+

āˆ’

vDS,n

+

āˆ’

vin vout

VDD

vGS,pāˆ’

+vDS,pāˆ’

+iD,p

iD,n

(a)

vDS,p

āˆ’

+

vGS,p

āˆ’

+

iD,p

Sourceterminal

Gateterminal

Drainterminal

(b)

Figureā€‚P4.7ā€‚ (a)ā€‚CMOSā€‚inverterā€‚circuit.ā€‚(b)ā€‚Aā€‚p-channelā€‚MOSā€‚transistorā€‚andā€‚itsā€‚definedā€‚terminalā€‚parameters.

Page 143: Numerical and Analytical Methods with MATLAB for

Roots of Algebraic and Transcendental Equationsā€ƒ ā—¾ā€ƒ 127

thep-channelMOSFETsimilarlytothen-channelMOSFETofProject4.5;thatis,thep-channeldraincurrentiD,Pisgivenby

=

ā‰„

āˆ’ āˆ’ āˆ’ āˆ’ Ī» < ā‰„ āˆ’

āˆ’ āˆ’ āˆ’ Ī» < < āˆ’

0 for

2( ) (1 ) for and ( )

( ) (1 ) for and ( )

,

, ,

, , , ,2

, , , , , ,

, ,2

, , , , , ,

i

v V

K v V v v v v V v v V

K v V v v V v v V

D p

GS p th p

p GS p th p DS p DS p p DS p GS p th p DS p GS p th p

p GS p th p p DS p GS p th p DS p GS p th p

(P4.7a)

where ,vGS p , ,vDS p ,and ,iD p areasdefinedinFigureP4.7b.Notethatthep-channelmodelmentionedissimilartothen-channelmodelofEquation(P4.5a)exceptforsomesignchanges.Inaddition,foragivenintegratedcircuittechnology,thevaluesofVth,K,andĪ»willbedifferentforp-versusn-channelMOSFETs(andthuswillbedenotedwithpandnsubscripts,respectively).Kirchhoffā€™svoltagelawisusedtorelatethevoltagesintheoutputsideofthecircuit:

=,v vDS n out (P4.7b)

= āˆ’,v v VDS p out DD (P4.7c)

Similarly,ontheinputside:

=,v vGS n in (P4.7d)

= āˆ’,v v VGS p in DD (P4.7e)

WecanalsoapplyKirchhoffā€™scurrentlawattheoutputnode:

+ = 0, ,i iD n D p (P4.7f)

wherethen-channelsourcecurrent ,iD n isdefinedas

( )=

ā‰¤

āˆ’ āˆ’ + Ī» > ā‰¤ āˆ’

āˆ’ + Ī» > > āˆ’

0 for

2( ) (1 ) for and ( )

( ) (1 ) for and ( )

,

, ,

, , , ,2

, , , , , ,

, ,2

, , , , ,

i

v V

K v V v v v v V v v V

K v V v v V v v V

D n

GS n th n

n GS n th n DS n DS n n DS n GS n th n DS n GS n th n

n GS n th n n DS n GS n th n DS n GS n th n

(P4.7g)

1. CreateaMATLABprogramusingthefzero function toobtaintherootsofEquation(P4.7f)byapplyingequations(P4.7a)and(P4.7g).TakeVDD=5V,Vth,n=0.7V,Vth,p=ā€“0.8V,Kn=0.0005,Kp=0.00015,Ī»n=0.05,andĪ»p=0.1.AssumeŹŗ Źŗ0 5vout Vinstepsof0.1Vand Źŗ Źŗ0 5vin Vinstepsof0.1V.

Page 144: Numerical and Analytical Methods with MATLAB for

128ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

2. Createatableofvoutversusvin. 3. Plotvoutversusvin. 4. Doesthecircuitdescribedherebehavelikeaninverter?Thatis,doesahigh

inputproducealowoutputandviceversa?

Reference 1. A.S. Sedra and K.C. Smith, Microelectronic Circuits, 3rd ed., Saunders College,

Philadelphia,1989.

Page 145: Numerical and Analytical Methods with MATLAB for

129

Chapter 5

Numericalā€‚Integration

5.1ā€‚ ā€‚IntroductionInthischapter,wederiveSimpsonā€™sruleforapproximatingthesolutionofdefiniteintegrals.Wethendemonstrateusageofthebuilt-inMATLABĀ®functionsquadanddblquadforevaluatingdefiniteintegrals.Finally,weapplythesefunctionstosolvesomecommonproblemsinelectromagneticfieldtheory.

5.2ā€‚ ā€‚Numericalā€‚Integrationā€‚andā€‚Simpsonā€™sā€‚RuleWewanttoevaluatetheintegralIwhere

āˆ«= ( )I f x dxA

B

(5.1)

ThestepsforcalculatingInumericallyareasfollows:

ā—¾ Subdividethexaxisfromx =Atox =BintoNsubdivisions,whereNisaneveninteger.

ā—¾ Simpsonā€™sruleconsistsofconnectinggroupsofthreepointsonthecurvef(x)bysecond-degreepolynomials(parabolas)andsummingtheareasundertheparabolastoobtaintheapproximateareaunderthecurve(seeFigure 5.1).

Page 146: Numerical and Analytical Methods with MATLAB for

130ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Weproceedbyfirstexpandingf(x)inaTaylorseriesaboutxiusingthreeterms,thatis,

= āˆ’ + āˆ’ +( ) ( ) ( )2f x a x x b x x ci i (5.2)

wherea,b,andcareconstantstobedetermined.Then,theareaundertwoadjacentstripsA2stripsiscomputedbyintegratingf(x)

betweenxiā€“1andxi+1:

āˆ« āˆ«= = āˆ’ + āˆ’ +

āˆ’

+

āˆ’

+

( ) [ ( ) ( ) ]2 strips2

1

1

A f x dx a x x b x x c dxx

x

i i

x x

x x

i

i

i

i

(5.3)

Let Ī¾ = āˆ’x xiThen,

dĪ¾ =dx

When = āˆ’ ,x x xi Ī¾ =āˆ’Ī”x,andwhen = + ,x x xi Ī¾ =Ī”x.MakingthesesubstitutionsintoEquation(5.3)gives

( )

3 2

3( )

3( )

2( )

2( ) ( ) ( )

2 strips

2

3 2

3 3 2 2

1

1

A f x dx

a b c d

a bc

ax

ax

bx

bx c x c x

x

x

x

x

x

x

i

i

āˆ«

āˆ«

=

= Ī¾ + Ī¾ + Ī¾

=Ī¾

+Ī¾

+ Ī¾

= āˆ’ āˆ’ + āˆ’ āˆ’ + āˆ’ āˆ’

āˆ’

āˆ’

āˆ’

+

x1

f1

xi

fi

xiāˆ’1

fiāˆ’1

xi+1

fi+1

xN+1

fN+1

āˆ† x āˆ† x

x

. . . . . .

. . .

. . .. . .

. . .

A2strips

f (x)

Figureā€‚5.1ā€‚ Arbitraryā€‚threeā€‚pointsā€‚onā€‚theā€‚curveā€‚f(x).

Page 147: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 131

Thus,

= +23( ) 22 strips

3Aa

x c x

Now,define = ( )f f xi i .SolvingEquation(5.2)forfi, +1fi ,and āˆ’1fi gives

= =

= = + +

= = āˆ’ + āˆ’ +

+ +

āˆ’ āˆ’

( )

( ) ( )

( ) ( ) ( )

1 12

1 12

f x f c

f x f a x b x c

f x f a x b x c

i i

i i

i i

Addingthelasttwoequationsgives + = ++ āˆ’ 2 21 12f f a x ci i .

Solvingforagives

= + āˆ’+ āˆ’

12

[ 2 ]2 1 1ax

f f fi i i

Then,

= Ɨ + āˆ’ + = + āˆ’ ++ āˆ’ + āˆ’23

12

[ 2 ]( ) 23[ 2 6 ]2 strips 2 1 1

31 1A

xf f f x f x

xf f f fi i i i i i i i

or

= + +āˆ’ +3

[ 4 ]2 strips 1 1Ax

f f fi i i (5.4)

ToobtainanapproximationfortheintegralI,weneedtosumallthetwo-stripareasunderthecurvefromx =Atox =B(seeFigure 5.2),thatis,

= + +

= + +

= + +

= + +āˆ’ +

3[ 4 ]

3[ 4 ]

3[ 4 ]

3[ 4 ]

1 1 2 3

2 3 4 5

3 5 6 7

/2 1 1

Ax

f f f

Ax

f f f

Ax

f f f

Ax

f f fN N N N

Page 148: Numerical and Analytical Methods with MATLAB for

132ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus,

āˆ«= = + + + + + + +=

=

+

+

( )3[ 4 2 4 2 4 ]1 2 3 4 5 1

1

1

I f x dxx

f f f f f f fx A

x B

N N

N

(5.5)

ThisisSimpsonā€™sruleforintegration.

Exampleā€‚5.1

Solve by Simpsonā€™s rule:

āˆ«= + āˆ’ +I x x x dx( 3.2 3.4 20.2)3 2

0

10

%Example_5_1.m%ThisprogramcalculatesanintegralbySimpson'sRule%Theintegrandis:x^3+3.2*x^2-3.4*x+20.2%Thelimitsofintegrationarefrom0-10.clear;clc;A=0;B=10;N=100;dx=(B-A)/N;%Computevaluesofxandfateachpoint:x=A:dx:B;f=x.^3+3.2*x.^2-3.4*x+20.2;%Usetwoseparateloopstosumuptheevenandoddterms%ofSimpson'sRule.Also,excludeendpointsintheloop.sum_even=0.0;fori=2:2:Nsum_even=sum_even+f(i);end

f3f2f1

fN

x1 x2 x3 xN

A1 A2A3

f (x)

x. . .

. . .

f6f5f4 f7. . .

x7x6x5x4 xN+1xNāˆ’1

fNāˆ’1

fN+1

AN/2

Figureā€‚5.2ā€‚ Integrationā€‚areasā€‚forā€‚Simpsonā€™sā€‚rule.

Page 149: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 133

sum_odd=0.0;fori=3:2:N-1sum_odd=sum_odd+f(i);end%CalculateintegralasperEquation5.5I=dx/3*(f(1)+4*sum_even+2*sum_odd+f(N+1));%Displayresultsfprintf('Integrand:x^3+3.2*x^2-3.4*x+20.2\n');fprintf('Integrationlimits:%.1fto%.1f\n',A,B);fprintf('I=%10.4f\n',I);

--------------------------------------------------------------------------

PROGRAMā€‚RESULTSIntegrand:x^3+3.2*x^2-3.4*x+20.2Integrationlimits:0.0to10.0I=3598.6667

5.3ā€‚ ā€‚Improperā€‚IntegralsAnintegralisimproperiftheintegrandapproachesinfinityateitheroftheend-points.Inmanycases,theintegrationwillstillresultinafinitesolution.

Exampleā€‚5.2

āˆ«=

+I

xx

dxlog(1 )

0

1

(5.6)

This integral is improper since both the numerator and denominator are zero at the lower limit (x = 0). The exact value of I can be obtained by residue

theory in complex variables and in this case evaluates to =Ļ€

=I12

0.822467.2

Let

āˆ«=

+= +I

xx

dx I Ilog(1 )

0

1

1 2

where

āˆ«=

+

Īµ

Ix

xdx

log(1 )1

1

and

āˆ«=

+Īµ

Ix

xdx

log(1 )2

0

Page 150: Numerical and Analytical Methods with MATLAB for

134ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

where Īµ << 1. To evaluate I2, expand log(1 + x) in a Taylor series about x = 0, giving

+ = āˆ’ + āˆ’ + āˆ’ +x x x x x xlog(1 )

12

13

14

15

2 3 4 5

then

+= āˆ’ + āˆ’ + āˆ’ +

xx

x x x xlog(1 )

112

13

14

15

2 3 4

āˆ«= āˆ’ + āˆ’ + āˆ’ + āˆ’ +

Īµ

I x x x x x x dx112

13

14

15

16

17

22 3 4 5 6

0

= Īµ āˆ’ Īµ + Īµ āˆ’ Īµ + Īµ āˆ’ Īµ + Īµ āˆ’ +I

14

19

116

125

136

149

22 3 4 5 6 7 (5.7)

Evaluate I1 by Simpsonā€™s rule and evaluate I2 by Equation (5.7). The fol-lowing program illustrates the method:

%Example_5_2.m%Thisprogramevaluatestheimproperintegral:%log(1+x)/xThelimitsofintegrationarefrom0to1.%Theintegrandisundefined(0/0)atx=0.Thus,the%integralisbrokenupinto2parts:I1andI2.%I1isevaluatedfromepsilonto1.%I2isexpandedinaTaylorSeriesandevaluatedfrom0%toepsilon.clear;clc;epsilon=0.0001;A=0;B=1;N=100;dx=(B-epsilon)/N;%EvaluateI1.First,evaluatelog(1+x)/xforeachvalue%ofxovertheinterval[epsilon,1].x=epsilon:dx:B;f=log(1+x)./x;%Next,calculatetheevenandoddtermsforSimpson's%Rule.sumeven=0.0;fori=2:2:Nsumeven=sumeven+f(i);endsumodd=0.0;fori=3:2:N-1sumodd=sumodd+f(i);end%AsperEquation(5.5),I1istheweightedsumofthe%evenandoddterms,plustheendterms.

Page 151: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 135

I1=dx/3*(f(1)+4*sumeven+2*sumodd+f(N+1));fprintf('Integrand=log(1+x)/x\n');fprintf('I1limitsofintegrationare');fprintf('from%.4fto%.4f\n',epsilon,B);fprintf('I2limitsofintegrationare');fprintf('from%.4fto%.4f\n',A,epsilon);fprintf('I1=%15.6f\n',I1);%CalculateI2viafirst4termsofTaylorseries%expansion.I2=epsilon-1/4*epsilon^2+1/9*epsilon^3...-1/16*epsilon^4;fprintf('I2=%15.6f\n',I2);I=I1+I2;fprintf('I=I1+I2=%10.6f\n',I);I_exact=0.822467;fprintf('I_exact=%10.6f\n',I_exact);

--------------------------------------------------------------------------

PROGRAMā€‚RESULTSIntegrand=log(1+x)/xI1limitsofintegrationarefrom0.0001to1.0000I2limitsofintegrationarefrom0.0000to0.0001I1= 0.822367I2= 0.000100I=I1+I2=0.822467I_exact= 0.822467

As we see, the method works quite well.

5.4ā€‚ ā€‚MATLABā€™sā€‚quadā€‚FunctionThe MATLAB function for evaluating an integral is quad. A description ofthefunctioncanbeobtainedbytypinghelp quadintheCommandwindow(excerptedinthefollowing):

Q=QUAD(FUN,A,B)triestoapproximatetheintegralofscalar-valuedfunctionFUNfromAtoBtowithinanerrorof1.e-6usingrecursiveadaptiveSimpsonquadrature.FUNisafunctionhandle.ThefunctionY=FUN(X)shouldacceptavectorargumentXandreturnavectorresultY,theintegrandevaluatedateachelementofX.

Q=QUAD(FUN,A,B,TOL)usesanabsoluteerrortoleranceofTOLinsteadofthedefault,whichis1.e-6.LargervaluesofTOLresultinfewerfunctionevaluationsandfastercomputation,butlessaccurateresults.TheQUADfunctioninMATLAB5.3usedalessreliablealgorithmandadefaulttoleranceof1.e-3.

Page 152: Numerical and Analytical Methods with MATLAB for

136ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus, the quad function takes as arguments a function handleFUN thatdefines the integrand in a .m file and the limits of integration. Alternatively. iftheintegrandisnotverylargeandcanbeexpressedinasingleline,thenyoucandefinetheintegrandwithinyourscriptwithananonymousoraninlinefunction(seeExamples5.4and5.5).Iftheintegrandinvolvesverysmallnumbersorverylargenumbers,youmightwishtochangethedefaulttolerancebyaddingathirdargumenttoquad(asshowninthesecondusagedescription).Thequadfunctionisabletoevaluatecertainimproperintegrals(seeExercises5.2d,5.2e,and5.2f).

Exampleā€‚5.3

We now repeat Example 5.1, but this time we use MATLABā€™s quad function to do the integration. The integral I in Example 5.1 is

āˆ«= + āˆ’ +I x x x dx( 3.2 3.4 20.2)3 2

0

10

The program follows:

%Example_5_3.m%Thisprogramevaluatestheintegralofthefunction%'f1'betweenAandBbyMATLAB'squadfunction.Since%thefunction'f1'isjustasingleline,wecanusethe%anonymousformofthefunction.clear;clc;f1=@(x)(x.^3+3.2*x.^2-3.4*x+20.2);A=0.0;B=10.0;I=quad(f1,A,B);fprintf('Integrationoff1over[%.0f,%.0f]',A,B);fprintf('byMATLAB''squadfunction:\n');fprintf('f1=x^3+3.2*x^2-3.4*x+20.2\n');fprintf('integral=%10.4f\n',I);

--------------------------------------------------------------------------

PROGRAMā€‚RESULTSIntegrationoff1over[0,10]byMATLAB'squadfunction:f1=x^3+3.2*x^2-3.4*x+20.2integral=3598.6667

We see that the results are the same as those obtained in Example 5.1.

Exampleā€‚5.4

āˆ« + +

tt t

dtEvaluate:13

0

1

Page 153: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 137

%Example_5_4.m%Thisprogramevaluatestheintegraloffunction"f2"%betweenAandBbyMATLAB'squadfunction.The%integrandcanbeexpressedinasinglelineandthuswe%canusetheanonymousformofthefunction.clear;clc;A=0.0;B=1.0;f2=@(t)t./(t.^3+t+1.0);I2=quad(f2,A,B);fprintf('Integrationoff2over[%.0f,%.0f]',A,B);fprintf('byMATLAB''squadfunction:\n');fprintf('f2=t/(t^3+t+1)\n');fprintf('integral=%f\n',I2);

--------------------------------------------------------------------------

PROGRAMā€‚RESULTSIntegrationoff2over[0,1]byMATLAB'squadfunction:f2=t/(t^3+t+1)integral=0.260068

Let us repeat Example 5.2, in which we evaluated the improper integral described by Equation (5.6), but this time we evaluate the integral using MATLABā€™s quad function with limits from 0 to 1. Recall that the function log(1 + x)/x is undefined at x = 0. In addition, we use the inline method for specifying the function.

Exampleā€‚5.5

%Example_5_5.m%Thisprogramevaluatestheimproperintegrallog(1+x)/x%withlimitsfrom0to1usingquad.clear;clc;A=0;B=1;fprintf('Thisprogramusesthequadfunctionto\n');fprintf('evaluatetheintegraloflog(1+x)/xfrom');fprintf('%.0fto%.0f.\n',A,B);I=quad(inline('log(1+x)./x'),A,B);fprintf('I=%10.6f\n',I);--------------------------------------------------------------------------

This program produces the following result:

Thisprogramusesthequadfunctiontoevaluatetheintegraloflog(1+x)/xfrom0to1.I=0.822467

This answer is the same as shown in Example 5.2.

5.5ā€‚ ā€‚Theā€‚Electricā€‚FieldElectricfieldproblemsofteninvolveintegration,andbeforeweproceed,wereviewsomebasicconceptsaboutelectromagneticfields.

Webeginby assuming that apoint chargeofQ coulombs is located at thecoordinates ( , , )x y zp p p infreespace.WedenotethelocationofQbythevector rp

Page 154: Numerical and Analytical Methods with MATLAB for

138ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

(seeFigure 5.3).TheelectricfieldE attheobservationpoint ro (correspondingto

thecoordinates ( , , )x y zo o o )duetothechargeat rp isdefinedas

=

Ļ€Īµ4Ė†2E

re

Q

or (5.8)

where Īµo isthepermittivityoffreespace( Ɨ āˆ’8.85 10 12 farad/m), r isthevector

fromthepointchargetothepointofmeasurement, er istheunitvectorinthe r

direction,andtheresultingE isinvolts/meter.FromFigure 5.3,wecanobserve

thevectorsum = +r r ro p ,andthus

= āˆ’r r ro p .Then,Equation(5.8)becomes

=

Ļ€Īµ āˆ’

āˆ’

āˆ’42E

r r

r rr r

Q

o o p

o p

o p (5.9)

wherewehaveappliedthedefinitionoftheunitvector=errr .

Wenowbreakdown ro and rp intotheirx,y,andzcomponentssothatwecanexpress them vectorially in Cartesian coordinates as

= + +Ė† Ė† Ė†r e e ex y zo o x o y o z and

= + +Ė† Ė† Ė†r e e ex y zp p x p y p z ,where e x , e y,and ez areunitvectorsinthex,y,andzdirections,respectively.Then,

āˆ’ = āˆ’ + āˆ’ + āˆ’( ) ( ) ( )2 2 2r r x x y y z zo p o p o p o p ,andEquation(5.8)becomes

( )=

Ļ€Īµ

āˆ’ + āˆ’ + āˆ’

āˆ’ + āˆ’ + āˆ’4( ) ( ) ( )

( ) ( ) ( )2 2 232

Ee e eQ x x y y z z

x x y y z zo

o p x o p y o p z

o p o p o p

(5.10)

Thus,Equation (5.10)gives theelectricfieldat the location ( , , )x y zo o o due toapointchargeofmagnitudeQlocatedat ( , , )x y zp p p .

y

x

z

+

Point charge Qlocated at rp

Measurementlocation ro

r

ro

E

rp

Figureā€‚5.3ā€‚ Theā€‚electricā€‚fieldā€‚E ā€‚atā€‚observationā€‚pointā€‚

ro ā€‚dueā€‚toā€‚aā€‚pointā€‚chargeā€‚

locatedā€‚atā€‚rp .

Page 155: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 139

Wenowwishtocalculatetheelectricfieldduetoalineofpointchargesextend-ingalongthez-axisfromāˆ’āˆžtoāˆž(seeFigure 5.4).Weshallassumethatthechargesareevenlyspacedalongthelinewithalinear charge density representedbythesym-bolĪ»withunitscoulomb/meter.WecanrewriteEquation(5.10)indifferentialformtoobtain an expression for

Ed in termsof thedifferentialquantity = Ī»dQ dz p,

where dz p representsaninfinitesimalsegmentofthelinechargeinthezdirection:

( )=Ī»

Ļ€Īµ

āˆ’ + āˆ’ + āˆ’

āˆ’ + āˆ’ + āˆ’4( ) ( ) ( )

( ) ( ) ( )2 2 232

Ee e e

ddz x x y y z z

x x y y z z

p

o

o p x o p y o p z

o p o p o p

(5.11)

SeparatingtheindividualdirectionalcomponentsofEquation(5.11)andinte-gratingfromāˆ’āˆžto+āˆž gives

āˆ« ( )

=Ī»

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edz x x

x x y y z zx

p

o

o p

o p o p o p

(5.12)

āˆ« ( )

=Ī»

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edz y y

x x y y z zy

p

o

o p

o p o p o p

(5.13)

āˆ« ( )

=Ī»

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edz z z

x x y y z zz

p

o

o p

o p o p o p

(5.14)

MeasurementlocationLine charge of density

Ī» coul/m along Ā±z axis

Differential linecharge element Ī»dz

x

z

r

ro

rp

dE

Figureā€‚5.4ā€‚ Theā€‚differentialā€‚electricā€‚fieldā€‚

dEr ā€‚atā€‚observationā€‚pointā€‚ro ā€‚dueā€‚toā€‚aā€‚

differentialā€‚lineā€‚chargeā€‚elementā€‚Ī»dzā€‚locatedā€‚alongā€‚theā€‚zā€‚axis.

Page 156: Numerical and Analytical Methods with MATLAB for

140ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚5.6

Given a line charge located along the z axis with density Ī» = Ɨ āˆ’2 10 coul/m,9 calculate the electric field at the location =x y zo o o( , , ) (0.005, 0, 0).

%Example_5_6.m%Thisprogramusesthequadfunctiontoevaluatethe%integralsofequations(5.12),(5.13)and(5.14)to%findEx,EyandEz.Thefollowingparametersareused%intheintegration:lambda=2e-9coul/m,xo=5e-3,yo=0%andzo=0.%Assumethat10isagoodapproximationforinfinity.clc;clear;globalxoyozolambdaepsilon0;lambda=2e-9;epsilon0=8.85e-12;xo=5e-3;yo=0;zo=0;Ex=quad(@linecharge_Ex,-10,10);Ey=quad(@linecharge_Ey,-10,10);Ez=quad(@linecharge_Ez,-10,10);fprintf('E-fieldduetoalinecharge');fprintf('at[%5.3f,%5.3f,%5.3f]:\n',xo,yo,zo);fprintf('[Ex,Ey,Ez]=[%10.4e,%5.2f,%5.2f]V/m\n',...Ex,Ey,Ez);

--------------------------------------------------------------------

%linecharge_Ex.m:FunctiontocalculateExat(xo,yo,zo)%foralinechargeonthezaxisfunctionEx=linecharge_Ex(zp)globalxoyozolambdaepsilon0;Ex=lambda/(4*pi*epsilon0)*xo..../(xo.^2+yo.^2+(zo-zp).^2).^1.5;

------------------------------------------------------------------------

%linecharge_Ey.m:FunctiontocalculateEyat(xo,yo,zo)%foralinechargeonthezaxisfunctionEy=linecharge_Ey(zp)globalxoyozolambdaepsilon0;Ey=lambda/(4*pi*epsilon0)*yo..../(xo.^2+yo.^2+(zo-zp).^2).^1.5;

------------------------------------------------------------------------

%linecharge_Ez.m:FunctiontocalculateEzat(xo,yo,zo)%foralinechargeonthezaxisfunctionEz=linecharge_Ez(zp)globalxoyozolambdaepsilon0;Ez=lambda/(4*pi*epsilon0)*(zo-zp)..../(xo.^2+yo.^2+(zo-zp).^2).^1.5;

------------------------------------------------------------------------

PROGRAMā€‚RESULTSE-fieldduetoalinechargeat[0.005,0.000,0.000]:[Ex,Ey,Ez]=[7.1934e+003,0.00,0.00]V/m

Page 157: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 141

5.6ā€‚ ā€‚Theā€‚quiverā€‚PlotAquiverplotisatwo-dimensionalplotofavectorfunctionthatusessmallarrowstorepresentthelocalvectormagnitudeanddirection.Forexample,aquiverplotcanbeusedtoshowanelectricormagneticfield(i.e.,theoutputfromthevectorfunc-tion)asafunctionofposition(i.e.,theinputtothevectorfunction).TheMATLABcommandisquiver(X,Y,U,V).Toseethesyntax,runhelp quiver intheCommandwindow:

QUIVER(X,Y,U,V)plotsvelocityvectorsasarrowswithcomponents(u,v)atthepoints(x,y).ThematricesX,Y,U,Vmustallbethesamesizeandcontaincorrespondingpositionandvelocitycomponents(XandYcanalsobevectorstospecifyauniformgrid).QUIVERautomaticallyscalesthearrowstofitwithinthegrid.

Beforewecanusethequiverfunction,weneedtoestablishan(X,Y)gridofobservationpoints,andthesimplestwaytoaccomplishthisistouseMATLABā€™smeshgridfunction.Themeshgridcommandisinvokedasfollows:

[X,Y]=meshgrid(x,y)

wherexandyarevectorsofvaluesoverwhichtocreatethegrid.Thefollowingexamplecreatesagridovertheareaāˆ’2ā‰¤xā‰¤2andāˆ’2ā‰¤yā‰¤2withastepsizeof1byusingthemeshgridcommand.Thegridthatiscreatedwillconsistoftwoarraysof25x-y coordinates (onearrayofx coordinatesanda secondarrayofycoordinates).

Exampleā€‚5.7

%Example_5_7.m:exampleusageofmeshgrid()fprintf('Thisprintoutisfrommeshgrid():\n');x=-2:1:2;y=-2:1:2;[XY]=meshgrid(x,y)------------------------------------------------------------------------

PROGRAMā€‚RESULTSThisprintoutisfrommeshgrid():X= -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2

Page 158: Numerical and Analytical Methods with MATLAB for

142ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Y= -2 -2 -2 -2 -2 -1 -1 -1 -1 -1 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2

Thus, meshgridis a very compact way of generating the coordinate sets.As can be seen, the number of elements in the grid will equal the number of elements in xtimes the number of elements in y. For each grid point, there is an X element and a Y element.

Exampleā€‚5.8

To demonstrate the quiver plot, we will calculate the electric field on the x-z plane resulting from the line charge along the z axis of Example 5.6.

%Example_5_8.m%ThisprogramplotstheelectricfieldontheX-Zplane%foralinechargelocatedontheZaxisandextending%toinfinityinbothZdirections.Thecalculationis%madeovertheintervalxo=[-.01,.01]mandzo=%[-.01,.01]mwithastepsizeof0.002m.Thisexample%reusesthefunctionsalreadydefinedinExample5.6.clc;clear;globalxoyozolambdaepsilon0;lambda=2e-9;epsilon0=8.85e-12;%formeasurementsontheX-Zplane,yowillalwaysbe0:yo=0;%FirstcreateagridofX-Zlocationsforwhich%calculatetheelectricfield[X,Z]=meshgrid(-10e-3:2e-3:10e-3,-10e-3:2e-3:10e-3);%CalculatetheE-fieldateachX-Zlocation,andstore%theresultinthematricesExandEzfori=1:length(X(:,1))forj=1:length(Z(1,:))xo=X(i,j);zo=Z(i,j);%NOTE:don'tcalculatethefieldwhensituated%ONthelinechargebecauseitwillbeinfinity.%Instead,usethevalue"NaN"(whichwillcause%nopointtobeprintedonthequiverplot).ifxo==0Ex(i,j)=NaN;Ez(i,j)=NaN;elseEx(i,j)=quad(@linecharge_Ex,-10,10);Ez(i,j)=quad(@linecharge_Ez,-10,10);endendend%Plottheelectricfield

Page 159: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 143

quiver(X,Z,Ex,Ez);title('E-fieldduetoalinechargealongtheZaxis');xlabel('xaxis');ylabel('zaxis');

------------------------------------------------------------------------

Figure 5.5 shows the resulting quiver plot.

5.7ā€‚ ā€‚MATLABā€™sā€‚dblquadā€‚FunctionTheMATLABfunctionfornumericallyevaluatingadoubleintegralisdblquad.Adescriptionofthefunctioncanbeobtainedbytypinghelp dblquadintheCommandwindow:

Q=DBLQUAD(FUN,XMIN,XMAX,YMIN,YMAX)evaluatesthedoubleintegralofFUN(X,Y)overtherectangleXMIN<=X<=XMAX,YMIN<=Y<=YMAX.FUNisafunctionhandle.ThefunctionZ=FUN(X,Y)shouldacceptavectorXandascalarYandreturnavectorZofvaluesoftheintegrand.

-0.015 -0.01 -0.005 0 0.005 0.01 0.015-0.015

-0.01

-0.005

0

0.005

0.01

0.015Electric field due to a line charge along the Z axis

x axis

z ax

is

Figureā€‚5.5ā€‚ Vectorā€‚plotā€‚ofā€‚theā€‚electricā€‚fieldā€‚inā€‚theā€‚x-zā€‚planeā€‚dueā€‚toā€‚aā€‚lineā€‚chargeā€‚alongā€‚theā€‚zā€‚axis.

Page 160: Numerical and Analytical Methods with MATLAB for

144ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Non-squareregionscanbehandledbysettingtheintegrandtozerooutsideoftheregionofinterest.Forexample,thevolumeofahemisphereofradiusRcanbedeterminedbythedblquadfunctionbysetting-R<=x<=Rand0<=y<=Randsettingz=0forpoints(x,y)thatlieoutsidethecircleofradiusRaroundtheorigin.

Theusageofdblquadissimilartoquad,except

ā—¾ FUNmustbeafunctionoftwovariables(insteadofone):avectorofvaluesinthexdirectionandasinglevalueintheydirection.

ā—¾ Theremustbetwosetsofintegrationlimits(oneforthexdirection,andonefortheydirection).

Exampleā€‚5.9

Calculate the surface area and volume of a hemisphere with radius of 1 m.To find the surface area, we define a differential area element = Ļ† Īø Ļ†dA R d dsin2 (as shown in Figure 5.6) and then double integrate over

the intervals Ļ† = Ļ€[0, 2] and Īø = [0,2Ļ€] using dblquad. To find the volume,

Īø

Ļ†

R

R sinĻ†dĪø

dĻ†

x

y

z

dA = (R sinĻ† dĪø)(RdĻ†)

R

Figureā€‚5.6ā€‚ Toā€‚findā€‚ theā€‚ surfaceā€‚areaā€‚ofā€‚ aā€‚hemisphere,ā€‚weā€‚defineā€‚aā€‚differentialā€‚surfaceā€‚elementā€‚dAā€‚andā€‚thenā€‚doā€‚aā€‚doubleā€‚integrationā€‚overā€‚dĻ•ā€‚andā€‚dĪø.

Page 161: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 145

we define a differential volume element = āˆ’ āˆ’dV R x y dxdy2 2 2 (as shown in Figure 5.7) and double integrate over the intervals x = [āˆ’R,R] and y = [āˆ’R,R].

%Example_5_9.m%Thisprogramcalculatesthesurfaceareaandvolumeof%ahemisphere(withradius=1)usingdblquad.Theexact%valuesfromformulaearealsocalculated.clear;clc;globalR;R=1;%calculatesurfaceareaSA=dblquad('hemisphere_dA',0,pi/2,0,2*pi);SA_exact=2*pi*R^2;%calculatevolumeV=dblquad('hemisphere_dV',-R,R,-R,R);V_exact=2/3*pi*R^3;%printresultsfprintf('SurfaceareaSAofahemisphereof');fprintf('radius%.4fm\n',R);fprintf('SAbyDBLQUAD=%.4fm^2\n',SA);fprintf('SAexact=%.4fm^2\n',SA_exact);fprintf('VolumeVofahemisphereofradius%.4fm\n',R);

R

differential volume element

dxdy

x

y

z

R2 ā€“ x2 ā€“ y2

R2 ā€“ x2 ā€“ y2dV = dxdy

Figureā€‚5.7ā€‚ Toā€‚findā€‚theā€‚volumeā€‚ofā€‚aā€‚hemisphere,ā€‚weā€‚defineā€‚aā€‚differentialā€‚volumeā€‚elementā€‚dVā€‚andā€‚thenā€‚doā€‚aā€‚doubleā€‚integrationā€‚overā€‚dxā€‚andā€‚dy.

Page 162: Numerical and Analytical Methods with MATLAB for

146ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

fprintf('VbyDBLQUAD=%.4fm^3\n',V);fprintf(ā€˜Vexact=%.4fm^3\n',V_exact);

-----------------------------------------------------------------------

%hemisphere_dA.m:Thisfunctiondefinestheintegrand%fordeterminingthesurfaceareaofahemisphereandis%usedinMATLAB'sdblquadfunction.function[dA]=hemisphere_dA(phi,theta)globalR;dA=R^2*sin(phi);

-----------------------------------------------------------------------

%hemisphere_dV.m:Thisfunctiondefinestheintegrand%z(x,y)fordeterminingthevolumeofahemisphereand%isusedinMATLABĆ­sdblquadfunction.Fromanalytical%geometry,theequationofasphereisX^2+Y^2+Z^2=%R^2.Thus,dV=Z*dX*dY,whereZ=sqrt(R^2-X^2-Y^2).Note%thatthehemisphereisonlydefinedfor(X,Y)points%whichliewithinacircleofradiusRaroundthe%origin,theregionthatistheprojectionofthe%hemisphereontotheX-Yplane.An'if'statementis%usedtosetZ=0for(X,Y)pointsoutsidethecircle%ofradiusR.Note:XisavectorandYisascalar.functionZ=hemisphere_dV(X,Y)globalR;fori=1:length(X)ifX(i)^2+Y^2<=R^2Z(i)=sqrt(R^2-X(i)^2-Y^2);elseZ(i)=0;endend-----------------------------------------------------------------------

PROGRAMā€‚RESULTSSurfaceareaSAofahemisphereofradius1.0000mSAbyDBLQUAD=6.2832m^2SAexact =6.2832m^2VolumeVofahemisphereofradius1.0000mVbyDBLQUAD=2.0944m^3Vexact =2.0944m^3

Exercises

Exercise.5.1

UseaTaylorseriesexpansionoflog(1+x)aboutx=0toshowthat

+ = āˆ’ + āˆ’ + āˆ’ +log(1 ) 1

213

14

15

2 3 4 5x x x x x x

Page 163: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 147

Exercise.5.2

UseMATLABā€™squadfunctiontoevaluatethefollowingintegrals;notethatinte-gralsd,e,andfareimproperintegrals:

āˆ«= + āˆ’a.5 23 3

0

3

Idx

e ex x

āˆ«=

āˆ’āˆ’Ļ€

Ļ€

b.sin1 4sin2

/2

/2

Ix dx

x

āˆ«= āˆ’

Ļ€

c. (sinh cos )0

I x x dx

āˆ«= āˆ’

d.31 2

0

1

Ie dx

x

x

āˆ«= āˆ’

e.log(1 )

0

1

Ix dxx

āˆ«= āˆ’

f.log(1 )2

0

1

Ix dxx

Projects

Project.5.1

ForthelinechargeofExample5.8,calculateandplot(usingquiver)theelectricfieldinthex-yplane(insteadofthex-zplane)fortheintervalāˆ’50ā‰¤x ā‰¤50mmandāˆ’50ā‰¤y ā‰¤50mmwithastepsizeof10mm.Remembernottocalculatethefieldatthelocationofthelinecharge.

Project.5.2

WenowmodifythelinechargeofExample5.8tobeofafinitelengthā„“ =0.02malongthezaxis,startingatz =āˆ’0.01mandendingatz =+0.01m.AssumeĪ» = Ɨ āˆ’2 10 9 coul/m.

1. Calculateandplot(usingquiver)themagnitudeoftheelectricfieldfortheintervalāˆ’0.05ā‰¤x ā‰¤0.05mandāˆ’0.05ā‰¤z ā‰¤0.05mwithastepsizeof0.01m.

Page 164: Numerical and Analytical Methods with MATLAB for

148ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

2. Printtothescreeneveryfourthvalueofx0,z0,andthecorrespondingvaluesofEx,Ez ,and themagnitudeof

E .

3. Now,assumethatthetotalchargeofthelinesegment = Ī» = Ɨ āˆ’0.04 10 9Q coulisconcentratedasapointchargeattheorigin.CalculatethemagnitudeoftheelectricfieldforthispointchargeoverthesameintervalaspreviouslyusingEquation(5.8).NotethatbecauseQisapointcharge,youcanuseEquation(5.8)directly,andnointegrationisrequired.

4. CalculatethepercentageerrorinusingthepointchargemethodinthevaluesofExandEzateachpointascalculatedinparts1and3.Usethefollowingformula forcalculating thepercentageerror inEx anda similar formula forcalculatingthepercentageerrorinEz.

=

āˆ’Ć—% error in 100

,1 ,2

,1E

E EEx

x x

x

where

Ex,1=Excalculatedinpart1.

Ex,2=Ex calculatedinpart3.

Printtothescreeneveryfourthvalueofxo,zo,andthecorrespondingvaluesofthepercentageerrorinthevaluesofExandEz.

5. Atwhatdistance from theorigin is thepercentage error inusing thepointchargemethodlessthan5%?Inmanycases,ifwearefarenoughawayfromthecharge,wecanavoidintegratingoveritsgeometryandinsteadjusttreatitasapointcharge,therebymakingourcalculationsmucheasier.Thisiscalledthefar-field approximation.

Project.5.3

Apositivesurface charge densityofmagnitude Ļƒ = Ɨ āˆ’4 10 coul/m12 2 extendsinfi-nitelyinthex-yplaneasshowninFigureP5.3a.UsingamethodsimilartowhatwasdescribedinSection5.4(showyourwork),defineadifferentialchargeelementdQ =Ļƒdydxandthenfindtheresultingelectricfieldbyintegratingoverthesheetofchargefor = āˆ’āˆž āˆž[ , ]x p , = āˆ’āˆž āˆž[ , ]y p ,and = 0z p :

āˆ«āˆ« ( )

=Ļƒ

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edy dx x x

x x y y z zx

p p

o

p

o p o p o p

(P5.3a)

āˆ«āˆ« ( )

=Ļƒ

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edy dx y y

x x y y z zy

p p

o

p

o p o p o p

(P5.3b)

āˆ«āˆ« ( )

=Ļƒ

Ļ€Īµ

āˆ’

āˆ’ + āˆ’ + āˆ’āˆ’āˆž

āˆž

āˆ’āˆž

āˆž

4 ( ) ( ) ( )2 2 232

Edy dx z z

x x y y z zz

p p

o

p

o p o p o p

(P5.3c)

Page 165: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 149

1. WriteaMATLABprogramusingthedblquadfunctiontocalculateEx,Ey,andEz atthefollowingpoints:

xo, yo, zo=[0,0,2Ɨ 10ā€“3] (abovetheplate)

= Ɨ āˆ’ Ɨ Ɨāˆ’ āˆ’ āˆ’, , [ 30 10 , 5 10 , 12 10 ]3 3 3x y zo o o (belowtheplate)

Assumethat10isagoodenoughapproximationforinfinity.Notethatbysymmetry,thexandycomponentsofthefieldshouldintegratetozero(orclosetoit).Confirmthisresult.

2. Now, assume that there are two sheet charges in the planes parallel to thex-yplane: thefirst sheet locatedat = +1z p mmwith surfacechargedensityĻƒ = Ɨ āˆ’4 10 coul/m12 2 andthesecondsheetlocatedat = āˆ’1z p mmandoppo-sitelychargedwithsurfacechargedensity Ļƒ = āˆ’ Ɨ āˆ’4 10 coul/m12 2 (seeFigureP5.3b).Findtheelectricfieldviasuperpositionbycalculatingtheelectricfield

y

x

zMeasurement point

Sheet charge with surfacecharge density Ļƒ coul/m2

Differential chargeelement Ļƒdxdy

r ro

rp

dE

(a)

y

x

z

Sheet charge with surfacecharge density Ļƒ coul/m2

located at zp = 1 mm

Sheet charge with surfacecharge density ā€“Ļƒ coul/m2

located at zp = ā€“1 mm

(b)

Figureā€‚P5.3ā€‚ (a)ā€‚Theā€‚differentialā€‚electricā€‚fieldā€‚Ed ā€‚atā€‚observationā€‚pointā€‚

roā€‚dueā€‚toā€‚aā€‚

differentialā€‚sheetā€‚chargeā€‚elementā€‚Ļƒdxdyā€‚locatedā€‚onā€‚theā€‚x-yā€‚plane.ā€‚(b)ā€‚Twoā€‚parallelā€‚andā€‚oppositelyā€‚chargedā€‚sheetā€‚chargesā€‚locatedā€‚onā€‚theā€‚planesā€‚zpā€‚=ā€‚+1mmā€‚ā€‚andā€‚zpā€‚=ā€‚ā€“1mm.

Page 166: Numerical and Analytical Methods with MATLAB for

150ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

separatelyforeachsheetandthenaddingthemtogether.FindEx,Ey,andEz forthethesethreepoints:

xo,yo,zo=[0,0,2Ɨ 10ā€“3] (abovetheplates)

xo,yo,zo=[10Ɨ 10ā€“3,0,ā€“0.5Ɨ 10ā€“3] (betweentheplates)

= Ɨ āˆ’ Ɨ Ɨāˆ’ āˆ’ āˆ’, , [ 30 10 , 5 10 , 12 10 ] (below the plates)3 3 3x y zo o o

Printouttheresults.Dotheseresultsmakesense?

Project.5.4

TheBiot-Savartlawrelateselectricalcurrenttomagneticfield(seeFigureP5.4a)andisdefinedforcurrentflowthroughwiresas

4 2d

Ido rBe

r

=Ļ€

Ɨ (P5.4)

whereBd isthedifferentialmagneticfield(avector), o isthepermeabilityof

free space ( Ļ€ Ɨ āˆ’4 10 7 henry/m), I is the current (in amperes),

d is adifferen-tialwirelengthwithdirectioncorrespondingtothecurrentflow,

r isthevector

fromthecurrentelementtothemeasurementpoint, er istheunitvectorinther direction,andƗrepresentsthevectorcrossproduct.InFigureP5.4a,wealsodefine

rp asthelocationofthecurrentelementand

ro asthepointofmeasure-

mentsuchthat r r ro p= āˆ’ .

WewishtocalculatethemagneticfieldforaninfinitewireextendingalongthezaxisandcarryingacurrentofI= 1mAinthe+zdirection.Notethat,inreality,aninfinite-

I

y

x

z

Wire

Measurementlocation

r

ro

rp

dB

Differential currentelement Id

Figureā€‚P5.4aā€‚ Theā€‚differentialā€‚magneticā€‚fieldā€‚elementā€‚Bd ā€‚atā€‚observationā€‚pointā€‚

roā€‚

dueā€‚toā€‚aā€‚differentialā€‚wireā€‚elementā€‚carryingā€‚currentā€‚

Id .

Page 167: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 151

lengthcurrent-carryingwireisimpossiblebecauseitviolatesconservationofcharge.Fornow,itissufficienttopresumethatthewireisconnectedtoacurrentsourceatĀ±āˆž.

1. AsshowninFigureP5.4b,forawireinthezdirection, ed dz p zĖ†= .Duetothe

crossproductinEquationP5.4,if

d isz directed,thentheresultingBd will

onlyhavecomponentsinthexandydirections.Writetwoseparateequationsfor dBx and dBy bywriting er intermsofits e x, e y,and ez components,computing thecrossproductsbetween

d and er and then separating the

xandycomponentsofBd intoseparateequations.Hint:Derive e x and e y

from er usingthemethodemployedinEquation(5.10). 2. Write two MATLAB functions for dBx and dBy that compute the x- and

y-directedmagneticfieldsintermsofasingleargumentzp.Useglobalvariablesforthemeasurementpositionparametersxo,yo ,andzo .Usethequadfunctiontointegrateovertheinterval = āˆ’āˆž āˆž[ , ]z p andcalculatethemagneticfieldatthesepoints:

= Ɨ Ɨāˆ’ āˆ’, , [1 10 , 1 10 , 0]4 4x y z (firstquadrant)

= āˆ’ Ɨ Ɨāˆ’ āˆ’, , [ 1 10 , 1 10 , 0]4 4x y z (secondquadrant)

x,y,z=[ā€“1Ɨ10ā€“4,ā€“1Ɨ 10ā€“4,0] (thirdquadrant)

x,y,z=[1Ɨ10ā€“4,ā€“1Ɨ 10ā€“4,0] (fourthquadrant)

Assume that 10 is a sufficient approximation for infinity. Print out the results.Commentonanysymmetryyoufindinthesesolutions.

3. Use the meshgrid function to create a set of points forro where

āˆ’ ā‰¤ ā‰¤200 200xo mm, āˆ’ ā‰¤ ā‰¤200 200yo mm, and = 0zo . Use a step size

I

x

z

Wire along z axiswith current I

Differential currentelement Idzpe z

r

ro

Magnetic field dB(directed into page) atmeasurement location rorp

Figureā€‚P5.4bā€‚ Theā€‚magneticā€‚fieldā€‚dueā€‚toā€‚aā€‚wireā€‚alongā€‚theā€‚zā€‚axisā€‚willā€‚haveā€‚onlyā€‚xā€‚andā€‚yā€‚components.

Page 168: Numerical and Analytical Methods with MATLAB for

152ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

of50mmforbothxoandyo.ComputethemagneticfieldBxandBy ateachvalueof

ro andplotwithquiver.Wheniteratingoveryourvaluesfor

ro ,

besuretoskipthepointattheorigin.

Project.5.5

FigureP5.5ashowsacircularwirewithradiusRcenteredattheoriginandcarry-ingacurrentI.UsingtheBiot-SavartlawfromEquation(P5.4),wecanwritethedifferentialmagneticfieldintermsofadifferentialcurrentelement eId IRd pĖ†

= Īø Īø ,

where ĪøRd p isthedifferentiallength(incylindricalcoordinates)ofthecurrentele-mentatlocation

rp ,and eĪø istheunitvectorinthe Īø p direction.Inthistypeof

problemwithcylindricalsymmetry,thesimplestapproachistoconvertthecylin-dricalunitvectorsinto(constant)cartesianunitvectorsbutstillperformtheinte-grationusingthecylindricalvariables.FigureP5.5bshowshow

rp and eĪø canbe

expressedintermsoftheirxandycomponentsusingtheunitvectors e x and e y :

Ė† cos Ė† sinr e eR Rp x p y p= Īø + Īø (P5.5a)

Ė† Ė† sin Ė† cose e ex p y p= āˆ’ Īø + ĪøĪø (P5.5b)

WecannowrewriteEquation(P5.4)as

4 2 2 2 3

2

( Ė† sin Ė† cos ) (Ė† ( cos ) Ė† ( sin ) Ė† ( ))

(( cos ) ( sin ) ( ) )B

e e e e ed

IRd

x R y R z z

x R y R z zo

px p y p x o p y o p z o p

o p o p o p

=Ļ€

Īøāˆ’ Īø + Īø Ɨ āˆ’ Īø + āˆ’ Īø + āˆ’

āˆ’ Īø + āˆ’ Īø + āˆ’

(P5.5c)

where o isthepermeabilityoffreespace( Ļ€ Ɨ āˆ’4 10 7 H/m).

y

x

z

Wire loopwith radius R

IĪøp

Measurementlocation

Differential currentelement IRdĪøpe Īø

rro

rp

dB

Figureā€‚P5.5aā€‚ Theā€‚differentialā€‚magneticā€‚fieldā€‚elementā€‚

dB ā€‚atā€‚observationā€‚pointā€‚roā€‚

dueā€‚toā€‚aā€‚wireā€‚loopā€‚locatedā€‚inā€‚theā€‚x-yā€‚plane.

Page 169: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 153

1. Calculate the vector cross product in Equation (P5.5c) and split the resultintothreeseparateequationsforthex,y,andzcomponentsofthedifferentialmagneticfield.Use the resultingexpressions fordBx,dBy, anddBz towritethreeMATLABfunctionsthattakeoneargument(Īøp)andcanbeusedwithMATLABā€™squadfunctiontodetermineBx,By,andBz .

2. UseMATLABā€™smeshgridfunctiontocreateasetofpointsinthex-zplaneforā€“8ā‰¤x0ā‰¤8mm(withastepsizeof1mm)andā€“2ā‰¤z0ā‰¤2mm(withastepsizeof0.5mm).DetermineBxandBz ateachpointintheset(besuretousethecorrectintegrationlimits)andplotwithquiver.AssumeR =2.5mm,I =1mA.

Project.5.6

Asolenoidisacoilofwireusedtocreateamagneticfieldtoactivateanactuator.Typicalusesincludeelectricalrelays,electricallycontrolledwatervalves,andauto-motivestartergears.FigureP5.6ashowsasolenoidwithradiusR,lengthD,turncountN,andcurrentI.

WemodelthesolenoidinMATLABasacylindricalsheetcurrentwithdensity

Ė†K eNID

= Īø A/mwith thecurrentdensitydirected in theĪødirection.TheBiot-

Savartlawforasurfacecurrentis

=Ļ€

Ɨ4 2B

K e

rd

dAo r (P5.6a)

wheredAisatwo-dimensionaldifferentialsurfaceelement,r isthevectorfrom

thedifferentialsurfacetothemeasurementpoint, er istheunitvectorinther

direction,Ɨrepresentsthevectorcrossproduct,and o isthepermeabilityoffreespace( Ļ€ Ɨ āˆ’4 10 7 H/m).FromFigureP5.6b,weseethatincylindricalcoordinates,

y

x

ey cosĪøp

exR cosĪøp

Ė†āˆ’ex sinĪøp

eĪø

eyR sinĪøp

Wire loopwith radius R

Īøp

I

rp

Figureā€‚P5.5bā€‚rp ā€‚andā€‚ Ė†

peĪø ā€‚mayā€‚beā€‚decomposedā€‚intoā€‚theirā€‚xā€‚andā€‚yā€‚componentsā€‚toā€‚solveā€‚forā€‚theā€‚magneticā€‚fieldā€‚withā€‚MATLABā€™sā€‚quadfunction.

Page 170: Numerical and Analytical Methods with MATLAB for

154ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

I

N turnsD

2R

Figureā€‚P5.6aā€‚ Aā€‚solenoidā€‚consistingā€‚ofā€‚Nā€‚turns,ā€‚radiusā€‚R,ā€‚lengthā€‚D,ā€‚andā€‚current I.

y

z

x

D

2R

ĪøpMeasurement location

Differential surface elementdA= RdĪøpdzp

Cylindrical sheet currentwith current densityK amp/m in the Īø direction

r

ro

rp

dBK

Figureā€‚P5.6bā€‚ Theā€‚solenoidā€‚canā€‚beā€‚modeledā€‚asā€‚aā€‚sheetā€‚currentā€‚ofā€‚magnitudeā€‚Kā€‚A/m.

Page 171: Numerical and Analytical Methods with MATLAB for

Numerical Integrationā€ƒ ā—¾ā€ƒ 155

= ĪødA Rd dzp p ,whererp isthelocationofthedifferentialsurface(withcylindri-

calcomponents rp , Īø p ,and z p),and eĪø istheunitvectorinthe Īø p direction.Wealsodefinetheobservationpoint

Ė† Ė† Ė†r e e ex y zo o x o y o z= + + .Fromthegeometryoftheproblem,wecanwrite

KdA and

r intermsofCartesianunitvectors:

Ė† ( Ė† sin Ė† cos )K e e edA

NID

Rd dzNID

Rd dzp p p p x p y p= Īø = Īø āˆ’ Īø + ĪøĪø (P5.6b)

Ė† ( cos ) Ė† ( sin ) Ė† ( )r r r e e ex R y R z zo p x o p y o p z o p= āˆ’ = āˆ’ Īø + āˆ’ Īø + āˆ’ (P5.6c)

SubstitutingbackintoEquation(P5.6a)gives

4( Ė† sin Ė† cos ) Ė† ( cos ) Ė† ( sin ) Ė† ( )

( cos ) ( sin ) ( )2 2 232

Be e e e e

dNIRD

d dzx R y R z z

x R y R z z

op p

x p y p x o p y o p z o p

o p o p o p( )( )

=Ļ€

Īøāˆ’ Īø + Īø Ɨ āˆ’ Īø + āˆ’ Īø + āˆ’

āˆ’ Īø + āˆ’ Īø + āˆ’

(P5.6d)

1. Calculate the vector cross product in Equation (P5.6d) and split the resultintothreeseparateequationsforthex,y,andzcomponentsofthedifferentialmagnetic field. Use the resulting expressions for dBx, dBy, and dBz to writethreeMATLABfunctionsthattaketwoarguments(Īøpandzp)andcomputethedifferentialBfieldinthex,y,andzdirections,respectively.

2. AssumethatthesolenoidiscenteredattheoriginwithradiusR=2.5mmandD=15mm.Usemeshgridtocreateathree-dimensionalpointset[X,Y,Z]ofmeasurementpointsfor

ro .Notethatmeshgridtakesanoptionalthirdargu-

menttocreatethree-dimensionalpointsets(seehelpmeshgridforusagedetails).Usetheselimitsfor ( , , )x y zo o o : āˆ’ ā‰¤ ā‰¤3 3xo mm(withastepsizeof1.5mm), Źŗ Źŗ0 3yo (withastepsizeof1.5mm),and 10 10zoāˆ’ ā‰¤ ā‰¤ mm(withastepsizeof5mm).

3. UsedblquadtocalculateBx,By,andBz ateachpointintheset(besuretousethecorrectintegrationlimits).Assume:N = 500,I =1mA.

4. Create a three-dimensional quiver plot of your results using MATLABā€™squiver3function(runhelpquiver3forusagedetails).

Page 172: Numerical and Analytical Methods with MATLAB for
Page 173: Numerical and Analytical Methods with MATLAB for

157

Chapter 6

Numericalā€‚Integrationā€‚ofā€‚Ordinaryā€‚Differentialā€‚Equations

6.1ā€‚ ā€‚IntroductionInthischapter,weexamineseveralmethodsforsolvingordinarydifferentialequa-tions(ODEs).ODEscanbebrokenupintotwocategories:

a.Initial value problemsinwhichweknowthenecessaryinitialconditions,forexample,thevalueofacircuitnodevoltage(oritsslope)att =0;

b.Boundary value problemsinwhichweknowthevalueofthedependentvariableatspecificcoordinatesintheproblemgeometry,forexample,theelectricpoten-tialatbothendsofaconductor.

For initial value problems, we examine several numerical integration meth-ods, including theEulermethod, themodifiedEulermethod, theRunge-Kuttamethod,andthebuilt-inode45functionofMATLAB.Forboundaryvalueprob-lems,weemployimplicitfinite-differencemethodsthatreduceODEstoasystemoflinearalgebraicequations,whichturnouttobeatri-diagonalsystemthatcanbesolvedalgebraically.

Page 174: Numerical and Analytical Methods with MATLAB for

158ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6.2ā€‚ ā€‚Theā€‚Initialā€‚Valueā€‚ProblemInaninitialvalueproblem,thevaluesofthedependentvariableandthenec-essaryderivativesareknownatthepointatwhichtheintegrationbegins.Webeginwithafirst-orderdifferentialequationofthegeneralformsuchthatthederivativeisaknownfunctionofxandy,andtheinitialcondition,y(0)=YI,isknown:

=

=

( , )

(0)

dydx

f x y

y YI

(6.1)

Thereareseveraltechniquesforsolvingthistypeofproblem,includingEulerā€™smethod,whichissimplebutnotusedverymuch;themodifiedEulermethod;theRunge-Kuttamethod;andothers.Eachtechniquehasprosandconswithrespecttosimplicity,accuracy,andcomputationalefficiency.

6.3ā€‚ ā€‚Theā€‚Eulerā€‚AlgorithmThegeneralapproachtosolvingdifferentialequationsnumericallyistosubdividethexdomainintoNsubdivisionsgiving +, , ,... ,1 2 3 1x x x xN andthenā€œmarchā€inthex directionovertheintervalwhilecalculating +, , , ...,2 3 3 1y y y yN .Notey1 is

xi xi+1

yi yi+1

y

xx1

y1 yN+1

xN+1

Figureā€‚6.1ā€‚ Toā€‚solveā€‚aā€‚first-orderā€‚differentialā€‚equationā€‚yā€² =ā€‚f(x,ā€‚y),ā€‚weā€‚divideā€‚theā€‚intervalā€‚ofā€‚interestā€‚intoā€‚Nā€‚subdivisionsā€‚andā€‚thenā€‚estimateā€‚theā€‚nextā€‚valueā€‚ofā€‚yā€‚byā€‚usingā€‚anā€‚approximationā€‚basedā€‚onā€‚aā€‚Taylorā€‚seriesā€‚aroundā€‚theā€‚knownā€‚point.

Page 175: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 159

specifiedand isequal to the initialconditionYI (seeFigure 6.1).ATaylor seriesexpansionaboutanarbitrarypointxigives

( ) ( )= + āˆ’ + āˆ’ +( ) ( ) ( )

1!( )2!

2y x y xy x

x xy x

x xii

ii

i (6.2)

Ifweuseonlythefirsttwotermsoftheseries,wecanapproximatethevaluefory(xi+1)(whichwedenoteasyi+1)as

ā‰ˆ + āˆ’

ā‰ˆ +

+ +( ) ( )1

( )1 1y y xy x

x x

y y h

i ii

i i

i i (6.3)

where = āˆ’+1h x xi i,whichisdefinedasthestep size, and yi istheslopeofthecurveofy(x)atxi.SubstitutingEquation(6.1)into(6.3),weobtain

= ++ ( , )1y y h f x yi i i i (6.4)

AscanbeseenfortheconfigurationshowninFigure 6.2,thepredictionofyi+1byEulerā€™smethodovershootsthetruevalueofyi+1.Thus,startingwithi =1,weobtain

= + = +( , ) ( , )2 1 1 1 1y y h f x y Y h f x YI I

Similarly,y3canbedeterminedbysubstitutingi=2intoEquation(6.4):

= + ( , )3 2 2 2y y h f x y

xi xi+1

yi

y

x

yi+1,Euler

yi+1,exact

Figureā€‚6.2ā€‚ Inā€‚theā€‚Eulerā€‚method,ā€‚weā€‚useā€‚aā€‚first-orderā€‚Taylorā€‚seriesā€‚approximationā€‚(i.e.,ā€‚aā€‚straightā€‚line)ā€‚toā€‚approximateā€‚theā€‚nextā€‚valueā€‚ofā€‚y.

Page 176: Numerical and Analytical Methods with MATLAB for

160ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

The process is continued, obtaining , , ,...,4 5 6 1y y y yN + . The Euler method isanexampleofanexplicitmethodbecauseeachnewvalueforyi+1dependssolelyonpreviousvaluesofxandy.

6.4ā€‚ ā€‚Modifiedā€‚Eulerā€‚Methodā€‚withā€‚Predictor-Correctorā€‚Algorithm

ThemodifiedEulermethod is amore accurateway for calculating the value ofyi+1thanthesimplelinearapproximationoftheEulermethodintheprevioussec-tion. Again, we consider a differential equation of standard form = ( , )y f x y withinitialcondition =(0)y YI ,andagainwesubdividethexdomainintoNsub-divisions and march in the x direction. We saw that in the Euler method, tak-ing = + = ++ ( , )1y y hy y hf x yi i i i i i overshoots the true value of yi+1 (as shown inFigure 6.2).Now,supposewewereabletodetermine +( )1y xi ,whichwouldbetheslopetothecurveat + .1xi Ifweweretopredictyi+1byusing +( )1y xi inEquation6.3,thatis,

( , )1 1 1 1y y h y y h f x yi i i i i i= + = ++ + + + (6.5)

thenwewouldundershootthetruevalueofyi+1.ThisisshowninFigure 6.3.Here,wehaveconstructedatangenttothecurveatyi+1anddrawnaparallellinepassing

yi

xi xi+1

yi+1

y

x

Slope = yi

Slope = yi+1

yi + hyi+1

yi + hyi

h

Figureā€‚6.3ā€‚ Inā€‚theā€‚modifiedā€‚Eulerā€‚method,ā€‚weā€‚useā€‚theā€‚averageā€‚ofā€‚twoā€‚straight-lineā€‚approximationsā€‚toā€‚predictā€‚yi+1.

Page 177: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 161

through point ( , )x yi i to obtain the predicted value for yi+1. Since using yi inEquation(6.3)overshootsthetruevalueofyi+1andusing +1yi inEquation(6.3)undershoots thetruevalueofyi+1,weseethatabetterestimate foryi+1wouldbeobtainedbyusinganaverageofthetwoderivativesinEquation(6.3),thatis,

= +

++

+

211y y h

y yi i

i i (6.6)

Unfortunately,Equation(6.6)isnolongerexplicitbecausewedonotknowthevalueof +1yi .TheuseofEquation(6.6)insolvingthedifferentialEquation(6.1)isanexampleofanimplicitmethod.However,wecanapproximateavaluefor +1yi byusingthepredictor-correctormethod.Toapplythismethod,werewriteEquation(6.6)asfollows:

( )= +

++

+

211y y h

y yiC

ii i

P

(6.7)

wherethePsuperscriptindicatesthepredictedvalue,andtheCsuperscriptindicatesthecorrectedvalue.Equation(6.7)iscalledthecorrector equationandcanbeusedtoiterativelycalculatethevalueforyi+1.SubstitutingEquation(6.1)into(6.7)gives

( )= + ++ + +2

( , ) ( , )1 1 1y yh

f x y f x yiC

i i i i iP (6.8)

Thepredictor-correctortechniqueproceedsasfollows:

1.UsetheEulermethodtodetermineafirstpredictedvalueforyi+1,called ,11yiP+

thatis,

= ++ ( , )11y y h f x yiP

i i i

2.Calculatethefirstcorrectedvalue +11yiC byusing 1

1yiP+ inEquation(6.8).

3.Use +11yiC asthenewpredictedvalue 1

2yiP+ inEquation(6.8).

4.Calculateanewcorrectedvalue +12yiC .

5.Repeatsteps3and4until āˆ’ < Īµ+ ++

1 11y yi

CiCn n ,whereĪµisanerrortolerancethat

dependsonthedesiredaccuracyandistypicallyafractionofapercentofthelastcorrectedvalue,forexample, Īµ = Ɨ +0.01% 1yiCn .

Page 178: Numerical and Analytical Methods with MATLAB for

162ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚6.1

In this example, we find the exact solution of a first-order differential equa-tion and then compare with the corresponding solutions found by the Euler and modified Euler methods.

A simple RC circuit is ā€œdrivenā€ by a voltage source VD as shown in Figure 6.4. Writing Kirchhoffā€™s voltage law around the loop gives

āˆ’ āˆ’ =V v vD R C 0 (6.9)

Applying Ohmā€™s law =v iRR( ) and the constituent relation for capacitor

current =i CdvdtC , we can rewrite Equation (6.9) as

āˆ’ āˆ’ =V RC

dvdt

vDC

C 0

Rearranging gives

+Ļ„

=Ļ„

dvdt

vVC

CD1

(6.10)

where Ļ„ = RC is the time constant for the RC circuit. Equation (6.10) is a first-order differential equation of vC with respect to time. We assume that at t = 0, the initial capacitor voltage is zero, and that the driving voltage is a ramp function, that is =V t V tD o( ) . We first solve Equation (6.10) analytically so that we can have a basis for comparison with numerical solutions. We begin by guessing a particular solution vC,P having the same form as the driving function:

= Ī± + Ī²v tC P, (6.11)

where Ī± and Ī² are constants to be determined. Substituting vC,P into Equation (6.10), we obtain

( ) ( )Ī± + Ī² +

Ļ„Ī± + Ī² =

Ļ„ddt

t tV to1

+ā€“

VD vC

+

āˆ’

C

R

+ vR āˆ’

Figureā€‚6.4ā€‚ RCā€‚circuit.

Page 179: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 163

which gives

Ī±Ļ„+ Ī± +

Ī²Ļ„

=Ļ„

t V to (6.12)

Matching terms between the left and right sides of Equation (6.12), we

see that Ī± = Vo and Ī² = āˆ’ Ļ„Vo . Thus,

= āˆ’ Ļ„v V t VC P o o,

Next, we find the complementary solution, vC,H, to the homogeneous equation, which is Equation (6.10) when the driving function is zero.

+Ļ„

=dvdt

vC HC H

10,

, (6.13)

Equation (6.13) is separable. Thus,

= āˆ’

Ļ„ā†’ = āˆ’

Ļ„+ Ī³ ā†’ = Ī³

āˆ’ Ļ„dvv

dtv

tv eC H

C HC H C H

tln ln,

,, , (6.14)

where Ī³ is a constant to be determined. We now take the complete solution as the sum of the particular and homogeneous solutions:

= +

= āˆ’ Ļ„ + Ī³āˆ’Ļ„

v v v

V t V e

C C P C H

o ot

, ,

(6.15)

Applying the initial condition =vC (0) 0 to Equation (6.15), we find that Ī³ = Ļ„Vo . Thus, the complete solution for the ramp response of an RC circuit is

( )= āˆ’ Ļ„ āˆ’

āˆ’Ļ„v t V t eC ot

( ) 1 (6.16)

We now solve Equation (6.10) numerically for the following parameter values: R = 1 kĪ©, C = 1 Ī¼F, and =Vo 10 V . First, we rearrange the governing differential equation (6.10) into the form of Equation (6.1):

( ) ( )=

Ļ„āˆ’ =

Ļ„āˆ’ =

dvdt

V v V t v f t vCD C o C C

1 1( , ) (6.17)

Next, we choose a time interval and time step. For the RC circuit, we know that the interesting transient behavior will occur within a few mul-tiples of the time constant, and thus we arbitrarily choose an interval of t =

[ 0, 10Ļ„ ]. We also divide the interval into 20 steps, and thus =Ļ„

h1020

.

Page 180: Numerical and Analytical Methods with MATLAB for

164ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

A MATLAB script that carries out the Euler method and the modified Euler method follows:

%Example_6_1.m%CalculaterampresponseofRCcircuitvia3methods:%1.exactsolution%2.byEulermethod%3.bymodifiedEulermethodclc;clear;%Circuitparameters:R=1e3;%ohmsC=1e-6;%faradstau=R*C;%secondsVo=10;%voltsf=@(tm,Vc)(1/tau)*(Vo*tm-Vc);%Equation6.17%ParametersforEuleralgorithminterval=10*tau;steps=20;h=interval/steps;%Createsetoftimepointstocalculatet=0:h:interval;%InitialconditionsVc_exact(1)=0;Vc_euler(1)=0;Vc_mod_euler(1)=0;%ExactandEulermethod:marchintimefori=1:length(t)-1%ApplyEquation6.16Vc_exact(i+1)=Vo*(t(i+1)-tau+tau*exp(-t(i+1)/tau));%ApplyEquation6.4Vc_euler(i+1)=Vc_euler(i)+h*f(t(i),Vc_euler(i));end%ModifiedEuler:applycorrectorequationtolerance=1e-4;%.01percentfori=1:length(t)-1%usetheEulermethodtocalculateaninitialguess%forthepredictedvalueVc_predicted=Vc_mod_euler(i)...+h*f(t(i),Vc_mod_euler(i));%Repeatedlyapplythecorrectorequationuntilthe%predictorandcorrectorareequal(orwithin%tolerance)forj=1:50Vc_corrected=Vc_mod_euler(i)...+(h/2)*(f(t(i),Vc_mod_euler(i))...+f(t(i+1),Vc_predicted));ifabs(Vc_corrected-Vc_predicted)/Vc_predicted...<tolerancebreak;elseVc_predicted=Vc_corrected;endend%ifwereachedtheiterationlimitof50,thenprint%warning:ifj==50

Page 181: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 165

fprintf('Warningatstep');fprintf('%d:reachediterationlimit\n',i);endVc_mod_euler(i+1)=Vc_corrected;end%Plotresultssubplot(1,2,1),plot(t,Vc_euler,'x',t,Vc_exact),legend('Euler','Exact','Location','NorthWest');title('Eulersolutioncomparedtoexact');xlabel('seconds');ylabel('Vc(volts)');text(0.006,0.005,sprintf('%dsteps',steps));subplot(1,2,2),plot(t,Vc_mod_euler,'x',t,Vc_exact),legend('ModifiedEuler','Exact','Location','NorthWest');title('ModifiedEulersolutioncomparedtoexact');xlabel('seconds'),ylabel('Vc(volts)');text(0.006,0.005,sprintf('%dsteps',steps));

The resulting solutions for Example 6.1 are graphed in Figure 6.5. Note that for N = 20 subdivisions in the time domain, both the Euler and modified Euler solutions are almost indistinguishable from the exact solution.

Figure 6.6 shows the same example where we have increased the time step by reducing N to 6 (accomplished by changing steps=20 to steps=6in the program). Note that in this case, the Euler solution deviates substantially from the exact solution and also oscillates above and below the exact solu-tion. On the other hand, the solution for the modified Euler method remains accurate and stable even for small N. Ideally, we would like to reduce N to as small as possible (to reduce computation time), but at the same time we want to avoid numerical instability. Thus, the modified Euler method is a compro-mise that has some additional computational operations (due to the iterative predictor-corrector algorithm) but yet stays stable for large time steps.

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

seconds

Vc

(vol

ts)

Euler solution compared to exact

20 steps

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

seconds

Vc

(vol

ts)

Modified Euler solution compared to exact

20 steps

EulerExact

Modified EulerExact

Figureā€‚ 6.5ā€‚ Plotā€‚ ofā€‚ VCā€‚ versusā€‚ tā€‚ forā€‚ RCā€‚ circuitā€‚ forā€‚ 20ā€‚ stepsā€‚ overā€‚ theā€‚ intervalā€‚0 ā‰¤ t ā‰¤ 10Ļ„:ā€‚(a)ā€‚Eulerā€‚andā€‚exactā€‚solutions;ā€‚(b)ā€‚modifiedā€‚Eulerā€‚andā€‚exactā€‚solutions.

Page 182: Numerical and Analytical Methods with MATLAB for

166ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6.5ā€‚ ā€‚Numericalā€‚Errorā€‚forā€‚Eulerā€‚AlgorithmsSolutionstodifferentialequationsusingtheEulerandmodifiedEuleralgorithmsarebydefinitionanapproximationtotheexactsolutionbecausethederivationsofthesealgorithmshavetheirbasisinatruncatedTaylorseries.Ifwewishtodeter-minetheaccuracyofaparticularnumericalscheme,wecantestitonadifferentialequationforwhichanexactsolutionisavailable.Unfortunately,inmostcases,wedonotknow(orcannotsolvefor)theexactsolutionofthedifferentialequation;thisisusuallywhyweresortedtoanumericalmethodinthefirstplace.However,inExample6.1,wedidderivetheexactsolution;thus,wecancalculatetheglobal percentage error ,globalEi foragivennumericalalgorithmattimestepias

=

āˆ’,global

,exact ,numerical

,exactE

y yyi

i i

i (6.18)

Analternativemeasureofaccuracyisthelocal truncation error(LTE),inwhichwecalculatethehigher-ordertermsoftheTaylorseries(oratleastthefirstdiscardedterm)anduseittodecidewhetherwehavechosentoolargeatimestep.Forexample,

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

seconds

Vc

(vol

ts)

Euler solution compared to exact

6 steps

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

seconds

Vc

(vol

ts)

Modified Euler solution compared to exact

6 steps

EulerExact

Modified EulerExact

Figureā€‚ 6.6ā€‚ Plotā€‚ ofā€‚ VCā€‚ versusā€‚ tā€‚ forā€‚ RCā€‚ circuitā€‚ forā€‚ sixā€‚ stepsā€‚ overā€‚ theā€‚ intervalā€‚0 ā‰¤ t ā‰¤ 10Ļ„.ā€‚(a)ā€‚Eulerā€‚andā€‚exactā€‚solutions.ā€‚Noteā€‚thatā€‚theā€‚Eulerā€‚solutionā€‚oscillates.ā€‚(b)ā€‚Modifiedā€‚Eulerā€‚andā€‚exactā€‚solutions.ā€‚Noteā€‚thatā€‚theā€‚modifiedā€‚Eulerā€‚methodā€‚isā€‚stableā€‚evenā€‚forā€‚aā€‚largeā€‚stepā€‚size.

Page 183: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 167

inEquation (6.3),wediscarded the second-orderandhigher terms in theTaylorseriestoderivetheEulermethod;thus,theLTEis

= +

2higher-order termsEuler

2LTEyhi

Ifweneglectthehigher-orderterms,thenthetruncationerrorisontheorderofh2,whichiscommonlywrittenasO(h2).Qualitatively,thismeansthatifwereducethestepsizebyafactoroftwo,thentheLTEisreducedbyapproximatelyafactoroffour,resultinginamoreaccuratesolution.

Inpractice,thesimplestmethodforchoosingthestepsizeistostartwithsomefractionofthefastestknownparameterinthesystem.Forexample,whensolving

anRCcircuit, startwitha stepsizeof1/100of the timeconstant,or =100

hRC .

Then,doublethestepsizeandreruntheprogram.Ifthetwosolutionsareidenti-cal,thenthestepsizeissufficientlysmall,andiftheprogramrunsslowly,thenyoumightconsiderredoublingyourstepsizeandcomparingagaintoobtainafasterexecutiontimewithoutlosingaccuracy.

6.6ā€‚ ā€‚Theā€‚Fourth-Orderā€‚Runge-Kuttaā€‚MethodThefourth-orderRunge-Kuttamethodusesaweightedaverageofderivativeesti-mateswithin the interval of interest to calculate a value for yi+1.Weagain startwiththefirst-orderdifferentialequationofEquation(6.1)withknowninitialcon-

ditions. In the modified Euler method, we used = + ++ +2( )1 1y y

hy yi i i i . In the

Runge-Kuttamethod,insteadweuse

( )= + + + ++ 6

2 21 1 2 3 4y yh

k k k ki i (6.19)

where

=

= + + +

= + + +

= + + +

( , ) (value of at )

2,

2estimate of at

2

2,

2a second estimate of at

2( , ) (estimate of at )

1

2 1

3 2

4 3 1

k f x y y x

k f xh

yhk y x

h

k f xh

yhk y x

h

k f x h y hk y x

i i i

i i i

i i i

i i i

Runge-KuttaisanexplicitalgorithmandthusissimpletocomputewithMATLAB.

Page 184: Numerical and Analytical Methods with MATLAB for

168ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚6.2

Solve the RC circuit of Example 6.1 using the Runge-Kutta method for N = 20 and N = 6 steps. Also, find the worst-case global error for each case. The MATLAB program follows:

%Example_6_2.m%CalculaterampresponseofRCcircuitviatwomethods:%1.exactsolution%2.Runge-Kuttamethodclc;clear;%circuitparametersR=1e3;%ohmsC=1e-6;%faradstau=R*C;%secondsVo=10;%voltsf=@(tm,Vc)1/tau*(Vo*tm-Vc);%Equation6.16%parametersforEuleralgorithminterval=10*tau;steps=[206];forj=1:length(steps)h=interval/steps(j);%createsetoftimepointstocalculatet=0:h:interval;Vc_exact=zeros(length(t),1);Vc_RK=zeros(length(t),1);%initialconditionsVc_exact(1)=0;Vc_RK(1)=0;fori=1:length(t)-1%CalculateexactsolutionVc_exact(i+1)=Vo...*(t(i+1)-tau+tau*exp(-t(i+1)/tau));%CalculateRunge-Kuttasolutionk1=f(t(i),Vc_RK(i));k2=f(t(i)+h/2,Vc_RK(i)+h/2*k1);k3=f(t(i)+h/2,Vc_RK(i)+h/2*k2);k4=f(t(i+1),Vc_RK(i)+h*k3);Vc_RK(i+1)=Vc_RK(i)+h/6*(k1+2*k2+2*k3+k4);end%plotresultssubplot(1,length(steps),j)plot(t,Vc_RK,'x',t,Vc_exact),legend('Runge-Kutta','Exact','Location','NorthWest');title('RampResponseforRCcircuit');xlabel('seconds'),ylabel('Vc(volts)');text(0.005,0.005,sprintf('%dsteps',steps(j)));%calculateglobalerrorglobal_error_RK=abs((Vc_exact-Vc_RK)./Vc_exact);fprintf('Worstcaseglobalpercenterrorfor');fprintf('Runge-Kuttafor%2dsteps:%4.2f%%\n',...steps(j),100*max(global_error_RK));end--------------------------------------------------------------------------

Page 185: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 169

PROGRAMā€‚RESULTS

WorstcaseglobalpercenterrorforRunge-Kuttafor20steps:0.23%

WorstcaseglobalpercenterrorforRunge-Kuttafor6steps:9.73%

Note that the fewer the steps, the larger the corresponding global error. Results are plotted in Figure 6.7.

6.7ā€‚ ā€‚Systemā€‚ofā€‚Twoā€‚First-Orderā€‚Differentialā€‚EquationsConsiderthefollowingtwofirst-orderODEs.

= =

= =

( , , ); (0)

( , , ); (0)

0

0

dudt

f t u v u u

dvdt

g t u v v v (6.20)

Tosolveasystemoftwofirst-orderdifferentialequationsbytheRunge-Kuttamethod,take

= + + + +

= + + + +

+

+

6( 2 2 )

6( 2 2 )

1 1 2 3 4

1 1 2 3 4

u uh

k k k k

v vh

l l l l

i i

i i

(6.21)

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

Seconds

Vc

(vol

ts)

Ramp Response for RC Circuit

20 steps

Runge-KuttaExact

0 0.005 0.010

0.02

0.04

0.06

0.08

0.1

Seconds

Vc

(vol

ts)

Ramp Response for RC Circuit

6 steps

Runge-KuttaExact

Figureā€‚6.7ā€‚ Plotā€‚ofā€‚VCā€‚versusā€‚tā€‚forā€‚RCā€‚circuitā€‚viaā€‚Runge-Kuttaā€‚method:ā€‚(a)ā€‚20ā€‚steps;ā€‚(b)ā€‚6ā€‚steps.

Page 186: Numerical and Analytical Methods with MATLAB for

170ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

where

( , , ) (estimate of at )

( , , ) (estimate of at )

2,

2,

2first estimate of at

2

2,

2,

2first estimate of at

2

2,

2,

2second estimate of at

2

2,

2,

2second estimate of at

2

( , , ) (estimate of at )

( , , ) (estimate of at )

1

1

2 1 1

2 1 1

3 2 2

3 2 2

4 3 3

4 3 3

k f t u v u t

l g t u v v t

k f t h u h k v h l u t h

l g t h u h k v h l v t h

k f t h u h k v h l u t h

l g t h u h k v h l v t h

k f t h u hk v hl u t h

l g x h u hk v hl v t h

i i i i

i i i i

i i i i

i i i i

i i i i

i i i i

i i i i

i i i i

=

=

= + + + +

= + + + +

= + + + +

= + + + +

= + + + +

= + + + +

(6.22)

and = = āˆ’+1h t t ti i .

Exampleā€‚6.3

Solve the following system of first-order differential equations by the Runge-Kutta method over the interval 0 ā‰¤ t ā‰¤ 10:

= āˆ’ =

= āˆ’ + =

āˆ’drdt

re ry f t r y

dydt

y ry g r y

t2 2 ( , , )

( , )

0.1

(6.23)

Initial conditions: r(0) = 1.0, y(0) = 3.0.

%Example_6_3.m%Thisprogramsolvesasystemof2firstorderordinary%differentialequationsbytheRunge-KuttaMethod.%First,definetwofunctionstocomputedr/dtanddy/dt:rprime_func=@(t,r,y)2.0*r*exp(-0.1*t)-2.0*r*y;yprime_func=@(r,y)-y+r*y;%Openafiletowriteresults:fo=fopen('Example_6_3_output.txt','w');fprintf(fo,'try\n');fprintf(fo,'--------------------------\n');%Definetimeintervalandstepsizetmax=10;steps=1000;h=tmax/steps;%Initialconditions:r(1)=1.0;y(1)=3.0;t(1)=0.0;

Page 187: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 171

%Estimateofderivativesandmarchingintime.fori=1:stepst(i+1)=i*h;K(1)=rprime_func(t(i),r(i),y(i));L(1)=yprime_func(r(i),y(i));K(2)=rprime_func(t(i)+h/2,r(i)+h/2*K(1),...y(i)+h/2*L(1));L(2)=yprime_func(r(i)+h/2*K(1),y(i)+h/2*L(1));K(3)=rprime_func(t(i)+h/2,r(i)+h/2*K(2),...y(i)+h/2*L(2));L(3)=yprime_func(r(i)+h/2*K(2),y(i)+h/2*L(2));K(4)=rprime_func(t(i)+h,r(i)+h*K(3),y(i)+h*L(3));L(4)=yprime_func(r(i)+h*K(3),y(i)+h*L(3));r(i+1)=r(i)+h/6*(K(1)+2*K(2)+2*K(3)+K(4));y(i+1)=y(i)+h/6*(L(1)+2*L(2)+2*L(3)+L(4));ifmod(i-1,10)==0fprintf(fo,'%.2f%10.4f%10.4f\n',t(i),r(i),y(i));endendfclose(fo);plot(t,r,t,y,'--'),xlabel('t'),ylabel('r,y');grid,legend('r','y');title('Runge-KuttaSolutionFor2nd-OrderSystem');

PROGRAMā€‚OUTPUT

The resulting MATLAB plot is shown in Figure 6.8.

0 2 4 6 8 100

0.5

1

1.5

2

2.5

3

3.5

t

r, y

Runge-Kutta Solution For 2nd-Order System

ry

Figureā€‚6.8ā€‚ Solutionā€‚ofā€‚twoā€‚first-orderā€‚differentialā€‚equationsā€‚byā€‚theā€‚Runge-Kuttaā€‚method.

Page 188: Numerical and Analytical Methods with MATLAB for

172ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6.8ā€‚ ā€‚Aā€‚Singleā€‚Second-Orderā€‚EquationForasinglesecond-orderODE,themethodofsolutionistoreducetheequationtoasystemoftwofirst-orderequations.Giventhefollowingsecond-orderdifferentialequationwithinitialconditions

= =

= =

( , , )

(0) and (0)

2

2

0 0

ud udt

f t u u

u u u u (6.24)

Let =u v,then = = = ( , , )udvdt

v f t u v .Also, = =( , , )u g t u v v ,giving

=

= ( , , )

u v

v f t u v (6.25)

Thus,wehaveconvertedEquations(6.24)intotwofirst-orderdifferentialequa-tionsofthesameformasEquations(6.20);thus,thesamesolutiontechniquescanbeapplied,thatis,

=

= =

= + + + +

= + = + +

= + + + +

= + = + +

= + + + +

= + = + +

( , , ) ( at )

( ) ( at )

2,

2,

2first estimate of at

2

2 2first estimate of at

2

2,

2,

2second estimate of at

2

2 2second estimate of at

2

( , , ) (estimate of at )

( ) (estimate of at )

1

1

2 1 1

2 1

3 2 2

3 2

4 3 3

4 3

k f t u v v t

l u t v u t

k f th

uhl v

hk v t

h

l u th

vhk u t

h

k f th

uhl v

hk v t

h

l u th

vhk u t

h

k f t h u h l v hk v t h

l u t h v hk u t h

i i i i

i i i

i i i i

i i i

i i i i

i i i

i i i i

i i i

Page 189: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 173

Thevaluesofu andv atthenexttimesteparegivenby

( )

( )

= + + + +

= + + + +

+

+

62 2

62 2

1 1 2 3 4

1 1 2 3 4

u uh

l l l l

v vh

k k k k

i i

i i

Exampleā€‚6.4

We illustrate this method by applying it to the series RLC circuit of Appendix A. Equation (A.6) gives the capacitor voltage vC (with no driving voltage) as

+ + =

d vdt

RLdvdt LC

vC CC

10

2

2

We wish to solve for vC for the component values R = 10 Ī©, L = 1 mH, C =

2 Ī¼F, and initial conditions =vC (0) 10 and =dvdt LCC (0)

6.

We first reduce this single second-order differential equation into two first-order equations.

Let =dvdt

vC2 . Then, the two coupled equations are

=

= = āˆ’ āˆ’

dvdt

v

dvdt

d vdt LC

vRLv

C

CC

1

2

22

2 2

Assuming an underdamped system, the exact solution has the form

= āˆ’ Ī± āˆ’ +Ī² āˆ’vRLt

LCRL

tLC

RL

tC exp2

cos1

2sin

12

2 2

For the given initial conditions, Ī± = 0 and Ī² =

āˆ’

dvdt

LCRL

C (0)

12

2.

Page 190: Numerical and Analytical Methods with MATLAB for

174ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

The program follows:

%Example_6_4.m%Thisprogramsolvesasinglesecondorderordinary%differentialequationbytheRunge-KuttaMethod.The%differentialequationdescribesthecapacitorvoltage%inaseriesRLCcircuitclear;clc;%Componentvalues:R=10;L=1.0e-3;C=2.0e-6;%Initialconditions:vc(1)=0;v2(1)=6*sqrt(1/(L*C));%Definetimeintervalandstepsize.Sincethenatural%frequencysqrt(1/LC)is3559Hz,chooseatimeinterval%tocaptureseveraloscillations.3559Hzhasperiodof%281usec,sochoose1000usecforinterval.tmax=1000e-6;steps=100;h=tmax/steps;t=0:h:tmax;%Definev2'=f(t,x,y):v2_prime=@(t,x,y)-(1/(L*C))*x-(R/L)*y;%DoRunge-Kuttaalgorithm:fori=1:stepsK1=v2_prime(t(i),vc(i),v2(i));L1=v2(i);K2=v2_prime(t(i),vc(i)+h/2*L1,v2(i)+h/2*K1);L2=v2(i)+h/2*K1;K3=v2_prime(t(i),vc(i)+h/2*L2,v2(i)+h/2*K2);L3=v2(i)+h/2*K2;K4=v2_prime(t(i),vc(i)+h*L3,v2(i)+h*K3);L4=v2(i)+h*K3;vc(i+1)=vc(i)+h/6*(L1+2*L2+2*L3+L4);v2(i+1)=v2(i)+h/6*(K1+2*K2+2*K3+K4);end%Calculateexactsolutionbeta=v2(1)/sqrt(1/(L*C)-(R/(2*L))^2);vc_exact=exp(-R/(2*L)*t)*beta....*sin(sqrt(1/(L*C)-(R/(2*L))^2)*t);%Printresultstoscreen.fprintf('Runge-Kuttasolutionforasingle');fprintf('secondorderODE:\n\n');fprintf('tR-KSol''nExactSol''n\n');fprintf('-------------------------------------\n');fori=1:10:steps+1%justprinteverytenthstepfprintf('%10.3e%8.4f%8.4f\n',...t(i),vc(i),vc_exact(i));end%Plotresults:plot(t,vc_exact,t,vc,'x');xlabel('t(seconds)'),ylabel('volts');title('CapacitorvoltageofseriesRLCcircuit');legend('Exact','Runge-Kutta');

--------------------------------------------------------------------------

A comparison of the Runge-Kutta solution with the exact solution is shown in Figure 6.9.

Page 191: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 175

6.9ā€‚ ā€‚MATLABā€™sā€‚ODEā€‚FunctionMATLAB has several built-in ODE functions that solve a system of first-orderODEs, includingode23 andode45. In this chapter,wedemonstrateode45,which is based on fourth- and fifth-order Runge-Kutta methods. A descriptionoftheode45functionfollows(thisdescriptioncanbeobtainedbytypinghelp ode45intheCommandwindow):

ODE45Solvenon-stiffdifferentialequations,mediumordermethod. [TOUT,YOUT]=ODE45(ODEFUN,TSPAN,Y0)withTSPAN=[T0

TFINAL]integratesthesystemofdifferentialequationsy'=f(t,y)fromtimeT0toTFINALwithinitialconditionsY0.ODEFUNisafunctionhandle.ForascalarTandavectorY,ODEFUN(T,Y)mustreturnacolumnvectorcorrespondingtof(t,y).EachrowinthesolutionarrayYOUTcorrespondstoatimereturnedinthecolumnvectorTOUT.ToobtainsolutionsatspecifictimesT0,T1,...,TFINAL(allincreasingoralldecreasing),useTSPAN=[T0T1...TFINAL].

0 0.2 0.4 0.6 0.8 1

Ɨ 10ā€“3

ā€“3

ā€“2

ā€“1

0

1

2

3

4

5

t (seconds)

Vol

tsCapacitor Voltage of Series RLC Circuit

ExactRunge-Kutta

Figureā€‚6.9ā€‚ Solutionā€‚ofā€‚aā€‚singleā€‚second-orderā€‚differentialā€‚equationā€‚byā€‚theā€‚Runge-Kuttaā€‚method.

Page 192: Numerical and Analytical Methods with MATLAB for

176ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus,ode45takesasargumentsahandletoafunctiondescribingthedifferentialequations(ODEFUN),avectordescribingatimeinterval(TSPAN),andavectordescrib-ingtheinitialconditions(Y0).ThefunctionODEFUNmusttaketwoarguments:atimetandavectorofvalues , ,...,1 2y y yn ,tobepassedtothedifferentialequations.Thesystemofndifferentialequationsmustbeinstandardform,thatis,nequationsoftheform = ( , , ,..., )1 2y f t y y yn n .ODEFUNmustreturnavectorofderivativesofthe form , ,...,1 2y y yn .The time intervalTSPAN is typically a two-element vectorcontainingastartandendtime;ode45willautomaticallychooseanappropriatetimestep(andmightevenvarythetimestepwithintheinterval).ode45willreturntwovectors:alistoftimepointsTOUTandthesolutionYOUTateachtimepoint.Ifyouwanttoforceode45tosolvethesystematspecifictimepoints,thenyoucanexplicitlyspecifythetimepointsinTSPAN(insteadofjustthestartandendtimepoints).

Exampleā€‚6.5

Solve the following system of three first-order differential equations using MATLABā€™s ode45 function:

=

= āˆ’

= āˆ’

y y y t

y y y

y y y0.51

1 2 3

2 1 3

3 1 2

Initial conditions: =y (0) 01 , =y (0) 1.02 , and =y t( ) 1.03 .

%Example_6_5.m%Thisprogramsolvesasystemof3ordinarydifferential%equationsbyusingMATLAB'sode45function.%y1'=y2*y3*t,y2'=-y1*y3,y3'=-0.51*y1*y2%y1(0)=0,y2(0)=1.0,y3(0)=1.0clear;clc;initial=[0.01.01.0];tspan=0.0:0.1:10.0;[t,Y]=ode45(@dydt3,tspan,initial);y1=Y(:,1);y2=Y(:,2);y3=Y(:,3);fid=fopen('output.txt','w');fprintf(fid,'ty1y2y3\n');fprintf(fid,'-------------------------------------\n');fori=1:2:101fprintf(fid,'%6.2f%8.4f%8.4f%8.4f\n',...t(i),y1(i),y2(i),y3(i));endfclose(fid);plot(t,y1,t,y2,'-.',t,y3,'--');xlabel('t'),ylabel('y1,y2,y3');title('(y1,y2,y3)vs.t'),grid;

Page 193: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 177

text(5.2,-0.8,'y1'),text(7.7,-0.25,'y2');text(4.2,0.85,'y3');

--------------------------------------------------------------------------

%dydt3.m%ThisfunctionworkswithExample_6_5.m%y1'=y2*y3*t,y2'=-y1*y3,y3'=-0.51*y1*y2%y1=Y(1),y2=Y(2),y3=Y(3).functionYprime=dydt3(t,Y)Yprime=zeros(3,1);Yprime(1)=Y(2)*Y(3)*t;Yprime(2)=-Y(1)*Y(3);Yprime(3)=-0.51*Y(1)*Y(2);

PROGRAMā€‚RESULTS

The calculated solutions for y1, y2 , and y3 are shown in Figure 6.10.

Exampleā€‚6.6

Solve the parallel RLC circuit of Section 2.17 using MATLABā€™s ode45 func-tion. Assume = = = = =R L C v iL50 , 1 H, 10 nF, (0) 3.3V, (0) 0 A . Plot the results for 0 ā‰¤ t ā‰¤ 4 Ī¼sec.

0 2 4 6 8 10ā€“2

ā€“1.5

ā€“1

ā€“0.5

0

0.5

1

1.5

2

t

y1, y

2, y

3(y1, y2, y3) vs. t

y1

y2

y3

Figureā€‚6.10ā€‚ Solutionā€‚ofā€‚threeā€‚differentialā€‚equationsā€‚byā€‚MATLABā€™sā€‚ode45ā€‚function.

Page 194: Numerical and Analytical Methods with MATLAB for

178ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%Example_6_6.m%Solveasystemoftwofirst-orderordinarydifferential%equations(Equations2.6and2.7).%Assume:y(1)=vandy(2)=iL%Assume:R=50,L=1e-6,C=10e-9,v(t=0)=3.3,i(t=0)=0.%Equation2.6:yprime(2)=(1/L)*y(1)%Equation2.7:yprime(1)=-1/(R*C)*y(1)-(1/C)*y(2)clear;clc;initial=[3.30];tspan=0:.01e-6:4e-6;[t,y]=ode45('dydt_rlc',tspan,initial);v=y(:,1);iL=y(:,2);fprintf('tviL\n');fprintf('---------------------------------------\n');%printeverytenthvalueofvandiLfori=1:10:length(t)fprintf('%1.10f%10.4f%10.4f\n',...t(i),v(i),iL(i));end%PlotvandiLtogether.Useplotyy()tocreatea%second'y'axisontherightside.plotyy()returns%graphicshandlestotheaxesandlinessothattheir%stylecanbeadjusted.[axis,line1,line2]=plotyy(t,v,t,iL);xlabel('t'),ylabel('v(volts)');title('vandiLvs.t'),grid;%setlabelforright'y'axisset(get(axis(2),'Ylabel'),'String','i_L(amps)');%plotiLwithadashedlineset(line2,'LineStyle','--');legend('v','i_L');

--------------------------------------------------------------------------

%dydt_rlc.m%ThisfunctionworkswithExample_6_6.m%Assume:v=y(1)andiL=y(2)functionyprime=dydt_rlc(t,y)yprime=zeros(2,1);R=50;L=1e-6;C=10e-9;yprime(1)=-1/(R*C)*y(1)-1/C*y(2);yprime(2)=(1/L)*y(1);

PROGRAMā€‚RESULTS

The results are plotted in Figure 6.11. Note the complementary nature of v(t) and iL(t) such that when either is zero, the other is always near a maximum. This behavior demonstrates how the energy in the RLC circuit oscillates back and forth between the capacitor and inductor.

Page 195: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 179

6.10ā€‚ ā€‚Boundaryā€‚Valueā€‚ProblemsWhen an ODE involves boundary conditions instead of initial conditions, thenweuseadifferentapproachtosolvetheproblem.Inaboundaryvalueproblem,weessentiallyneedtoā€œfitā€asolutionintotheknownboundaryconditionsasopposedtosimplyintegratingfromtheinitialconditions.Anexampleofthistypeofproblemistodeterminetheelectricfieldbetweentheplatesofacapacitorwithaknownchargedensitybetweentheplatesandafixedvoltageacrosstheplates.Thefixedvoltageistheboundarycondition,andthesolutionmaybefoundbynumericallysolvingasecond-order,nonhomogeneousODEusingfinite difference formulas.Withcertaintypesofboundaryconditions,thenumericalmethodwillreducetosolvingasetoflinearequationsthatfallintothecategoryofatri-diagonalmatrix.Thesolutionofasetoflinearalgebraicequationsthatareclassifiedasatri-diagonalsysteminvolvesfewercalculationsthanthesolutionbytheGausseliminationmethoddescribedinChapter3,whichisimportantifthesystemofequationsislarge.Thesolutionofatri-diagonalsystemisdiscussednext.

0 0.5 1 1.5 2 2.5 3 3.5 4Ɨ 10ā€“6

ā€“4

ā€“2

0

2

4

t

v (v

olts

)

v and iL vs. t

ā€“0.4

ā€“0.2

0

0.2

0.4

i L (

amps

)

viL

Figureā€‚6.11ā€‚ Solutionā€‚ofā€‚RLCā€‚circuitā€‚withā€‚theā€‚ode45ā€‚function.

Page 196: Numerical and Analytical Methods with MATLAB for

180ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6.11ā€‚ ā€‚Solutionā€‚ofā€‚aā€‚Tri-Diagonalā€‚Systemā€‚ofā€‚Linearā€‚Equations

Atri-diagonalsystemofequationshasthefollowingform:

āˆ’

āˆ’ āˆ’

āˆ’ āˆ’

āˆ’ āˆ’

āˆ’

=

1 0 0 01 0 0

0 1 00 0 10 0 0 1

1

2 2

3 3

4 4

5

1

2

3

4

5

1

2

3

4

5

ab a

b ab a

b

xxxxx

ccccc

(6.26)

whereai,bi,andciareconstantterms,andxiaretheunknowns.Thetermtri-diag-onalreferstothefactthattheelementsofthecoefficientmatrixontheleftsideofEquation(6.26)isnonzeroforthemaindiagonalandthediagonalsimmediatelyaboveandbelowthemaindiagonal.Asidefromthethreediagonals,therestoftheelementsinthecoefficientmatrixareallzero.BymultiplyingoutthematricesinEquation(6.26),thesetofequationsforthisfifth-ordersystembecomes

āˆ’ =1 1 2 1x a x c (6.27)

āˆ’ + āˆ’ =2 1 2 2 3 2b x x a x c (6.28)

āˆ’ + āˆ’ =3 2 3 3 4 3b x x a x c (6.29)

āˆ’ + āˆ’ =4 3 4 4 5 4b x x a x c (6.30)

āˆ’ + =5 4 5 5b x x c (6.31)

Thegeneralconceptforsolvingatri-diagonalsystemisasfollows:

We can solve Equation (6.27) for x1 and substitute the result into Equation(6.28),givinganequationinvolvingonlyx2andx3,whichwedesignateasEquation(6.28ā€²).

WecanthensolveEquation(6.28ā€²)forthex2intermsofx3andsubstitutetheresultintoEquation(6.29).Thisgivesanequationonlyinvolvingx3andx4,whichwedesignateasEquation(6.29ā€²).

Thisprocess iscontinueduntil the lastequation.Whenx4 is substituted intoEquation(6.31),anequationonlyinvolvingx5isobtained,thusallowingustosolvealgebraicallyforx5.

Then,bybacksubstitution,wecanobtainalltheotherxivalues.

Page 197: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 181

Method Summary for m equationsArrangethesetofequationsintothegeneralform

= + ++ āˆ’1 1x a x b x ci i i i i i (6.32)

Note:forthefirstandlastequations(correspondingtotheupper-leftandlower-rightcoefficientsinthetri-diagonalmatrix), = 01b and = 0am .

Bythesubstitutionprocedureoutlined,wecanobtainasetofequationsoftheform

= + +1x d e xi i i i (6.33)

wherediandeiarethecoefficientsfortheā€œprimeā€equations.Notethatem=0.Then,

=

= +

= +

āˆ’ āˆ’ āˆ’1 1 1

1 1 1 2

x d

x d e x

x d e x

m m

m m m m

(6.34)

Ifgeneralexpressionsfordiandeicanbeobtained,thenwecansolvethesystemforallxi.

WestartbyrewritingEquation(6.33)toputthe(i ā€“1)thequationintotheform

= +āˆ’ āˆ’ āˆ’1 1 1x d e xi i i i (6.35)

SubstitutingEquation(6.35)in(6.32)gives

= + + ++ āˆ’ āˆ’( )1 1 1x a x b d e x ci i i i i i i i

Solvingforxigives

=

+āˆ’

+āˆ’

āˆ’

āˆ’

+

āˆ’

( )(1 ) (1 )

1

1

1

1x

c b db e

a xb ei

i i i

i i

i i

i i (6.36)

MatchingtermsbetweenEquations(6.36)and(6.33),weobtain

=+āˆ’

=āˆ’

āˆ’

āˆ’

āˆ’

1

1

1

1

1

dc b d

b e

eab e

ii i i

i i

ii

i i (6.37)

whichisvalidfori =2,3,ā€¦,m.

Page 198: Numerical and Analytical Methods with MATLAB for

182ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Theveryfirstequationinthesystemisalreadyintheform = + āˆ’1x d e xi i i i ;thus,matchingtermsbetweenEquations(6.27)and(6.33),weobtain

=

=

1 1

1 1

d c

e a (6.38)

We can now successively apply Equation (6.37) to find ā€¦, , ,2 3d d dm andā€¦, , ,2 3e e em .

Then, =x dm m ,andbybacksubstitution

= +

= +

= +

āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’ āˆ’

1 1 1

2 2 2 1

1 1 1 2

x d e x

x d e x

x d e x

m m m m

m m m m

Exampleā€‚6.7

Solve the following system of equations for all xi:

+ =+ + = āˆ’

+ āˆ’ =āˆ’ + + =

+ āˆ’ = āˆ’+ =

x xx x x

x x xx x x

x x xx x

2 7 (6.39)4 3 14 9 (6.40)

11 6 3 (6.41)3 2 31 1 (6.42)

4 8 19 (6.43)20 11 (6.44)

1 2

1 2 3

2 3 4

3 4 5

4 5 6

5 6

First, we need to put the equations in the form of Equation (6.32), which is

= + ++ āˆ’x a x b x ci i i i i i1 1

This gives

=āˆ’ +x x2 71 2

=āˆ’ āˆ’ āˆ’x x x

143

43

93

2 3 1

= āˆ’ +x x x6 11 33 4 2

=āˆ’ + +x x x

312

32

12

4 5 3

= āˆ’ āˆ’x x x8 4 195 6 4

=āˆ’ +x x20 116 5

Page 199: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 183

We see that

= āˆ’ āˆ’ āˆ’

= āˆ’ āˆ’ āˆ’ āˆ’

= āˆ’ āˆ’

a

b

c

2 14 / 3 6 31/ 2 8 0

0 4 / 3 11 3 / 2 4 20

7 3 3 1/ 2 19 11

A MATLAB program to solve Equations (6.39)ā€“(6.44) for all xi follows:

%Example_6_7.m%Exampleofsolvingatri-diagonalsystemofequationsa=[-2-14/36-31/280];b=[0-4/3-113/2-4-20];c=[7-331/2-1911];m=length(a);%Computedandecoefficients:d(1)=c(1);e(1)=a(1);fori=2:md(i)=(c(i)+b(i)*d(i-1))/(1-b(i)*e(i-1));e(i)=a(i)/(1-b(i)*e(i-1));end%Computex:x(m)=d(m);fori=(m-1):-1:1x(i)=d(i)+e(i)*x(i+1);end%Displaythesolution:x

PROGRAMā€‚RESULTSx= 37.3362-15.1681-8.0600-29.65151.1653-12.3051

Note that the example contains only arithmetic operations and no expensive matrix operations (e.g., solving by Gauss elimination or finding an inverse matrix). Thus, the algorithm will be extremely fast, even for systems with many equations (e.g., order of m = 1000 or more).

6.12ā€‚ ā€‚Differenceā€‚FormulasTo solve a boundary value problem involving an ordinary, linear differentialequationnumerically,weneed thedifference formulasobtainedbyTaylor seriesexpansion.Thiswillenableustoreducedifferentialequationstoasetofalgebraic

Page 200: Numerical and Analytical Methods with MATLAB for

184ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

equations.AswesawinSection6.3,wecanexpandy =g(x)inaTaylorseriesexpan-sionaboutpointxi,thatis,

( ) ( )= + āˆ’ + āˆ’ + āˆ’ +( ) ( ) ( )( ) ( )

2!( )3!

2 3y x y x y x x xy x

x xy x

x xi i ii

ii

i

Wedefinethestepsize = āˆ’h x xi ,whichgives

+ = + + + +( ) ( ) ( ) ( )

2!( )3!

2 3y x h y x y x hy x

hy x

hi i ii i

Let + = +( ) 1y x h yi i and =( )y x yi i , =( )y x yi i ,andsoon.Then,theTaylorseriesexpansionequationcanbewrittenas

= + + + ++ 2! 3!1

2 3

y y y hy h y h

i i ii i (6.45)

WenowrewriteEquation(6.45)forthepoint = āˆ’x x hi ,thatis,theequidis-tantpointontheothersideofxi.Thisgives

āˆ’ = = + āˆ’ + āˆ’ + āˆ’ +āˆ’( ) ( )

2!( )

3!( )1

2 3y x h y y y hy

hy

hi i i ii i

or

= āˆ’ + āˆ’ + āˆ’āˆ’ 2! 3!1

2 3

y y y hy h y h

i i ii i (6.46)

WeuseEquations(6.45)and(6.46)toderiveseveraldifferenceformulas.WestartbyusingthefirsttwotermsofEquation(6.45):

= ++1y y y hi i i

Solvingfor yi gives

=

āˆ’+1yy y

hii i (6.47)

Thisistheforwarddifferenceformulafor yi witherroroforderh. Similarly,fromEquation(6.46),usingthefirsttwotermsintheexpansiongives

=

āˆ’ āˆ’1yy y

hii i (6.48)

Thisisthebackwarddifferenceformulafor yi witherroroforderh.

Page 201: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 185

Now,letussubtractEquation(6.46)fromEquation(6.45)andkeepthefirstthreetermsineachequation.Thisgives

āˆ’ =+ āˆ’ 21 1y y y hi i i

Solvingfor yi gives

=

āˆ’+ āˆ’

21 1y

y yhi

i i (6.49)

Thisisthecentraldifferenceformulafor yi withanerroroforder 2h (theerrorisorder2h becausethreetermsintheTaylorserieswereusedtoobtaintheformula).Ifweadd

Equations(6.45)and(6.46)andkeepthefirstthreetermsineachequation,weobtain

+ = ++ āˆ’ 21 12y y y y hi i i i

Solvingfor yi gives

=

+ āˆ’+ āˆ’ 21 12y

y y yhi

i i i (6.50)

Thisisthecentraldifferenceformulafor yi witherroroforder 2h .The four difference formulas derived are summarized in Table 6.1. We now

showhowtheyareappliedtomodelaboundaryvalueproblemthatleadstoatri-diagonalsystemoflinearequations.

Table 6.1ā€‚ Summaryā€‚ofā€‚Finiteā€‚Differenceā€‚Formulasā€‚forā€‚Boundaryā€‚Valueā€‚Problems

=āˆ’+y

y yh

ii i1

First-order forward difference formula. Used for yā€™ boundary condition at beginning of the domain.

=āˆ’ āˆ’y

y yh

ii i 1

First-order backward difference formula. Used for yā€™ boundary condition at end of the domain.

=āˆ’+ āˆ’y

y yh2

ii i1 1

First-order central difference formula. Used for first-order differential equation at interior points.

=+ āˆ’+ āˆ’y

y y yh

2i

i i i1 12

Second-order central difference formula. Used for second-order differential equation at interior points.

Page 202: Numerical and Analytical Methods with MATLAB for

186ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6.13ā€‚ ā€‚One-Dimensionalā€‚Plateā€‚Capacitorā€‚ProblemFigure 6.12showsaparallelplatecapacitorwithconstantappliedvoltageVoandafixedchargedensityĻbetweentheplates.Forcaseswithplanarsymmetrysuchastheparallelplatecapacitorforwhichthechargedensityonlychangesinthexdirection(i.e.,thereisnoyorzdependency),thenPoissonā€™sequationdescribingtheelectricpotentialĪ¦reducestoanODE:

Ī¦=āˆ’ĻĪµ

( ) ( )2

2d xdx

x (6.51)

whereĪ¦(x)istheelectricpotential(involts),Ļ(x)isthex-dependentchargedensity(inC/m3),andĪµisthedielectricconstantforthematerialbetweentheplates.

Exampleā€‚6.8

Solve for Ī¦(x) between the plates of the capacitor of Figure 6.12 with a plate separation of D meters, Ļ = Ļ āˆ’x x Do( ) ( )2 , and boundary conditions Ī¦(0) = 0 and Ī¦ =D Vo( ) .

Substituting the expression for Ļ(x) into Equation (6.51), we obtain

Ī¦=āˆ’ĻĪµ

āˆ’ =āˆ’ĻĪµ

āˆ’ +ddx

x D x Dx Do o( ) ( 2 )2

22 2 2 (6.52)

Conducting plates

Material betweenplates with dielectric Īµand charge density Ļ(x)

Vo

+

āˆ’Dx

Figureā€‚6.12ā€‚ Parallelā€‚plateā€‚capacitorā€‚withā€‚plateā€‚separationā€‚ofā€‚Dā€‚metersā€‚andā€‚fixedā€‚chargedā€‚densityā€‚Ļ(x)ā€‚C/m3ā€‚betweenā€‚theā€‚plates.

Page 203: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 187

As we did for the RC circuit in this chapter, we solve Equation (6.52) using both classical and numerical techniques and then compare the solu-tions. We can solve this simple differential equation by integrating twice on both sides, giving

Ī¦ =

āˆ’ĻĪµ

āˆ’ + + Ī± + Ī²x xDx

Dx xo( )

112 3 2

4 32

2 (6.53)

where Ī± and Ī² are constants of integration that are determined by applying the boundary conditions. Applying the first boundary condition Ī¦(0) = 0 gives

=āˆ’ĻĪµ

āˆ’ + + Ī± + Ī²D Do0

112

030

20 04 3

22

Thus, Ī² = 0.

For the second boundary condition Ī¦ =D Vo( ) , we get

=āˆ’ĻĪµ

āˆ’ + + Ī±V DD

DD

d Doo 1

12 3 24

33

22

Solving for Ī± gives

Ī± =

āˆ’ĪµĻ

āˆ’V

DDo

o 4

3

Thus, the exact solution to Equation (6.52) is

Ī¦ =

āˆ’ĻĪµ

āˆ’ + āˆ’ĪµĻ

+x xDx

Dx

VD

Dxo o

o( )

112 3 2 4

4 32

23

(6.54)

To solve Equation (6.52) numerically, we subdivide the region between the plates into N intervals and apply the finite difference formulas of Table 6.1. Dividing the region 0 ā‰¤ x ā‰¤ D into N intervals will result in N + 1 values for x and thus N + 1 values for Ī¦. Our goal is to determine the coef-ficients in an (N + 1) Ɨ (N + 1) tri-diagonal matrix.

We begin by applying the second-order central difference formula from Table 6.1 to Equation (6.52), giving

( )Ī¦ =

Ī¦ + Ī¦ āˆ’ Ī¦=āˆ’ĻĪµ

āˆ’ ++ āˆ’

hx Dx Di

i i i oi i

221 1

22 2

Solving for Ī¦i gives

( )Ī¦ = Ī¦ + Ī¦ +

ĻĪµ

āˆ’ ++ āˆ’h

x Dx Di i io

i i12

12 2

21 1

22 2 (6.55)

Page 204: Numerical and Analytical Methods with MATLAB for

188ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

This equation is valid for i = 2, 3, 4, ā€¦ , N. Note that Equation (6.55) is in the same general form as Equation (6.32). We can identify the elements of a tri-diagonal matrix as

=ai12,

=bi12,

( )=ĻĪµ

āˆ’ +ch

x Dx Dio

i i2

22

2 2

We now use the boundary conditions to determine the values for the upper-left and lower-right corners of the coefficient matrix. First, we rewrite the boundary conditions as

Ī¦ = ā†’ Ī¦ =(0) 0 01 (6.56)

Ī¦ = ā†’ Ī¦ =+D V Vo N o( ) 1 (6.57)

Equation (6.56) gives

= = =a b c 01 1 1

Equation (6.57) gives

= = =+ + +a b c VN N N o0, 0,1 1 1

A MATLAB program to solve Equation (6.51) numerically follows:

%Example_6_8.m%Findtheelectricpotentialbetweenaparallelplate%capacitorwithfixedchargedensitybetweentheplates%andknownboundaryconditions.clc;clear;N=40;%stepcountD=.0004;%plateseparation(meters)h=D/N;%stepsizerho_o=1e4;%coulomb/m^3epsilon=1.04e-12;%dielectricbetweentheplatesVo=5;%voltageacrossplates%First,calculateallvaluesofx.Alsocalculate%theexactsolution.x=0:h:D;%Calculateexactsolution(Equation6.54)phi_exact=(-rho_o/epsilon)*(x.^4/12-(D/3)*x.^3...+(D^2/2)*x.^2-((epsilon*Vo/(D*rho_o))+(D^3/4))*x);%Next,solvenumericallyusingatri-diagonalmatrix.%Define'a','b',and'c'vectors:a=.5*ones(1,N+1);b=.5*ones(1,N+1);c=(rho_o*h^2/(2*epsilon))*(x.^2-2*D*x+D^2);%Setboundaryconditionsfor'a','b',and'c'vectorsa(1)=0;b(1)=0;c(1)=0;a(N+1)=0;b(N+1)=0;c(N+1)=Vo;%Solvetri-diagonalmatrixbycalculating"d"and%"e"vectorsd(1)=c(1);e(1)=a(1);fori=2:N+1d(i)=(c(i)+b(i)*d(i-1))/(1-b(i)*e(i-1));

Page 205: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 189

e(i)=a(i)/(1-b(i)*e(i-1));end%calculatephibasedondande,alsocalculate%globalerrorphi(N+1)=d(N+1);fori=N:-1:1phi(i)=d(i)+e(i)*phi(i+1);end%Plotnumericalandexactsolutionsforphi:plot(x,phi,'x',x,phi_exact);xlabel('\itx(meters)'),ylabel('\Phi(volts)');grid;legend('numericalsolution','exactsolution',...'Location','SouthEast');%Findworst-caseglobalerror:error=abs((phi-phi_exact)./phi_exact);fprintf('Maxglobalerrorfor%dsteps:%5.3f%%\n',...N,100*max(error));

--------------------------------------------------------------------------

PROGRAMā€‚RESULTSMaximumglobalerrorfor40steps:0.029%

The MATLAB plot of Ī¦ as a function of x is shown in Figure 6.13.

0 1 2 3 4

x 10-4

0

2

4

6

8

10

12

x (meters)

Ī¦ (

volts

)

numerical solutionexact solution

Figureā€‚ 6.13ā€‚ Plotā€‚ ofā€‚ theā€‚ electricā€‚ potentialā€‚ Ī¦(x)ā€‚ betweenā€‚ theā€‚ plates,ā€‚ includingā€‚exactā€‚solutionā€‚andā€‚finiteā€‚differenceā€‚solutionā€‚forā€‚N =ā€‚40.

Page 206: Numerical and Analytical Methods with MATLAB for

190ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ProjectsProject.6.1

SolvetheRCcircuitofFigure 6.4forvC(t)wherethedrivingvoltagehasthefol-lowingform:

=

Ļ‰ ā‰„

<( )

sin 00 0

V tV t t

tD

o

Assumetheinitialcondition =(0) 0vC andparametervaluesR =1kĪ©,C =1Ī¼F,Ļ‰ =2000rad/sec,andVo=10V.

1. FindtheexactsolutionforvC(t)byassumingaparticularsolutionoftheform= Ī± Ļ‰ +Ī² Ļ‰( ) sin cos,v t t tC P and using Equation (6.14) for the homogenous

equationsolution,whichis = Ī³ āˆ’ Ļ„,

/v eC Ht .SolvefortheconstantsbyĪ±,Ī²,and

Ī³bysubstitutingback intothegoverningdifferentialequationandapplyingtheinitialcondition.

2. UsetheEuleralgorithmtosolvenumericallyforvC(t).Solveovertheintervalt =[0,5]mswithatimestepof0.1ms.

3. UsetheModifiedEuleralgorithmtosolvenumericallyforvC(t)forthesameintervalaspart2.

4. OnonegraphplotvC(t)versustobtainedbyboththeEulermethodandtheexactsolution.Onaseparategraph,plotvC(t)versustobtainedbothbythemodifiedEulermethodandtheexactsolution.

5. Increase the step size in your numerical solutions until you start to seeinstability.Whatisareasonableruleofthumbtoensurenumericalstabilityinthisfirst-ordersystemwithsinusoidalinput?

Project.6.2

FigureP6.2ashowsathird-orderRLCcircuit.Torunatime-domaintransientanal-ysis,wetransformthecircuitintodifferentialequationsusingthefollowingmethod:

RL

iL iC2iC1

1

C2C1

vS

+

āˆ’vL

+

āˆ’

vR

+

āˆ’

iR

2

VC1+ āˆ’VC2āˆ’ + 21

Figureā€‚P6.2aā€‚ Third-orderā€‚RLCCā€‚circuitā€‚containingā€‚twoā€‚capacitorsā€‚andā€‚anā€‚inductor.

Page 207: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 191

First,writeKirchhoffā€™scurrentlawforeachnodeinthecircuit:

atnode1: + āˆ’ = 01 2i i iC C L (P6.2a)

atnode2: + = 02i iR C (P6.2b)

Second,writeKirchhoffā€™svoltagelawforthetwoloopsinthecircuit:

forloop1: āˆ’ āˆ’ = 01v v vS C L (P6.2c)

forloop2: + āˆ’ = 02v v vL C R (P6.2d)

Third,writetheconstituentrelationsforeachcircuitelement:

for 1C : =1 1 1i C vC C (P6.2e)

for 2C : =2 2 2i C vC C (P6.2f)

forL: =v LiL L (P6.2g)

forR: =v i RR R (P6.2h)

Wechoosethethreevoltagesandcurrentswithderivativeterms(vC1,vC2,andiL )asthestate variablesforthisproblem.

1. Rearrangeequations(P6.2a)ā€“(P6.2h)intothefollowingstandardform:

= ( , , , ( ))1

1 2dvdt

f v v i v tCC C L S (P6.2i)

= ( , , , ( ))2

1 2dvdt

g v v i v tCC C L S (P6.2j)

= ( , , , ( ))1 2

didt

h v v i v tLC C L S (P6.2k)

wherethefunctionsf,gandhinvolveparametersC1,C2,L,andR.

0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

vS(t)

5 V

t (Ī¼sec)

Figureā€‚P6.2bā€‚ Inputā€‚pulseā€‚forā€‚theā€‚RLCCā€‚circuit.

Page 208: Numerical and Analytical Methods with MATLAB for

192ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

2. SolveEquations(P6.2i)ā€“(P6.2k)withtheRunge-Kuttaalgorithmforthefol-lowingcircuitparameters:C1=1Ī¼F,C2=0.001Ī¼F,R=100kĪ©,L=0.01mH.Useatimeintervalof0ā‰¤t ā‰¤10Ī¼sandastepsizeof0.01Ī¼s.Assumevs(t)isa5-Vpulsestartingattimet=0withrisetimeof0.1Ī¼s,anā€œonā€timeof0.8Ī¼s,andfalltimeof0.1Ī¼s(asshowninFigureP6.2b).Initialconditions:

=(0) 01vC , =(0) 02vC ,and =(0) 0iL . 3. Plotonseparategraphs: ( ), ( ), ( ) and ( )1 2v t v t i t v tC C L S versustime.

Project.6.3

TheSallen-Keycircuit(FigureP6.3)iscommonlyusedtoimplementsecond-order(orhigher)filters.Althoughthereareseveralwaystomodelthiscircuit,weanalyzeitheredirectlyinthetimedomainusingdifferentialequations.Ifweassumethattheopampisideal,thenv2=voutandi5=0.ApplyingKirchhoffā€™scurrentlawatthenodeslabeledv1andv2andusingtheconstituentrelationsforresistors(vR=

iRR)andcapacitors =i CdvdtCC ,weget

Atnode 1v : + + =āˆ’

+āˆ’

+āˆ’

=0 ( ) 01 2 31

1

2 1

21

1i i iv vR

v vR

Cd v v

dtin out

Atnode 2v : + =āˆ’

+ =0 02 42 1

22

2i iv vR

Cdvdt

Rearrangingintoasystemoftwofirst-orderODEsandsetting =2v vout ,weget

=

āˆ’+

1 12 2 2 2

1dvdt R C

vR C

voutout (P6.3a)

= āˆ’ + āˆ’ āˆ’ +

1 1 1 1 1 11

2 1 2 2 2 2 1 1 2 11

1 1

dvdt R C R C

vR C RC R C

vRC

vout in

(P6.3b)

+ā€“i4

i3

i2i1C2

C1

R1 R2vin vouti5

v2v1

Figureā€‚P6.3ā€‚ Sallen-Keyā€‚circuit.

Page 209: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 193

1. Solve for vout and v1 using MATLABā€™s ode45 function. Assume that theinputtothecircuitvinisastepvoltagethatchangesfrom0Vto1Vattime= +0t .Assume the followingvalues for the circuit elements: = 5000 ,1R = 50002R , = 22001C pF, = 11002C pF. Use a time interval of t =

[0,100Ī¼s]andassume = =(0) (0) 01v vout . 2. FindtheimpulseresponseofthecircuitbyfirstcreatingaMATLABfunction

pulse(t)thatreturnsthefollowingvalues:

pulse(t)=< < āˆ’10 for 0 10

0 otherwise

6 6t

Then, solve for vout and v1 using MATLABā€™s ode45 function where vi =pulse(t).Use thesamecomponentvalues, time interval,and initialcondi-tionsasinpart1.

3. Plotthestepresponse(frompart1)andtheimpulseresponse(frompart2)onthesamesetofaxes.Whatrelationshipcanyouseebetweenthetwo?

4. WhatisoneadvantageoftheSallen-Keycircuitversustheordinarysecond-orderRLCcircuitofAppendixA?

Problem.6.4

BycascadingtheSallen-Keycircuit,wecancreatehigher-orderfilters.FigureP6.4showsanexampleofafourth-orderfilter.

UsingEquations(P6.3a)and(P6.3b),writeasystemoffourfirst-orderdiffer-entialequationstodescribethefourth-orderSallen-Keycircuit.Rememberthatvoutofthefirststagewillbeequaltovin ofthesecondstage.

1. SolveforvoutusingMATLABā€™sode45function.Assumethattheinputtothecircuitvinisastepvoltagethatchangesfrom0Vto1Vattime = +0t .Assumethe following values for the circuit elements: = = = = 50001 2 3 4R R R R ,

= 180001C pF, = 150002C pF, = 4.73C Ī¼F,and = 104C pF.Usea timeintervaloft =[0,0.005]secandassume = = = =(0) (0) (0) (0) 01 2 3v v v vo .

2. Plotvoutandvinwithrespecttotonthesamesetofaxes.

+ā€“

C2

C1

R1 R2vin v1 v3

v2 v4vout

+ā€“

C4

C3

R3 R4

Figureā€‚P6.4ā€‚ Fourth-orderā€‚filterā€‚usingā€‚cascadedā€‚Sallen-Keyā€‚circuits.

Page 210: Numerical and Analytical Methods with MATLAB for

194ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Project.6.5

Acommonboundaryvalueprobleminelectricalengineeringissolvingfortheelec-tricpotentialinthedepletionregionofaPNjunction.PNjunctionsareformedbytwoadjacentregionsofoppositelydopedsemiconductor(typicallysilicon)andareusedtocreateelectronicdevicessuchasbipolartransistors,MOSFETs,(metal-oxide-semiconductorfield-effecttransistors)andJFETs(junctionfield-effecttran-sistor).Herewewillanalyzethesimplestdevice,thePNdiode.

FigureP6.5ashowsthecircuitrepresentationofadiodewithappliedvoltageVAandresultingcurrentiD.FigureP6.5bshowsaphysicalrepresentationofthediodeas

iD

VA

+

āˆ’

Figureā€‚P6.5aā€‚ Diodeā€‚circuit.

p n

iD

++

+

+

+

++

++

++

ā€“ ā€“

ā€“

ā€“ā€“

ā€“

ā€“

ā€“

ā€“

ā€“

ā€“

n-type silicon withelectron density ND

p-type silicon withelectron density NA

depleted n-type siliconwith net positive charge

depleted p-type siliconwith net negative charge

x

Figureā€‚P6.5bā€‚ Close-upā€‚ofā€‚theā€‚depletionā€‚regionā€‚ofā€‚aā€‚PNā€‚junction.

Page 211: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 195

adjacentregionsofp-typesemiconductor(wherecurrentisprimarilycarriedbymobileholeswithdensityNAcarriers/cm3)andn-typesemiconductor(wherecurrentispri-marilycarriedbymobileelectronswithdensityND carriers/cm3).Intheareaimmedi-atelysurroundingthejunction(showninthefiguredetail),themobilechargecarriersofthe(normallyneutral)p-typeandn-typeregionswillrecombine,leavinganetfixedchargedensitylayeraroundthejunctioncalledthedepletion region.Thechargeden-sityinthedepletionregionisdependantonthedoping profile,andanexampledopingprofileisshowninFigureP6.5c.Inthisfigure,wehavemadetwoapproximations:(a)thatthesilicondopinglevelschangeabruptlyfromNA toNDatthejunction(i.e.atx=0),and(b)thatthedepletionregionendsabruptlyatā€“xP ontheleftsideandatxN ontherightside.Thus,thechargedensitiescanbeapproximatedasstraightlines:

Ļ = ā€“qNP A for āˆ’ < < 0x xP (P6.5a)

qNN DĻ = for < <0 x xN (P6.5b)

where ĻP and ĻN arethechargedensitiesinthep-andn-typeregionsrespectively,andqistheunitelectriccharge( Ɨ āˆ’1.6 10 19 coulomb).(NotethatthechargedensityonthePsideofthedepletionregionisnegativebecauseitisdepletedofpositivecar-riers.Similarly,theNsidewillhaveapositivechargedensity.)

The governing equation for the voltage potential Ī¦ in the p-type depletionregionis

Ī¦=

Īµ

2

2ddx

qN A (P6.5c)

and thegoverningequation for thevoltagepotentialĪ¦ in then-typedepletionregionis

Ī¦=āˆ’

Īµ

2

2ddx

qND (P6.5d)

Wesetx =0attheexactpointoftheP-to-NtransitionandarbitrarilysetthevoltagepotentialĪ¦ =0Vatx =0;thatis,

Ī¦(0)=0 (P6.5e)

( )P xĻ

( )N xĻ

Nxx

Ļ

P-side of junction N-side of junction

++

+

+

ā€“ā€“

ā€“ā€“

DqN

AqNāˆ’

Pxāˆ’

Figureā€‚P6.5cā€‚ Chargeā€‚densitiesā€‚ĻN(x)ā€‚andā€‚ĻP(x)ā€‚ā€‚atā€‚theā€‚PNā€‚junction.

Page 212: Numerical and Analytical Methods with MATLAB for

196ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thesecondboundarycondition is that theelectricfieldmustbezero intheneutralregionoutsidethedepletionregionbecausethereisnonetchargeinthat

region.Because = āˆ’Ī¦

Eddx

,thisconditionimpliesthat

Ī¦ = 0 at = āˆ’x xP (P6.5f)

Ī¦ = 0 at =x xN (P6.5g)

AssumethatwecanmodelthePNjunctionasaparallelplatecapacitorwiththeplates locatedat =x xN and = āˆ’x xP .Use the techniquedemonstrated inExample6.8tocalculatetheelectricpotentialinthedepletionregion.Assumethefollowingparameters:

q= Ɨ āˆ’1.6 10 19 coulomb, = 1016ND carriers/cm3, = Ɨ0.3 1016NA ,

= 0.15 mxN , = 0.5 mxP ,Ī”x=0.005Ī¼m, Īµ = Ɨ āˆ’1.04 10 12 F/cm.

1. SolveforĪ¦inthep-typeregionovertheinterval āˆ’ ā‰¤ ā‰¤ 0x xP withthebound-aryconditionsĪ¦ āˆ’ =( ) 0xP andĪ¦(0)=0andusingthefinitedifferenceequa-tionstodefineatri-diagonalmatrixandthensolvingthematrixproblem.

2. SolveforĪ¦inthen-typeregionovertheinterval Źŗ Źŗ0 x xN withtheboundaryconditionsĪ¦(0)=0and Ī¦ =( ) 0xN usingthesamemethodasdescribedinpart1.

3. Plot your results for both thep- andn-type regions onone graphover theinterval āˆ’ ā‰¤ ā‰¤x x xP N .

Problem.6.6

ForthePNjunctioninProblem6.5,wearbitrarilysetthegroundpointĪ¦ =0tobeattheexactpointoftheP-to-Nboundary.SupposeinsteadwesetthegroundpointtobeattheP-to-intrinsicboundary,thatis, Ī¦ āˆ’ =( ) 0xP .Theproblem(forthep-typeregion)becomes

Ī¦=

Īµ

2

2ddx

qN A (P6.6a)

Ī¦ āˆ’ =( ) 0x p (P6.6b)

Ī¦ āˆ’ =( ) 0xP (P6.6c)

Forthen-typeregion,

Ī¦=āˆ’

Īµ

2

2ddx

qND (P6.6d)

Attheintersectionofthetworegions,wherex=0,

Ī¦ =Ī¦āˆ’ +(0 ) (0 ) (P6.6e)

Page 213: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 197

and

Ī¦=

Ī¦āˆ’ +(0 ) (0 )ddx

ddx

(P6.6f)

1. FindanexactsolutionforEquations(P6.6a)ā€“(P6.6f)bydirectintegration. 2. Find a numerical solution for Equations (P6.6a)ā€“(P6.6f) using MATLABā€™s

ode45function.Assume: 0.3 1016NA = Ɨ carriers/cm3, 1016ND = carriers/cm3,Īµ = Ɨ āˆ’1.04 10 12 F/cm,āˆ’xP ā‰¤xā‰¤xN,where = 0.5 mxP , = 0.15 mxN ,andĪ”x=0.005Ī¼m.

3. Plotyourexactandode45solutionsonthesameaxes. 4. Findandprinttheglobalerrorintheode45solution.

Problem.6.7

A heat sink is often attached to electronic components to dissipate excess heatgeneratedbythedevicetopreventitfromoverheating(FigureP6.7a).AsketchofoneheatsinkfinisshowninFigureP6.7b,wherethetrapezoidalfinhasabottomwidthW1,topwidthW2,heightL1,anddepthD,andthecoordinatesxandyareasdrawninthediagram.Thetemperaturedistributioninthefinisgovernedbyaone-dimensionalanalysisoftheheatequationinasolid.Theanalysisincludesanempiricalrelationthatinvolvestheconvectiveheattransfercoefficienth.Thisempirical relation is introducedtoseparate theheatconductionprobleminthesolidfromtheheattransferprobleminthesurroundingfluid.Theconvectiveheattransfercoefficienthisdeterminedbyeitherexperimentoranalytical/numericalmethods.Thegoverningequationforthefinis

= āˆ’ āˆž( )d

dxAdTdx

hPk

T T (P6.7a)

Figureā€‚P6.7aā€‚ Typicalā€‚finā€‚heatā€‚sinkā€‚usedā€‚toā€‚coolā€‚anā€‚electronicā€‚componentā€‚suchā€‚asā€‚aā€‚microprocessor.ā€‚

Page 214: Numerical and Analytical Methods with MATLAB for

198ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

or

+ = āˆ’ āˆž( )

2

2dAdx

dTdx

Ad Tdx

hPk

T T (P6.7b)

whereTisthetemperatureinthefinatpositionx,Tāˆžisthesurroundingambientairtemperature,A isthefincross-sectionalarea,histheconvectiveheattransfercoefficient,kisthethermalconductivityofthefinmaterial,andPisitsperimeter.Webeginbywritingequationsfortheareaandperimeterintermsofthemeasure-mentsofthefin:

A=yD

P = 2y + 2D

Bythegeometryofsimilartriangles,wecandeterminethat =āˆ’

1

yW

L xL

,andthustheareaandperimeterasfunctionsofxare

= āˆ’

= āˆ’ +

( ) ( )

( ) 2 ( ) 2

1

1

A xW DL

L x

P xW DL

L x D

Thegoverningdifferentialequationbecomes

āˆ’ āˆ’ = āˆ’ + āˆ’ āˆž( ) 2 ( ) 2 ( )1

2

21 1W D

LL x

d Tdx

W DL

dTdx

hk

WL

L x D T T (P6.7c)

Cross section:

Device surface

L

L1

y

xD

W1

W2

Side view:

Figureā€‚P6.7bā€‚ Sideā€‚andā€‚cross-sectionalā€‚viewsā€‚ofā€‚aā€‚singleā€‚finā€‚ofā€‚theā€‚heatā€‚sinkā€‚withā€‚trapezoidalā€‚heightā€‚L1,ā€‚bottomā€‚widthā€‚W1ā€‚,ā€‚topā€‚widthā€‚W2ā€‚,ā€‚andā€‚depthā€‚D.ā€‚Theā€‚trap-ezoidā€‚isā€‚formedā€‚fromā€‚aā€‚truncatedā€‚triangleā€‚ofā€‚heightā€‚L.

Page 215: Numerical and Analytical Methods with MATLAB for

Numerical Integration of Ordinary Differential Equationsā€ƒ ā—¾ā€ƒ 199

Thefirstboundaryconditionisthatatthesurfaceofthedevice,thetempera-tureT W isknown:

=(0)T TW (P6.7d)

Toobtainthesecondboundarycondition,weemploytheconceptofenergyconservation,thatis

RatethatHeatLeavestheFinat(x=L1)perUnitSurfaceAreabyConduction =RatethatHeatIsCarriedAwaybyConvectionperUnitSurfaceArea

Thisstatementcanbewrittenmathematicallyas

āˆ’ = āˆ’ āˆž( ) [ ( ) ]1 1k

dTdx

L h T L T (P6.7e)

Wewishtosolvethisproblemnumericallyusingthefinitedifferencemethod.First,subdividethexaxisintoNsubdivisions,giving ā€¦ +, , ,1 2 3 1x x x xN .Take

thetemperatureatxitobeTi.Thefinitedifferenceformulasfor2

2d Tdx

anddTdx

(seeTable 6.1)are

=

+ āˆ’+ āˆ’( ) 22

21 1

2d Tdx

xT T T

xii i i

=

āˆ’+( ) 1dTdx

xT T

xii i

ThefinitedifferentialformofEquation(P6.7c)is

āˆ’

+ āˆ’āˆ’

āˆ’= āˆ’ + āˆ’+ āˆ’ +

āˆž( ) 2 2 ( ) 2 ( )1 1 12

1 1 1W DL

L xT T T

xw DL

T Tx

hk

WL

L x D T Tii i i i i

i i

SolvingforTigives

( ) ( )

( ) ( ) ( )

= āˆ’ āˆ’ + āˆ’ +

Ɨ āˆ’ āˆ’ + āˆ’ + āˆ’ +

āˆ’

+ āˆ’ āˆž

2 2 2

2 2

1 12

11

1 11

11

21

TW DL

L xW DL

xh xk

WL

L x D

W DL

L xW DL

x TW DL

L x Th xk

WL

L x D T

i i i

i i i i i

(P6.7f)

Equation(P6.7f)isvalidfori =2,3,ā€¦,N.ThefinitedifferenceformforEquation(P6.7e)is

[ ]āˆ’

āˆ’= āˆ’+

+ āˆž1

1kT T

xh T TN N

N

Page 216: Numerical and Analytical Methods with MATLAB for

200ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Solvingfor +1TN gives

=

+++ āˆž

1

11T h x

k

Th xk

TN N

Also, =1T TW .Alltheheattransferfromthefintothesurroundingairpassesthroughthebase

ofthefin.Thus,therateofheatlossQthroughthefinisgivenby

=āˆ’ āˆ’( )1

2 1QkAxT T

whereA1isthecross-sectionalareaatthebaseofthefin,thatis,atx=0+.UsingthemethoddescribedinSection6.11foratri-diagonalsystemofequa-

tions,writeaMATLABprogramthatwillsolveforthetemperaturedistributioninthefinandtherateofheatlossthroughthefin.Usethefollowingvalues:

200 C, 40 C, 204 W/m-K, 60 W/m -K,

50, 5 cm, 20 cm, 5 cm, 0.2 cm

2

1 1

T T k h

N W L L D

W = Ā° = Ā° = =

= = = = =

āˆž

Theoutputofyourprogramshouldincludethevaluesof Ā°, , , ,h k T T Qw ;atableofTversusxatevery0.1cm;andaplotofTversusx.

Page 217: Numerical and Analytical Methods with MATLAB for

201

Chapter 7

Laplaceā€‚Transforms

7.1ā€‚ ā€‚IntroductionTransformtechniquesinvolveapplyingamathematicaloperationtotheequationsofaproblem,solvinginthe(presumablyeasier)transformdomain,andthentakingtheinversetransformtoobtainananswerinthedomainofinterest.Laplace trans-formsarefrequentlyusedtosolveordinaryandpartialdifferentialequations.Themethodreducesanordinarydifferentialequationtoanalgebraicequation,whichcanbemanipulatedtoaformsuchthattheinversetransformiseasilyobtained.In circuit theory, any circuit containing capacitors or inductors will contain atleastonedifferentialrelationship,andalargecircuitmaycontainmanymore.InChapter6,wesolvedcircuitsdirectlyinthetimedomainbyintegratingthedif-ferentialequationsinMATLAB.WenowdescribetheLaplacetransformapproach[1,2];weconvertthetime-domainequationstotheLaplacedomain,solvealgebra-ically,andthentaketheinversetransformbacktothetimedomaintoobtainthefinalanswer.Sometimes,wedonotevenbotherwith thefinal stepbecause theresultintheLaplacedomainissufficienttofullysolvetheproblemofinterest.

7.2ā€‚ ā€‚Laplaceā€‚Transformā€‚andā€‚Inverseā€‚TransformLetf(t)beacausalfunctionsuchthatithassomedefinedvalueforalltā‰„0andiszerootherwise,thatis,f(t)=0fort <0.TheunilateralLaplacetransformisdefinedas

L āˆ«= = āˆ’

āˆž

( ( )) ( ) ( )0

f t F s e f t dtst (7.1)

Page 218: Numerical and Analytical Methods with MATLAB for

202ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

F(s) iscalled theLaplace transformof f (t),andthe symbol L isused to indi-catethetransformoperation.Byconvention,weuselowercaselettersfortimedomain functions and uppercase for their Laplace domain (or ā€œs-domainā€)counterparts.

Theinverse Laplace transformofF(s)isdefinedtobethefunctionf(t)suchthat

L =āˆ’ ( ( )) ( )1 F s f t (7.2)

Tables have been created that contain both f(t) and the corresponding F(s)(see Table 7.1attheendofthischapter).Often,weneedtorearrangethetransformtoaformorseveralformsthatareavailableinthetableofLaplacetransforms.WenowderivetheLaplacetransformforsomecommonfunctions.

7.2.1 Laplace Transform of the Unit StepWedefinetheunitstepfunctionu(t)mathematicallyas

( )1 for 00 for 0

u ttt

=ā‰„

<

Then

L āˆ«=

= āˆ’

=

āˆ’

āˆž

āˆ’ āˆž

( ( )) (1)

1

0

0

u t e dt

es

s

st

st

(7.3)

7.2.2 ExponentialLet

( )f t e at=

Page 219: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 203

whereaisaconstant.Then,

L āˆ«

āˆ«

=

=

= āˆ’āˆ’

=āˆ’

āˆ’

āˆž

āˆ’ āˆ’

āˆž

āˆ’ āˆ’ āˆž

( )

( )

1

0

( )

0

( )

0

e e e dt

e dt

es a

s a

at at st

s a t

s a t

(7.4)

7.2.3 LinearityLet

f(t)=Ag(t)+Bh(t)

whereg(t)andh(t)arefunctions,andAandBareconstants.Then,

L

L L

āˆ«

āˆ«āˆ«

+ = +

= +

= +

āˆ’

āˆž

āˆ’ āˆ’

āˆžāˆž

( ( ) ( )) ( ( ) ( ))

( ) ( )

( ( )) ( ( ))

0

00

A g t B h t Ag t Bh t e dt

A g t e dt B h t e dt

A g t B h t

st

st st

(7.5)

Thus,theLaplacetransformofasumisequaltothesumofthetransformsoftheaddends,andtheLaplacetransformofascaledfunctionisequaltothetrans-formoftheunscaledfunctionmultipliedbythescalingfactor.

7.2.4 Time DelayLet

f(t)=g(t āˆ’T )

Page 220: Numerical and Analytical Methods with MATLAB for

204ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

wheref(t)issimplyatime-delayedversionofg(t)withdelaytimeTseconds(withTpresumedalwayspositive).Then,

L āˆ«āˆ’ = āˆ’ āˆ’

āˆž

( ( )) ( )g t T g t T e dtst

T

wherethebottomintegrationlimithasbeensettoTbecauseg(t āˆ’T )ispresumedtobezerofort <T.Then,letĻ„ =t āˆ’T(andthusdĻ„ =dt).Then,

L āˆ«

āˆ«

āˆ’ = Ļ„ Ļ„

= Ļ„ Ļ„

=

āˆ’ Ļ„+

āˆž

āˆ’ āˆ’ Ļ„

āˆž

āˆ’

( ( )) ( )

( )

( )

( )

0

0

g t T g e d

e g e d

e G s

s T

sT s

sT (7.6)

Thus,theLaplacetransformofadelayedfunctionisequaltothetransformoftheundelayedfunctionmultipliedbythedelayfactor e sTāˆ’ .

7.2.5 Complex ExponentialLet

( )f t e j t= Ļ‰

Then,applyingEquation(7.4),weget

L =āˆ’ Ļ‰

=āˆ’ Ļ‰

Ɨ+ Ļ‰+ Ļ‰

=+ Ļ‰+Ļ‰

=+Ļ‰

+Ļ‰+Ļ‰

Ļ‰( ) 1

1

2 2

2 2 2 2

es j

s js js j

s js

ss

js

j t

(7.7)

Page 221: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 205

Byapplyingtheidentity cos sine x j xjx = + ,wealsoknow

L L

L L

= Ļ‰ + Ļ‰

= Ļ‰ + Ļ‰

Ļ‰( ) (cos sin )

(cos ) (sin )

e t j t

t j t

j t

(7.8)

Equating the real and imaginary components of Equation (7.7) andEquation (7.8)givestheLaplacetransformsforsineandcosine:

L Ļ‰ =

+Ļ‰( ) 2 2cos t

ss

(7.9)

L Ļ‰ =

Ļ‰+Ļ‰

( ) 2 2sin ts

(7.10)

Generalizingtothecasewhentheexponenthasbothrealandimaginaryparts,

L

L L

=āˆ’ + Ļ‰

=āˆ’ āˆ’ Ļ‰

=āˆ’

āˆ’ +Ļ‰+

Ļ‰āˆ’ +Ļ‰

= Ļ‰ + Ļ‰

+ Ļ‰( ) 1( )1

( )

( ) ( )( cos ) ( sin )

( )

2 2 2 2

es a j

s a js a

s ajs a

e t j e t

a j t

at at

Wemayobservefromthisthatmultiplicationofthefunction ( )f t e j t= Ļ‰ bye atinthetimedomainproducesansshiftintheLaplacedomain.Thismaybegeneri-callystatedas

L = āˆ’( ( )) ( )e f t F s aat (7.11)

7.2.6 Powers of tLet

( ) 1f t t n= +

Then,

L āˆ«=+ +

āˆž

āˆ’( )1 1

0

t t e dtn n st

Page 222: Numerical and Analytical Methods with MATLAB for

206ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Tosolve,integratebyparts.Let 1u t n= + anddv e dtst= āˆ’ .Then, ( 1)du n t dtn= +

and = āˆ’āˆ’

ves

st

.Applying udv uv vduāˆ« = āˆ’ āˆ« ,weget

Lāˆ« āˆ«= āˆ’ +

+=

++ āˆ’

āˆž

+āˆ’

=

āˆž

āˆ’

āˆž1 1 ( )1

0

1

0 0

t e dt tes

ns

t e dtns

tn st nst

t

n st n (7.12)

FromEquation(7.12),wecanseethat

L L

L L

L L L

=

=āˆ’

= = =

āˆ’

āˆ’ āˆ’

( ) ( )

( ) 1 ( )

( ) 1 ( ) 1 (1) 1

1

1 2

1 02

tns

t

tns

t

ts

ts s

n n

n n

(7.13)

7.2.7 Delta FunctionThedelta functionwasformalizedbyphysicistPaulDiracandisdefinedasfollows:

( ) for 0

0 otherwiset t

Ī“ =āˆž =

and

( ) 10

t dtāˆ« Ī“ =

āˆž

Althoughwe cannotphysically realizeĪ“(Ļ„) in an actual circuit (though it isoften approximated), it has many useful applications in circuit theory, and itsLaplacetransformis

L āˆ«Ī“ = Ī“ = =āˆ’

āˆž

āˆ’ āˆž( ( )) ( ) 1

00

t t e es t s t

Exampleā€‚7.1

Find the Laplace transform of the pulse p(t) as shown in Figure 7.1, where A is the amplitude, T1 is the turn-on time, and T2 is the turn-off time.

Page 223: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 207

We can express the pulse mathematically as the sum of two delayed unit steps with amplitude A:

p t Au t T Au t T( ) ( ) ( )1 2= āˆ’ āˆ’ āˆ’

We know from Equation (7.3) that the Laplace transform of the unit step is

s1 . Also, from Equation (7.5), the transform of a sum is simply the

sum of the transforms. In addition, from Equation (7.6), the transform of a time-delayed function is simply e sTāˆ’ times the transform of the undelayed function. Thus, the transform of the pulse is

P s A es

A es

Ase e

sT sT

sT sT

( ) ( )( )1

( )( )1

( )

1 2

1 2

= āˆ’

= āˆ’

āˆ’ āˆ’

āˆ’ āˆ’ (7.14)

Exampleā€‚7.2

Find the inverse Laplace transform of the following function:

F s

es

T eT s

sT sT

( )1 2

42

2

2 2 2=āˆ’

+Ļ€+ Ļ€

āˆ’ āˆ’

(7.15)

We start by decomposing the first term of Equation (7.15):

es s

es

sTsT1 1 1

2 2 2

āˆ’= āˆ’

āˆ’āˆ’ (7.16)

We know from Equation (7.13) that L =ts

( )12 and from Equation (7.6)

that multiplication by e sTāˆ’ in the Laplace domain corresponds to delay

T1 T2t

A

p(t)

Figureā€‚7.1ā€‚ Pulseā€‚withā€‚amplitudeā€‚A,ā€‚turn-onā€‚timeā€‚T1,ā€‚andā€‚turn-offā€‚timeā€‚T2.

Page 224: Numerical and Analytical Methods with MATLAB for

208ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

in the time domain. Thus, the inverse transform of Equation (7.16) is the subtraction of a ramp f t t( ( ) )= and a time-delayed ramp and is shown graphically in Figure 7.2a.

For the second term of Equation (2.15), we rearrange as follows:

T eTs

TeT

T s

Te T

sT

Tes

sTsT

sT

sT

2( ) 4

2(2 )

2

2

2

2 2 2 2 2

22

2 2

Ļ€+ Ļ€

=Ļ€+ Ļ€

=

Ļ€

+Ļ€

=Ļ‰+ Ļ‰

āˆ’āˆ’

āˆ’

āˆ’ (7.17)

By inspection, Equation (7.17) corresponds to a time-delayed sine wave of

amplitude T and frequency Ļ‰ =Ļ€

T2

and is illustrated in Figure 7.2b. The

complete inverse transform is shown in Figure 7.2c.

( )f t t=

t Tt

T

tT

āˆ’ =

( ) ( )f t g tāˆ’( )g t t T= āˆ’for Tt ā‰„

(a)

Tt

T

āˆ’T T

t

T

2T

(b) (c)

Figureā€‚7.2ā€‚ Exampleā€‚ofā€‚ inverseā€‚Laplaceā€‚transform.ā€‚(a)ā€‚Theā€‚inverseā€‚transformā€‚of

āˆ’ āˆ’

s2e sT

s1 12 ā€‚isā€‚theā€‚subtractionā€‚ofā€‚aā€‚rampā€‚andā€‚aā€‚time-delayedā€‚ramp.ā€‚(b)ā€‚Theā€‚inverse

transformā€‚ofā€‚Ļ‰+ Ļ‰

āˆ’

s2 2Te sT ā€‚isā€‚aā€‚time-delayedā€‚sineā€‚wave.ā€‚(c)ā€‚Theā€‚completeā€‚inverse

transformā€‚isā€‚theā€‚sumā€‚ofā€‚theā€‚graphsā€‚inā€‚(a)ā€‚andā€‚(b).

Page 225: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 209

7.3ā€‚ ā€‚Transformsā€‚ofā€‚DerivativesLet

( ) ( )

f tdf tdt

=

Then,

L āˆ« āˆ«= =āˆ’

āˆž

āˆ’

āˆž

( )0 0

fdfdt

e dt e dfst st

Integratingbyparts, letdv =dfand u e st= āˆ’ .Then,v = fand du se dtst= āˆ’ āˆ’ .Applying udv uv vduāˆ« = āˆ’ āˆ« ,weget

Lāˆ« āˆ«= + = āˆ’ +āˆ’

āˆž

āˆ’

=

āˆž āˆ’

āˆž

(0) ( )0

00

e df fe s fe dt f s fst stt

st (7.18)

Thus,theLaplacetransformofaderivativeisthetransformoftheoriginalfunc-tionmultipliedbysandminusthevalueofthefunctionattimet = 0(i.e.,lesstheinitialcondition).

Similarly,forthesecondderivative,

L āˆ«= āˆ’

āˆž

( ) ( )0

f f t e dtst

L āˆ« āˆ«( ) = =āˆ’

āˆž

āˆ’

āˆž

0 0

fdfdt

e dt e dfst st

Let dv df= and u e st= āˆ’ . Then, v f= and du se dtst= āˆ’ āˆ’ . Integrating byparts,weget

L

L

āˆ« āˆ«= +

= āˆ’ +

= āˆ’ āˆ’ +

āˆ’

āˆž

āˆ’

=

āˆž āˆ’

āˆž

(0) ( )

(0) (0) ( )

00

0

2

f e dt f e s f e dt

f s f

f s f s f

st s tt

st

(7.19)

ByEquations(7.18)and(7.19),wecanseethepatternfortheLaplacetransformofthenthderivative,thatis:

L L= āˆ’ āˆ’ āˆ’ āˆ’āˆ’ āˆ’( ) ( ) (0) (0) (0)( ) 1 2 ( )f s f s f s f fn n n n n (7.20)

Page 226: Numerical and Analytical Methods with MATLAB for

210ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

7.4ā€‚ ā€‚Ordinaryā€‚Differentialā€‚Equations,ā€‚Initialā€‚Valueā€‚Problem

ConsiderthedifferentialequationarisingfromtheparallelRLCcircuitofAppendixAinEquation(A.7).Thegoverningdifferentialequationfortheinductorcurrentiis

1 1 ( )i

RCi

LCi

I tLCo+ + = (7.21)

whereListheinductance(inhenries),Ristheresistance(inohms),Cisthecapaci-tance(infarads),andIoisthedrivingcurrent.

Wealsoassumetheinitialconditionstobe

i(0)=Ī± and (0)i =Ī²

First,weconvertthisequationintothefollowinggeneralform:Lety(t)=i(t),

= = =1 , 1 and ( ) ( )

pRC

qLC

f tI tLCo .Then,Equation(7.20)becomes

( )y py qy f t+ + = (7.22)

TheLaplacetransformofeachofthetermsinEquation(7.22)isasfollows:

L

L

L

L

( )

= āˆ’ Ī± āˆ’Ī²

= āˆ’Ī±

=

=

( ) ( )

( ) ( )

( ) ( )

( ) ( )

2y s Y s s

py p sY s

qy qY s

f F s

Thus,Equation(7.22)becomes

( ) ( ( ) ) ( ) ( )

( ) ( ) ( )

2

2

s Y s s p sY s qY s F s

Y ss p F s

s ps q

āˆ’ Ī± āˆ’Ī² + āˆ’ Ī± + =

ā†’ =+ Ī± +Ī² +

+ +

Let

( ) 1

2H ss ps q

=+ +

Then,

( ) [( ) ] ( ) ( ) ( )Y s s p H s F s H s= + Ī± +Ī² + (7.23)

Page 227: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 211

BydoingapartialfractionexpansionofEquation(7.23)andusingLaplacetransformtables,wecanobtainy(t)byfindinginversetransformofY(s),thatis, ( ( )) ( )1 Y s y tL =āˆ’ .

Exampleā€‚7.3

Given the following differential equation (no damping and an exponentially decaying driving function), determine the solution for y(t):

y y e

y y

t5

(0) 2, (0) 0

+ =

= =

āˆ’

(7.24)

This problem fits the general form of Equation (7.22), with p = 0, q = 1, and f e t5= āˆ’ . Thus,

Y(s) = (2s)H(s)+F(s)H(s)

where

H s

s( )

112=

+ and

L= =

+āˆ’F s e

st( ) (5 )

51

Thus,

Y s

ss s s

( )2

15

( 1)( 1)2 2=+

++ +

(7.25)

For the second term of Equation (7.25), we need to decompose by the method of partial fractions:

s sAs

Bs Cs

A s Bs C ss s

5( 1)( 1) 1 1

( 1) ( )( 1)( 1)( 1)

2 2

2

2

+ +=

++

++

=+ + + +

+ +

Matching terms in the numerator,

A B C B A C

A B C

0, 0, 5

52,

52,

52

+ = + = + =

ā†’ = = āˆ’ =

Thus,

s s sss

5( 1)( 1)

52( 1)

52( 1)( 1)2 2+ āˆ’

=+

āˆ’āˆ’+

and substituting back into Equation (7.25), we get

Y s

ss s

ss s

( )2

( 1)5

2( 1)5

2( 1)5

2( 1)2 2 2=+

++

āˆ’+

++

Page 228: Numerical and Analytical Methods with MATLAB for

212ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

From Table 7.1, we observe

ss

t1

cos12L+

=āˆ’

st

11

sin12L+

=āˆ’

se t1

11L

+=āˆ’ āˆ’

Therefore, by applying inverse transforms, the solution to Equation (7.24) is

y t t t e t( )

12cos

52sin

52

= āˆ’ + + āˆ’

A plot of y versus t is shown in Figure 7.3.

Exampleā€‚7.4

Determine the solution of the following differential equation:

y y y t

y y

3 2 5sin2

(0) 1, (0) 4

+ + =

= = āˆ’ (7.26)

0 5 10 15 20āˆ’3

āˆ’2

āˆ’1

0

1

2

3

4

t(s)

y(m

)

y vs. t

Figureā€‚7.3ā€‚ Plotā€‚of y versusā€‚tā€‚forā€‚Exampleā€‚7.3.

Page 229: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 213

Using the same form as Equation (7.22),

p

q

f t tt

3

2

( ) 5sin2 10sin22

=

=

= =

In the Laplace domain,

H s

s s s s( )

13 2

1( 2)( 1)2=

+ +=

+ +

L= =

+F s

ts

( ) 10sin22

1042

Thus,

Y s s H s F s H s

ss s s s s s s

( ) ( 3)(1) 4 ( ) ( ) ( )

( 2)( 1)1

( 2)( 1)10

( 4)( 2)( 1)2

[ ]= + āˆ’ +

=+ +

āˆ’+ +

++ + +

(7.27)

We now make use of the MATLAB function residue function, which can be used to solve partial fraction expansions. The residue function takes two arguments that are arrays containing the coefficients of the numerator and denominator polynomials to be expanded. It then returns the numerator coefficients (the ā€œresiduesā€), the denominator roots (the ā€œpolesā€), and any nonfractional term (which will always be zero in the usual case where the denominator is of higher order than the numerator).

To solve with residue, we rewrite the first term of Equation (7.27) in polynomial form:

ss s

ss s( 2)( 1) 3 22+ +

=+ +

(7.28)

By the use of partial fractions, we can determine that

ss s s s( 2)( 1)

22

11+ +

=+

āˆ’+

Now, let us use MATLABā€™s residue to reduce the right-hand side of Equation (7.28) to the sum of two fractions. In the numerator of the right-hand side of Equation (7.28), we see that the first polynomial term (for s1) has a coefficient of 1, and the second term (for s0) has a coefficient of 0. This is expressed in MATLAB as [10]. Similarly, the denominator polynomial has

Page 230: Numerical and Analytical Methods with MATLAB for

214ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

an s2 coefficient of 1, an s1 coefficient of 3, and an s0 coefficient of 2, which is expressed as [132]. Then, in MATLAB we run

>> [r, p, k] = residue([1 0],[1 3 2])

r= 2 -1p= -2 -1k= []

This result shows that the residues are 2 and āˆ’1, and their respective poles are āˆ’2 and āˆ’1, giving

ss s s s3 2

2( 2)

1( 1)2 + +

=+

āˆ’+

(7.29)

which is the same that was obtained by the use of partial fractions.For the second term in Equation (7.27), we run residue([-1],[132])

to obtain

s s s s

s s

1( 2)( 1)

13 2

1( 2)

1( 1)

2

āˆ’+ +

=āˆ’

+ +

=+

āˆ’+

(7.30)

For the third term in Equation (7.27), we first rewrite as a polynomial:

s s s s s s s10

( 4)( 2)( 1)10

3 6 12 82 4 2 2+ + +=

+ + + +

Then, in MATLAB we obtain

>> [r, p, k] = residue([10],[1 3 6 12 8])r= -0.3750+0.1250i -0.3750-0.1250i -1.2500 2.0000p= 0.0000+2.0000i 0.0000-2.0000i -2.0000 -1.0000k= []

Page 231: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 215

Thus, the residues are at āˆ’0.375 Ā± 0.125j, āˆ’1.25, and 2. The correspond-ing poles are at Ā±2j, āˆ’2, and āˆ’1. Thus,

+ + +=

+ + + +

=āˆ’ +

āˆ’+āˆ’ āˆ’

+

āˆ’+

++

s s s s s s s

js j

js j

s s

10( 4)( 2)( 1)

103 6 12 8

0.375 0.125( 2 )

0.375 0.125( 2 )

1.25( 2)

2( 1)

2 4 2 2

(7.31)

The final answer is the sum of the inverse transforms of Equations (7.29), (7.30), and (7.31). From Table 7.1,

L

L

L

L

+=

+=

āˆ’=

+=

āˆ’ āˆ’

āˆ’ āˆ’

āˆ’

āˆ’ āˆ’

se

se

s je

s je

t

t

jt

j t

12

11

12

12

1 2

1

1 2

1 2

Collecting all the terms in Y(s) and applying these inverse transforms gives the complete solution for Equation (7.26):

L ( )= = āˆ’ āˆ’ + āˆ’āˆ’ āˆ’ āˆ’ āˆ’y t Y s e e e je jet j t j t j t j t( ) ( ) 1.75 0.375 0.375 0.125 0.1251 2 2 2 2 2

Applying the identities e e tj t j t 2cos+ = Ļ‰Ļ‰ āˆ’ Ļ‰ and e e j tj t j t 2 sināˆ’ = Ļ‰Ļ‰ āˆ’ Ļ‰ , we obtain

y t e t tt( ) 1.75 0.75cos 2 0.25sin22= āˆ’ āˆ’āˆ’ (7.32)

It is illustrative to compare the Laplace-obtained solution with a direct solution of Equation (7.26) obtained via MATLABā€™s ode45 function. The program follows, and the output is shown in Figure 7.4:

%Example_7_4.m:ThisprogramsolvesEquation7.26by%convertingitintoasystemoftwodifferential%equationsandsolvingwithode45.%Letv=y',Y=[yv],andY'=[y'v'].%Y(1)=y,Y(2)=v,Y'(1)=Y(2),Y'(2)=5*sin2t-3Y(2)-2Y(1)%Initialconditions:y(0)=1.0,y'(0)=v(0)=-4.0clear;clc;%Defineinitialconditions:Y0=[1.0-4.0];%Definetimeintervaltosolve:dt=0.1;Tstop=10;Tspan=0.0:dt:Tstop;%solvetheODEdirectlywithode45:[t,Yode45]=ode45('dydt',Tspan,Y0);%computethesolutionfoundviaLaplaceTransforms

Page 232: Numerical and Analytical Methods with MATLAB for

216ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%(Equation7.32):Ylaplace=1.75*exp(-2*Tspan)...-0.75*cos(2*Tspan)-0.25*sin(2*Tspan);plot(t,Yode45(:,1),'x',Tspan,Ylaplace),axis([0Tstop-11]);xlabel('t'),ylabel('Yode45,Ylaplace');title('ODEsolutionsusingode45andLaplaceTransform');legend('ode45','Laplace','Location','SouthWest');-------------------------------------------------------------------

%dydt:thisfunctionworkswithExample7.4.functionYprime=dydt(t,Y)Yprime=zeros(2,1);Yprime(1)=Y(2);Yprime(2)=5*sin(2*t)-3.0*Y(2)-2.0*Y(1);

Exampleā€‚7.5

Determine the solution of the following differential equation:

+ + =<

ā‰„

= =

y y yt t

t

y y

3 25 , for 2

0, for 2

(0) 1, (0) 0

(7.33)

0 2 4 6 8 10āˆ’1

āˆ’0.8

āˆ’0.6

āˆ’0.4

āˆ’0.2

0

0.2

0.4

0.6

0.8

1

t

Yod

e45,

Yla

plac

eODE solutions using ode45 and Laplace Transform

ode45Laplace

Figureā€‚7.4ā€‚ Comparisonā€‚betweenā€‚solutionā€‚obtainedā€‚byā€‚Laplaceā€‚ transformsā€‚andā€‚MATLABā€™sā€‚ode45ā€‚forā€‚Exampleā€‚7.4.

Page 233: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 217

Applying the standard form of Equation (7.22), let p = 3, q = 2, and

f t

t t

t( )

5 , for 2

0, for 2=

<

ā‰„

We begin by writing f(t) into a form that is recognizably transformable, that is, in terms of the unit step function:

r t t u t u t

t u t t u t

( ) 5 ( ) ( 2)

5 ( ) 5 ( 2)

( )= āˆ’ āˆ’

= āˆ’ āˆ’ (7.34)

The first term in Equation (7.34) is easily transformable L =t u ts

(5 ( ))52 ,

but the second is less recognizably so. However, for the second term, let 5t = 5(t āˆ’ 2 + 2). Then,

f t t u t t u t

t u t t u t u t

( ) 5 ( ) 5( 2 2) ( 2)

5 ( ) 5( 2) ( 2) 5(2) ( 2)

= āˆ’ āˆ’ + āˆ’

= āˆ’ āˆ’ āˆ’ āˆ’ āˆ’

Then,

L ( )= āˆ’ āˆ’ āˆ’ āˆ’ āˆ’

= āˆ’ āˆ’āˆ’ āˆ’

F s tu t t u t u t

se

se

ss s

( ) 5 ( ) 5( 2) ( 2) 10 ( 2)

5 5 102

22

2

Thus,

Y s s H s

se

s sH ss( ) [( 3)(1)] ( )

5 5 10( )2

22= + + āˆ’ +āˆ’

H s

s s s s( )

13 2

1( 2)( 1)2=

+ +=

+ +

=+ +

++ +

++ +

āˆ’+ +

āˆ’+ +

āˆ’ āˆ’

Y ss

s s s s s s s

es s s

es s s

s s

( )( 2)( 1)

3( 2)( 1)

5( 2)( 1)

5( 2)( 1)

10( 2)( 1)

2

2

2

2

Let Y s Y Y Y Y Y( ) 1 2 3 4 5= + + + + , where

=+ +

=+ +

=+ +

= āˆ’+ +

= āˆ’+ +

āˆ’

āˆ’

Ys

s s

Ys s

Ys s s

Ye

s s s

Ye

s s s

s

s

( 2)( 1)

3( 2)( 1)

5( 2)( 1)

5( 2)( 1)

10( 2)( 1)

1

2

3 2

4

2

2

5

2

Page 234: Numerical and Analytical Methods with MATLAB for

218ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

By partial fraction expansion via MATLABā€™s residue function, we can determine that

L

L

L

L

L

= āˆ’

= āˆ’ +

= āˆ’ āˆ’ +

= āˆ’ āˆ’ āˆ’ āˆ’ + āˆ’

= āˆ’ + āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

Y e e

Y e e

Y t e e

Y t t e e e e u t

Y e e e e u t

t t

t t

t t

t t

t t

( ) 2

( ) 3 3

( )52

154

54

5

( )52

154

54

5 ( 2)

( ) 1012

12

( 2)

11

2

12

2

13

2

14

4 2 2

15

4 2 2

Summing these five terms gives

y t

t e e t

e e e e t

t t

t t

( )

52

154

94

7 , for 2

94

154

(7 5 ) , for 2

2

4 2 2

=

āˆ’ āˆ’ + <

āˆ’ + + + ā‰„

āˆ’ āˆ’

āˆ’ āˆ’

(7.35)

This problem can also be solved numerically by the use of the ode45 function in MATLAB. The MATLAB program used to solve this problem follows:

%Example_7_5.m:ThisprogramsolvesEquation7.33by%convertingitintoasystemoftwodifferential%equationsandsolvingwithode45.%Letv=y',Y=[yv],andY'=[y'v'].%Y(1)=y,Y(2)=v,Y'(1)=Y(2).%Y'(2)=5*t-3Y(2)-2Y(1)fort<2%Y'(2)=-3Y(2)-2Y(1)fort>=2%Initialconditions:y(0)=1,y'(0)=0clear;clc;%Defineinitialconditions:Y0=[1.00.0];%Definetimeintervaltosolve:dt=0.1;Tstop=4;Tspan=0:dt:Tstop;%SolvetheODEdirectlywithode45:[t,Yode45]=ode45('dydt2',Tspan,Y0);%ComputethesolutionfoundviaLaplaceTransforms%(Equation7.35)fori=1:length(Tspan)ifTspan(i)<2Ylaplace(i)=2.5*Tspan(i)-15/4-...9/4*exp(-2*Tspan(i))+7*exp(-Tspan(i));else

Page 235: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 219

Ylaplace(i)=-(9/4+15/4*exp(4))...*exp(-2*Tspan(i))...+(7+5*exp(2))*exp(-Tspan(i));endendplot(t,Yode45(:,1),'x',Tspan,Ylaplace),title('ODEsolutionsusingode45andLaplaceTransform');legend('ode45','Laplace');-------------------------------------------------------------------

%dydt2:ThisfunctionworkswithExample7.5.%Y(1)=y,Y(2)=v%Y1'=Y(2),Y2'=5*t-3Y2-2Y1,ift>2,Y2'=-3Y2-2Y1,ift>=2functionYprime=dydt2(t,Y)Yprime=zeros(2,1);Yprime(1)=Y(2);ift<2Yprime(2)=5*t-3.0*Y(2)-2.0*Y(1);elseYprime(2)=-3.0*Y(2)-2.0*Y(1);end

A comparison of the ode45 and the Laplace transform solution is shown in Figure 7.5.

0 0.5 1 1.5 2 2.5 3 3.5 4

0.8

1

1.2

1.4

1.6

1.8

2

2.2

2.4

2.6ODE solutions using ode45 and Laplace Transform

ode45Laplace

Figureā€‚7.5ā€‚ Comparisonā€‚betweenā€‚solutionā€‚obtainedā€‚byā€‚Laplaceā€‚ transformsā€‚andā€‚MATLABā€™sā€‚ode45ā€‚forā€‚Exampleā€‚7.5.

Page 236: Numerical and Analytical Methods with MATLAB for

220ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

7.5ā€‚ ā€‚ConvolutionGiven two functions f(t) andg(t)withknown transformsF(s) andG(s), respec-tively,thentheinversetransformoftheproductF(s)G(s)istheconvolutionintegral

L āˆ« āˆ«( ) = Ļ„ āˆ’ Ļ„ Ļ„ = Ļ„ āˆ’ Ļ„ Ļ„āˆ’ ( ) ( ) ( ) ( ) ( ) ( )1

0 0

F s G s f g t d g f t dt t

(7.36)

Proof:

( ) ( ) ( ) ( )

( ) ( )

0 0

0

( )

0

F s G s f p e dp g e d

g f p e dp d

ps s

p s

āˆ« āˆ«

āˆ« āˆ«

= Ļ„ Ļ„

= Ļ„ Ļ„

āˆ’

āˆž

āˆ’Ļ„

āˆž

āˆž

āˆ’ +Ļ„

āˆž

(7.37)

Lett =p +Ļ„.Then,whenp =0,t =Ļ„andwhenp =āˆž,thent =āˆž.Also,dp =dt.Then,

( ) ( ) ( ) ( )

( ) ( )

0

F s G s g f t e dt d

g f t e dt d

t s

R

t s

āˆ«āˆ«

āˆ«āˆ«

= Ļ„ āˆ’ Ļ„ Ļ„

= Ļ„ āˆ’ Ļ„ Ļ„

āˆ’

Ļ„

āˆžāˆž

āˆ’ (7.38)

whereR istheregionbelowthelinet =Ļ„ asshowninFigure 7.6.TheintegrationorderofthemultipleintegralaswritteninEquation(7.38)is

tointegratewithrespecttotfirst,thenwithrespecttoĻ„.Inthiscase,theorderof

Region R

t

Ļ„t = Ļ„

Figureā€‚7.6ā€‚ Integrationā€‚regionā€‚forā€‚convolutionā€‚inā€‚theā€‚(Ļ„,ā€‚t)ā€‚plane.

Page 237: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 221

integrationdoesnotmatter,sowecanintegratewithrespecttoĻ„ first,thenwithrespecttot.Thisgives

L

āˆ«āˆ«

āˆ«āˆ«

āˆ«

= Ļ„ āˆ’ Ļ„ Ļ„

= Ļ„ āˆ’ Ļ„ Ļ„

= Ļ„ āˆ’ Ļ„ Ļ„

āˆ’

āˆ’

āˆž

( ) ( ) ( ) ( )

( ) ( )

( ) ( )

00

0

F s G s g f t e dt d

e g f t d dt

g f t d

R

s t

s t

t

t

Thus,

L āˆ«= Ļ„ āˆ’ Ļ„ Ļ„āˆ’ ( ( ) ( )) ( ) ( )1

0

F s G s g f t dt

(7.39)

Alternatively,wecanreversetherolesoff andg,giving

L āˆ«= āˆ’ Ļ„ Ļ„ Ļ„āˆ’ ( ( ) ( )) ( ) ( )1

0

F s G s g t f dt

Convolutionisdenotedbytheā€œ*ā€operator;thus,

L ( ) = āˆ— = āˆ—āˆ’ ( ) ( ) ( ) ( ) ( ) ( )1 F s G s f t g t g t f t

Exampleā€‚7.6

We illustrate the Laplace transform of the convolution function by studying the waveforms of Figure 7.7a where we have two pulses f(t) and g(t):

f tt T

g tT t T

( )for 0

0 otherwise

( )for

0 otherwise

1

2 3

=Ī± ā‰¤ <

=Ī² ā‰¤ <

Figure 7.7b shows the convolution operation where we take the mir-ror image f(Ļ„ āˆ’ t) of f(t) and slide it along the t axis (by varying Ļ„) while

Page 238: Numerical and Analytical Methods with MATLAB for

222ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

T1t

T3T2t

Ī±

Ī²

f(t)

g(t)

(a)

T3T2t

g(t)

f (t āˆ’ Ļ„)for varying Ļ„

(b)

T3T2t

T1+T2 T1+T3

f (t)*g(t)Ī±Ī²

(c)

T1

T2 T1 + T2

T1 + T3

eāˆ’sT1

s2eāˆ’s(T1 + T3)

s2

+ + +

++ +ā€“eāˆ’sT2

s2 s2ā€“eāˆ’s(T1 + T2)ā€“1 ā€“1 ā€“1 ā€“1

(d)

Figureā€‚7.7ā€‚ Graphicalā€‚representationā€‚ofā€‚convolution.ā€‚(a)ā€‚Theā€‚pulseā€‚waveformsā€‚f(t)ā€‚andā€‚g(t).ā€‚(b)ā€‚Weā€‚performā€‚theā€‚convolutionā€‚graphicallyā€‚byā€‚takingā€‚theā€‚mirrorā€‚imageā€‚ofā€‚f(t),ā€‚slidingā€‚itā€‚onā€‚theā€‚tā€‚axis,ā€‚andā€‚integratingā€‚withā€‚g(t).ā€‚(c)ā€‚Theā€‚resultā€‚ofā€‚graphi-callyā€‚convolvingā€‚f(t)*g(t)ā€‚isā€‚aā€‚trapezoidalā€‚waveform.ā€‚(d)ā€‚Theā€‚identicalā€‚solutionā€‚isā€‚obtainedā€‚byā€‚takingā€‚theā€‚inverseā€‚transformā€‚ofā€‚F(s)G(s).

Page 239: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 223

integrating the two functions. The result of the convolution f(t)*g(t) is the trapezoidal waveform shown in Figure 7.7c:

f t g t

T Tt T T t T

T t T T

T Tt T T T T t T T

( ) ( )

( )( ) for

for ( )

( )( ) for ( ) ( )

0 otherwise

3 22 2 3

3 1 2

3 21 3 1 2 1 3

āˆ— =

Ī±Ī²āˆ’

āˆ’ ā‰¤ <

Ī±Ī² ā‰¤ < +

āˆ’Ī±Ī²āˆ’

āˆ’ āˆ’ + ā‰¤ < +

(7.40)

We now calculate the Laplace transforms of f(t) and g(t), multiply them in the s domain, and then inverse transform to obtain the identical answer. We previously calculated the transform of a pulse in Equation (7.14). Thus,

F ss

e

G sse e

sT

sT sT

( ) (1 )

( ) ( )

1

2 3

=Ī±

āˆ’

=Ī²

āˆ’

āˆ’

āˆ’ āˆ’

Multiplying,

F s G s

se e e esT sT s T T s T T( ) ( ) 2

( ) ( )2 3 1 2 1 3( )=Ī±Ī²

āˆ’ āˆ’ +āˆ’ āˆ’ āˆ’ + āˆ’ + (7.41)

By inspection, the inverse transform of Equation (7.41) consists of the sum of four time-delayed ramp functions and is shown graphically in Figure 7.7d. The sum of the four ramps equals the same trapezoid as in Figure 7.7c.

7.6ā€‚ ā€‚Laplaceā€‚Transformsā€‚Appliedā€‚toā€‚CircuitsIncircuittheory,capacitorsandinductorshaveconstituentrelationsthatparticu-larlylendthemselvestoanalysisintheLaplacedomain.Startingwiththecapacitor,

i C

dvdtCC=

whereiCisthecapacitorcurrent,vCisthecapacitorvoltage,andCisthecapacitorvalue (in farads). Applying Equation (7.18), we can rewrite this equation in theLaplacedomainas

( ) ( ) (0)I s C sV s vC C C( )= āˆ’

Ifweneglectforthemomenttheinitialcondition,thisbecomes

( ) ( ) 1V s I s

CsC C= (7.42)

Page 240: Numerical and Analytical Methods with MATLAB for

224ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

NotethatEquation(7.42)resemblesOhmā€™slaw ( )v iR= ,andwethusdefinethecomplex impedance ZCofacapacitortobe

( ) 1Z s

CsC = (7.43)

Bysimilaranalysiswiththeconstituentrelationfor inductors =v LdidtLL , the

compleximpedanceZLofaninductorL(neglectinginitialconditions)isshownto be

( )Z s LsL = (7.44)

Finally,forresistors,theLaplacetransformofOhmā€™slawimplies

( )Z s RR = (7.45)

BecausewehavepreviouslyproventhatLaplacetransformsarelinear,wecannowsolvecomplicatedlinearcircuitsdirectlyintheLaplacedomainbyusingthesamealge-braictechniquesusedtosolvetheinput/outputrelationshipsforresistor-onlycircuits.Forexample,theparallelRLCcircuitasredrawninFigure 7.8withinputcurrentIo(s),outputvoltageVc(s),andcompleximpedancescanbesolvedwithoneequation:

( ) ( ) ( ) || ( ) || ( )V s I s Z s Z s Z sC o R C L( )=

where theparallel operator ( ) indicates the calculation for resistors (or imped-ances)inparallel.Then,

( )( )

11 1 1

11 1

11 12

V sI s

Z Z Z

RCs

Ls

Cs

sRC

sLC

C

o

R C L

=+ +

=+ +

= Ɨ+ +

(7.46)

Io(s) ZR ZL CZ VC(s)+

āˆ’

Figureā€‚7.8ā€‚ RLCā€‚circuitā€‚usingā€‚impedances.

Page 241: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 225

Wealsodefine

( ) ( )

( )H s V s

I sC

o= (7.47)

asthetransfer functionofthecircuit,thatis,theratiooftheoutputvariable(inthiscaseVC )totheinputdrivingfunction(inthiscaseIo).

Letusnowassumeasinusoidalformforio(t)suchthat

( )i t C eoj t= Ļ‰

where ( cos sin )e t j tj t = Ļ‰ + Ļ‰Ļ‰ isasumofsinesandcosinesoffrequencyĻ‰.Forconvenience,wehavealsoaddedaconstantfactorofCtosimplifythemathasweprogress.Then,

( ) 1

I s Cs jo =āˆ’ Ļ‰

and

( ) ( ) ( )

( )( )( )1 2

V s H s I s

ss s s s s j

C o=

=+ + āˆ’ Ļ‰

(7.48)

where s1and s2arethezerosofthedenominatorofEquation(7.46)andarecal-culatedfromR,L,andC.Wealsoassumeforthisanalysisthats1ands2arereal.RearrangingEquation(7.48)bypartialfractions,weget

=

+ āˆ’ Ļ‰+

++ āˆ’ Ļ‰

++

Ļ‰Ļ‰ + Ļ‰ +

āˆ’ Ļ‰( ) ( )( ) ( )( ) ( )( )

1

1 2 1

1

2

2 1 2

2

1 2V s

ss s s j

s s

ss s s j

s s

jj s j s

s jC

Byinversetransform,weget

( )

( )( ) ( )( )( )1

1 2 1

2

2 1 2

1 2v ts

s s s je

ss s s j

e H j eCs t s t j t=

+ āˆ’ Ļ‰+

+ āˆ’ Ļ‰+ Ļ‰āˆ’ āˆ’ Ļ‰ (7.49)

AlthoughEquation(7.49)lookscomplicated,notethatthefirsttwotermscontainnegativeexponentialsandthusinthesteady state(t ā†’āˆž),thisequationreducesto

lim ( ) ( )v t H j et

cj t= Ļ‰

ā†’āˆž

Ļ‰ (7.50)

Page 242: Numerical and Analytical Methods with MATLAB for

226ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ThemeaningofEquation(7.50)isthatforanysinusoidalinput(offrequencyĻ‰)tothecircuit,wecancalculatethevalueofthesteady-stateoutput(alsooffre-quencyĻ‰)bycalculatingH( jĻ‰).Thisderivationcanbegeneralizedfordetermin-ingthefrequency responseofanylinearcircuitbyfindingthetransferfunctionH(s)analyticallyandthenlettings =jĻ‰tofinditsfrequency-dependentbehavior.

Frequency response is traditionally plotted as two graphs showing the mag-nitude | ( )|H jĻ‰ andphaseāˆ H( jĻ‰),bothversus frequency.Themagnitudeplotistypicallyonlog-logaxes,andthephaseplotistypicallyonsemilogaxes(linearphasevs.logfrequency).Together,theplotsarereferredtoasaBode plot.

Exampleā€‚7.7

Let

H s

s( )

10001000

=+

Plot the magnitude and phase of H(jĻ‰) over the interval [1 10 , 1 10 ]1 6Ļ‰ = Ɨ Ɨāˆ’ rad/sec. The solution is shown in Figure 7.9.

mag

H(jw

)

Bode Plot

100 101 102 103 104 105 106

100

100

10āˆ’2

101 102 103 104 105 106

āˆ’100

āˆ’80

āˆ’60

āˆ’40

āˆ’20

0

Frequency (rad/sec)

phas

e H

(jw)

Figureā€‚7.9ā€‚ Bodeā€‚plotā€‚forā€‚ Ļ‰Ļ‰ ==Ļ‰Ļ‰ ++

( )1000

1000H j

j.

Page 243: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 227

%Example_7_7.m:Plotmagnitudeandphaseof%H(jw)=1000/(s+1000)forw=[1e-1,1e6].%First,createalogarithmicpointsetforthefrequency%rangefrom1to1e6rad/secwithtenpointsineach%decade.fork=1:60w(k)=10^(k/10);end%ComputethemagnitudeforH(jw)H_mag=abs(1000./(j*w+1000));%ComputethephaseforH(jw),andconverttodegreesH_phase=(180/pi)*angle(1000./(j*w+1000));%Plotmagnitudeonlog-logaxessubplot(2,1,1);loglog(w,H_mag);axis([10^010^610^-32*10^0]);ylabel('magH(jw)');title('BodePlot');%Plotphaseonlog-linearaxessubplot(2,1,2);semilogx(w,H_phase);axis([10^010^6-10010]);xlabel('Frequency(rad/sec)');ylabel('phaseH(jw)');

7.7ā€‚ ā€‚Impulseā€‚ResponseInSection7.2.7,wediscussedthedeltafunctionanditsproperties.WhathappensifweuseadeltafunctionastheinputtoacircuitwithknowntransferfunctionH(s)?InEquation(7.47),wedefinedH(s)astheratioofthecircuitoutputtothecircuitinput.Ifweassumethattheinputisadeltafunction,then

( ) ( ) ( )

( ) 1

V s H s I s

H s

C o

( )

=

= (7.51)

where we have assumed ( ) ( )i t to = Ī“ with corresponding Laplace transform ofunity.IfweinversetransformEquation(7.51),weget

( ) ( )v t h tC =

Inotherwords,ifthecircuitinputisadeltafunction,thenthecircuitoutputis simply the inverse transform of the transfer function h(t), also known as theimpulse response.Conversely,ifwecanaccuratelycalculate(ormeasure)theimpulseresponseh(t)ofacircuit,thenwecanobtainthetransferfunctionH(s)andthuspredictthecircuitbehaviorforanyarbitraryinputwaveform.Thisconceptisillus-tratedinExample7.8.

Page 244: Numerical and Analytical Methods with MATLAB for

228ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚7.8

A circuit has an impulse response of

h t e tt( ) 10 cos102= āˆ’

What is the unit step response r(t) of the circuit?Transforming h(t) into H(s), we obtain

H s

ss

( ) 102

( 2) 1002=+

+ +

where we have applied Equations (7.9) and (7.11) to determine the Laplace transform. To obtain the step response, we first multiply H(s) by the unit step

transform s1

to obtain R(s):

R s

ss s

( ) 102

( 2) 1001

2=+

+ +

We now calculate the inverse transform as follows:

L

L

L

=

=+

+ +

=āˆ’ āˆ’

+ āˆ’+āˆ’ āˆ’

+ ++

Ɨ

= āˆ’ + āˆ’

āˆ’ +

= āˆ’ āˆ’ +

āˆ’

āˆ’

āˆ’

āˆ’ + āˆ’ + āˆ’ āˆ’

āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

r t R s

ss s s

js j

js j s

e je e

je u t

e e t e t u t

t j t t j t t j t

t j t

t t t

( ) ( )

102

4 104

100.0096 0.0481

(2 10 )0.0096 0.0481

(2 10 )0.0192

(calculated using residue)

10( 0.0096 0.0481 0.0096

0.0481 0.0192 ( ))

1.92 ( cos10 5 sin10 ( ))

1

13 2

1

2 10 2 10 2 10

2 10

2 2 2

Exercises

Exercise7.1 Determine L Ļ‰(sin )2 t .

Exercise7.2 Determine L( cos )2e tt .

Exercise7.3 Determine L āˆ’( sin2 )3e tt

Exercise7.4 DeterminetheLaplacetransformofthefunctionshowngraphicallyinFigureE7.4.

Page 245: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 229

Exercise7.5 Determine L+

+ āˆ’āˆ’ 2 1

( 9)( 2)1

2s

s s.

Exercise7.6 Determine L+ +

āˆ’ 1( 5 6)

.12s s

Exercise7.7 Determine L+ + +

āˆ’ 1( 1)( 3 2)

12s s s

by convolution in the timedomain.

Exercise7.8 SolvethefollowingdifferentialequationbyLaplacetransforms:

3 2 3 , (0) 1, (0) 2y y y e y yt+ āˆ’ = = =āˆ’

Projects

Project.7.1

FigureP7.1showsaseriesRLCcircuitdrivenbyaninputvoltagevi(t)andthreedefinedoutputvoltagesvR(t),vL(t),andvC(t).

t

1

āˆ’11

3

f (t)

Figureā€‚E7.4ā€‚ f(t)ā€‚consistsā€‚ofā€‚oneā€‚cycleā€‚ofā€‚aā€‚sineā€‚waveā€‚overā€‚theā€‚intervalā€‚1ā€‚ā‰¤ā€‚t ā‰¤ā€‚3ā€‚sec.

C

āˆ’

+vR

āˆ’

+vL

āˆ’

+vC

L

R

+ā€“

vi

Figureā€‚P7.1ā€‚ Seriesā€‚RLCā€‚circuit.

Page 246: Numerical and Analytical Methods with MATLAB for

230ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

1. Solvethecircuitusingcompleximpedancestofindthethreetransferfunc-

tions =( ) ( )( )

H sV sV sRR

i, =( ) ( )

( )H s

V sV sLL

i,and =( ) ( )

( )H s

V sV sCC

i.Putthetransfer

functionsinthefollowingstandardform:

( ) 1

22 3

24 5

H sK s K s Ks K s K

=+ ++ +

wheretheconstantsK1throughK5arereal.Notethatthefiveconstantsarescaledsuchthatthehighest-orderterminthedenominatorshouldhavenoconstant.

2. CreatetheBodeplotsfor ( )H jR Ļ‰ , ( )H jL Ļ‰ ,and ( )H jC Ļ‰ .Usethesecom-ponentvalues:R=1kĪ©,L=0.1mH,andC=0.1ĀµF.Plotovertherange

[1, 1 10 ]10Ļ‰ = Ɨ rad/sec.3. Thethreetransferfunctionsrepresentthreetypesoffilters:high-pass,low-pass,

andbandpass.Whichtransferfunctioncorrespondstowhichfiltertype?

Project.7.2

Acommon emitter amplifier is showninFigureP7.2awith inputvoltagevinandoutputvoltagevout.Inthesetypesofsingle-transistorcircuits,thevoltagesofinter-estrideatopDCcomponentsVBIASandVOFFSET,whichareusedtobiasthetransis-torintoitslinear(i.e.,amplification)mode.FigureP7.2bshowsthesmall-signalhybrid-pimodelofthebipolartransistor[3].Inthesmall-signalmodel,theDCcomponents (VCC, VBIAS, and VOFFSET) are ignored, and we can use Kirchhoffā€™s

+ā€“+ā€“

vin

VBIAS

LR

VCC

vout + VOFFSET

IBIAS

Figureā€‚P7.2aā€‚ Commonā€‚emitterā€‚amplifier.ā€‚VBIASā€‚isā€‚theā€‚nonvaryingā€‚(ā€œDCā€)ā€‚compo-nentā€‚ofā€‚theā€‚input,ā€‚whichā€‚isā€‚adjustedā€‚toā€‚obtainā€‚theā€‚desiredā€‚operatingā€‚pointā€‚(IBIAS )ā€‚ofā€‚theā€‚transistor.ā€‚VOFFSETā€‚isā€‚theā€‚DCā€‚componentā€‚ofā€‚theā€‚output.ā€‚Theā€‚voltagesā€‚ofā€‚interestā€‚areā€‚theā€‚varyingā€‚componentsā€‚ofā€‚theā€‚inputā€‚vinā€‚andā€‚theā€‚outputā€‚vout.

Page 247: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 231

current law to solve for the transfer function in termsof complex impedances.WritingKCLequationsatnodesvĻ€andvoutgives

āˆ’āˆ’ +

āˆ’=Ļ€ Ļ€

Ļ€Ļ€

Ļ€( )1

( )1 0v v

rv

rc s

v v

c s

in

b

out (P7.2a)

āˆ’

+ + =Ļ€Ļ€

( )1 0v v

c s

g vv

r Rout

mout

o L (P7.2b)

wherevĻ€isthesmall-signalbase-emittervoltage;rĻ€isthesmall-signalbase-emitterresistance;rb is thebaseresistance;cĻ€andcĪ¼arethebase-emitterandcollector-emittercapacitances,respectively;roisthesmall-signalcollector-emitterresistance;gmisthesmall-signaltransconductance;andRListheloadresistance.Solvingtheseequationsgivesthetransferfunctionofthesystem:

( )

1

112

H svv

rc s g

c c sc

r Rc

r R r rg

sr r r R

out

in

bm

o Lo L b

m

b o L

( )

( )( )

= =āˆ’

+ + +Ļ€Ļ€

Ļ€Ļ€

(P7.2c)

Ifweassumethatthetransistor ismodel2N3904,wecanobtainnumericalvaluesforthecircuitparametersfromthemanufacturerdatasheetforthiscom-ponent [4]. These are summarized in Table P7.2. We also assume that VBIAS isadjustedtoobtainatransistorcollectorcurrent(IBIAS)of1mA,andthatRL=5 kĪ©.Becausethe2N3904isadiscretedevice(andnotpartofanintegratedcircuit),we

alsoassumeasmallbaseresistancerb=25Ī©.Also,assumethat =gIVm

o

T,where

= = 0.026VkTqT mV.

+ā€“vin vout

+

āˆ’

RLrogmvĻ€

cĀµ

cĻ€rĻ€vĻ€

+

āˆ’

rb

Figureā€‚P7.2bā€‚ Small-signalā€‚modelā€‚ofā€‚theā€‚commonā€‚emitterā€‚amplifier.ā€‚rbā€‚isā€‚theā€‚seriesā€‚baseā€‚resistance,ā€‚rĻ€ā€‚isā€‚theā€‚small-signalā€‚base-emitterā€‚resistance,ā€‚gmā€‚isā€‚theā€‚transcon-ductanceā€‚(theā€‚transistorā€‚ā€œgainā€),ā€‚roā€‚isā€‚theā€‚small-signalā€‚collector-emitterā€‚resistance,ā€‚andā€‚cĻ€ā€‚andā€‚cĪ¼ā€‚areā€‚ theā€‚base-emitterā€‚andā€‚collector-emitterā€‚capacitances,ā€‚ respec-tively.ā€‚RLā€‚isā€‚theā€‚loadā€‚resistanceā€‚ofā€‚theā€‚amplifier.

Page 248: Numerical and Analytical Methods with MATLAB for

232ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

1. Create the Bode plot for the transfer function of Equation (P7.2a)using the parameters in Table P7.2. Plot over the frequency interval

[1 10 , 1 10 ]5 11Ļ‰ = Ɨ Ɨ rad/sec.2. AcommontrickforhandanalysisofthiscircuitistousetheMiller approxima-

tion;weassumealternativevaluesforcĪ¼andcĻ€asfollows:

0

( ) 1

c

c c g r R cm o L( )

=

= + +Ļ€ Ļ€

SubstitutetheseapproximatedvaluesforcĪ¼andcĻ€intoEquation(P7.2a)andfindtheapproximatetransferfunctionHMiller(s).

3. PlotHMiller(s)onthesamesetofaxes thatyoualreadyusedtoplotH(s).UnderwhatcircumstancesistheMillerapproximationreasonabletouse?

References 1. Churchill,R.V.,Operational Mathematics,2nded.,McGraw-Hill,NewYork,1958. 2. Kreyszig,E.,Advanced Engineering Mathematics,8thed.,Wiley,NewYork,1999. 3. Sedra, A.S., and Smith, K.C., Microelectronic Circuits, 3rd ed., Saunders College,

Philadelphia,1991. 4. 2N3904/MMBT3904/PZT3904 NPN general purpose amplifier, Fairchild

Semiconductordatasheet,http://www.fairchildsemi.com,2011.

Tableā€‚P7.2ā€‚ Parametersā€‚forā€‚2N3904ā€‚NPNā€‚transistor

Transistor Parameter Typical Value

hFE (= Ī²) 125

Cobo (= cĪ¼) 3 pF

Cibo (= cĻ€) 4 pF

hie (= rĻ€) 4 kĪ©

hoe (= 1/ro) 10 Āµmho

Page 249: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 233

Table 7.1ā€‚ Commonā€‚Laplaceā€‚Transforms

f(t) F(s)

1 Unit step: 1s1

2 Ramp: ts12

3 Power of t: tn( 1)!

n 1

āˆ’

āˆ’

sn

1( 1,2,...)n =

4 Derivative: df tdt( )

sF(s)āˆ’f(0)

5 Time delay: f(tāˆ’T) eāˆ’sT F(s)

6 Exponential: eat f(t) F(sāˆ’a)

7 Convolution: f(t)āˆ—g(t) F(s)G(s)

8 Delta function: Ī“(t) 1

9t

1ā‰  s

1

10t

2ā‰  s

32

āˆ’

11t

n2

1 3 5 (2 1)

n n 1/ 2

ā€¦Ć— Ɨ Ɨ Ɨ āˆ’ Ļ€

āˆ’

s n( 1,2,...)n

12 =

āˆ’ +

12 eat

s a1āˆ’

13 teat

s a1

( )2āˆ’

14n

t e1

( 1)!n at1

āˆ’āˆ’

s an

1( )

( 1,2,...)nāˆ’=

15 t ek at1āˆ’ ks a

k( )

( )( 0)k

Ī“āˆ’

>

(continued)

Page 250: Numerical and Analytical Methods with MATLAB for

234ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Table 7.1ā€‚ Commonā€‚Laplaceā€‚Transformsā€‚(Continued)

f(t) F(s)

16a b

e e1

( )( )at bt

āˆ’āˆ’

s a s ba b

1( )( )

( )āˆ’ āˆ’

ā‰ 

17a b

ae be1

( )( )at bt

āˆ’āˆ’

ss a s b

a b( )( )

( )āˆ’ āˆ’

ā‰ 

18b a e c a e a b e

a b b c c a( ) ( ) ( )

( )( )( )

at bt ct

āˆ’āˆ’ + āˆ’ + āˆ’

āˆ’ āˆ’ āˆ’ s a s b s c1

( )( )( )āˆ’ āˆ’ āˆ’

19a

at1sin

s a1

2 2+

20 cos a ts

s a2 2+

21a

at1sinh

s a1

2 2āˆ’

22 cosh a ts

s a2 2āˆ’

23a

at1

(1 cos )2 āˆ’s s a

1( )2 2+

24a

at at1

( sin )3 āˆ’s s a

1( )2 2 2+

25a

at at at12

(sin cos )3 āˆ’s a

1( )2 2 2+

26ta

at2

sins

s a( )2 2 2+

27a

at at at12

(sin cos )+s

s a( )

2

2 2 2+

28 tcos ats as a( )

2 2

2 2 2

āˆ’+

Page 251: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 235

Table 7.1ā€‚ Commonā€‚Laplaceā€‚Transformsā€‚(Continued)

f(t) F(s)

29at btb a

cos cos2 2

āˆ’āˆ’

ss a s b

a b( )( )

( )2 2 2 22 2

+ +ā‰ 

30be bt

1sinat

s a b1

( )2 2āˆ’ +

31 e btcosat s as a b( )2 2

āˆ’āˆ’ +

32 e eat at

cos3

23 sin

32

atat2āˆ’ āˆ’āˆ’ a

s a3 2

3 3+

33 sin at cosh at āˆ’ cos at sinh ata

s a44

3

4 4+

34a

at at12

sin sinh2

ss a44 4+

35a

at at12

(sinh sin )3 āˆ’s a

14 4āˆ’

36a

at at12

(cosh cos )2 āˆ’s

s a4 4āˆ’

37 a t at at at(1 )sin cos2 2+ āˆ’a s

s a8

( )

3 2

2 2 3+

38 L ten

ddt

t e( )!

( )n

t n

nn t= āˆ’

sss

1 1 nāˆ’

39te at

1(1 2 )at

Ļ€+

s

s a( )32āˆ’

40t

e e1

2( )bt at

3Ļ€āˆ’ s a s bāˆ’ āˆ’ āˆ’

(continued)

Page 252: Numerical and Analytical Methods with MATLAB for

236ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Table 7.1ā€‚ Commonā€‚Laplaceā€‚Transformsā€‚(Continued)

f(t) F(s)

41t

ae a t1

erfc( )a t2

Ļ€āˆ’

s a1+

42t

ae a t1

erfc( )a t2

Ļ€+ s

s a2āˆ’

43ae a t

1erf( )a t2

s s a1

( )2āˆ’

44 e a terfc( )a t2

s s a1

( )+

45b a

e b a t1

erf ( )at

āˆ’āˆ’āˆ’

s a s b1

( )+ +

46 eba

a terf ( ) 1a t2 āˆ’b a

s s a s b( )( )

2 2

2

āˆ’āˆ’ +

47 J at( )0s a

12 2+

48 J kt(2 )0se

1 k s/āˆ’

49t

kt1

cos 2ā‰  s

e1 k s/āˆ’

50 tkt

1cosh2

ā‰  se

1 k s/

51k

kt1

sin2ā‰  s

e1 k s3/ 2

/āˆ’

52k

kt1

sinh2ā‰  s

e1 k s3/ 2

/

53k

t

kt2

exp43

2

Ļ€āˆ’ e k( 0)k s >āˆ’

Page 253: Numerical and Analytical Methods with MATLAB for

Laplace Transformsā€ƒ ā—¾ā€ƒ 237

Table 7.1ā€‚ Commonā€‚Laplaceā€‚Transformsā€‚(Continued)

f(t) F(s)

54kt

erfc2 s

e k1

( 0)k s ā‰„āˆ’

55t

kt

1exp

4

2

Ļ€āˆ’

se k

1( 0)k s ā‰„āˆ’

56t k

tk

kt

2 exp4

erfc2

2

Ļ€āˆ’ āˆ’ s e k( 0 )k s3/ 2 ā‰„āˆ’ āˆ’

57 e e a tkt

kt

erfc2

erfc2

ak a t2āˆ’ + + aes a s

k( )

( 0)k s

+ā‰„

āˆ’

58 e e a tkt

erfc2

ak a t2 + es a s

k( )

( 0)k s

+ā‰„

āˆ’

59te e

1( )bt atāˆ’

s as b

logāˆ’āˆ’

60t

at2

1 cos( )āˆ’s as

log2 2

2

+

61t

at2

1 cosh( )āˆ’s as

log2 2

2

āˆ’

62t

kt1sin

ks

tan 1āˆ’

Page 254: Numerical and Analytical Methods with MATLAB for
Page 255: Numerical and Analytical Methods with MATLAB for

239

Chapter 8

Fourierā€‚Transformsā€‚andā€‚Signalā€‚Processing

8.1ā€‚ ā€‚IntroductionInelectroniccircuits,weareoftenpresentedwithvoltageandcurrentsthatrepre-sentsignalsthatcarrymeaningfulinformation.Examplesinclude

ā—¾ audio,includinghi-fiandvoice

ā—¾ video,includingtelevisionandsurveillance

ā—¾ telemetryfromtemperaturesensors,straingauges,medicalinstrumentation,powermeters,andthelike

ā—¾ radar,loran,andGPSsignalsfordetectionandguidancesystemsonaircraftandships

ā—¾ modulatedsignalsasAM,FM,VHF,UHF,CDMA(codedivisionmultipleaccess),GSM(GroupespĆ©cialemobile),andWi-Fiforbroadcastandpoint-to-pointtransmissionofaudio,video,voice,anddata

Therearecountlessreasonsforprocessingsignals.Foraudioandvideo,wemightwant tofilteroutnoiseor reducebandwidth.For telemetry signals,wemaywanttoexaminethedatafrommultiplesensorstoachieveagoalsuchaspredictingthe

Page 256: Numerical and Analytical Methods with MATLAB for

240ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

weather,reducinganautomobileā€™sfuelconsumption,orinterpretingsensordatafromanelectrocardiogram.Inthecaseofcommunicationsystems,wecanusemodulationtomultiplexaudioorvideosignals(fromradioorTVstations)ontohigh-frequencycarriers,therebyallowingmultiplesignalstobecarriedoveracommonmedium(e.g.,acoaxialcableoropticalfiber)or throughtheairwaves. Inaddition,we typicallywanttoaccountforthelinklossandintersymbolinterference(ISI)introducedbythechannel.

TheprimarymathematicaltoolusedinsignalprocessingistheFourier trans-form. This transform provides a method for describing a signal in terms of itsfrequency components (i.e., in the ā€œfrequency domainā€) instead of in the morefamiliar and tangible ā€œtimedomain.ā€Table 8.1 lists several typesof signals andtheircorrespondingfrequencyranges(i.e.,therangeoffrequencycomponentsthatmightbepresentinthewaveforms).Fortherestofthischapter,weuseaudiosignalsinourexamplesbecausetheyarelikelytobefamiliartomostreaders.However,all of the techniques introduced in this chapter are applicable to signals of anyfrequencyrange.

Figure 8.1showsanexamplewaveformforsomeofthesignalsofTable 8.1.Ingeneral,theā€œsharpnessā€oftheshapeofeachsignalcorrespondstoitshigh-frequencycomponents,andthemorejaggedthesignal,thehigherthefrequencyrange.Thus,overa25-msecinterval,thehigh-fidelityaudiosignalshowninFigure 8.1bismorejagged than the speech signal in Figure 8.1a. Periodic signals (e.g., the musicalnoteshowninFigure 8.1c)consistprimarilyofasinglefundamentalfrequencyplussmallerharmoniccomponents thatcause thewaveformtodeviate fromaprecisesinusoidalshape.

Table 8.1ā€‚ Exampleā€‚Signalsā€‚andā€‚Theirā€‚Correspondingā€‚Frequencyā€‚Ranges

Signal Type Frequency Range

Speech 200 to 3200 Hz

High-fidelity audio (range of human ear) 20 to 20,000 Hz

AM radio 535 to 1705 kHz (North America) or 526.5 to 1606.5 kHz (Europe)

FM radio 87.5 to 108.0 MHz

802.11b Wi-Fi networking 2.401 to 2.473 GHz

White noise 0 to āˆž Hz

A above middle C on the piano 440 Hz (fundamental)

880 Hz, 1320 Hz, 1760 Hz, ā€¦ (harmonics)

Page 257: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 241

8.2ā€‚ ā€‚Mathematicalā€‚Descriptionā€‚ofā€‚Periodicā€‚Signals:ā€‚Fourierā€‚Series

Webeginwitha signalx(t),whichmightrepresentaudible soundthathasbeenconvertedtoavaryingvoltageusingatransducer(e.g.,amicrophone).Ifx(t)isperi-odicasshowninFigure 8.1casasustainedAnoteonapiano,thenFouriertheorytellsusthatthewaveformmaybeexpressedasaweightedsumofpuresinusoids:

ā€¦ ā€¦āˆ‘ āˆ‘= + Ļ€ ā‹… ā‹… + Ļ€ ā‹… ā‹…= =

( ) cos(2 ) sin(2 )0

1,2,3, 1,2,3,

x t A A nf t B nf tn o

n

n o

n

(8.1)

t

x(t)

0.025

(a)

t

y(t)

0.025

(b)

t

z(t)

0.025

(c)

Figureā€‚ 8.1ā€‚ Exampleā€‚ ofā€‚ band-limitedā€‚ waveforms:ā€‚ (a)ā€‚ speech;ā€‚ (b)ā€‚ high-fidelityā€‚audio;ā€‚(c)ā€‚Aā€‚aboveā€‚middleā€‚Cā€‚onā€‚theā€‚piano.

Page 258: Numerical and Analytical Methods with MATLAB for

242ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thefrequenciesnfointhesecondandthirdtermsrepresentallpossiblesineandcosinecomponentsofx(t).Then =1componentisthefundamentalfrequencyfo,andcomponentswheren >1arecalledtheharmonics.ThefactorsAnandBnarecalledtheFourier coefficients,andA0istheā€œDCā€componentofx(t).Wecandeter-mineA0,An,andBnmathematicallybymultiplyingx(t)byeachpossiblefrequencycomponentandthenintegratingoveroneperiodofx(t).Forexample,tofindtheFouriercoefficientforthemthcosineterm,wemultiplybothsidesofEquation(8.1)

bycos(2Ļ€mfot)andintegrateovertheinterval āˆ’ ā‰¤ ā‰¤2 2T

tT

,where =1

Tfo

isthe

timeperiodforonecycleoftheperiodicwaveform:

āˆ«

āˆ‘āˆ‘āˆ«

Ļ€

= + Ļ€ + Ļ€ Ļ€

āˆ’

āˆ’

( )cos(2 )

cos(2 ) sin(2 ) cos(2 )

/2

/2

0

/2

/2

x t mf t dt

A A nf t B nf t mf t dt

o

T

T

n o n o o

T

T

(8.2)

Becausesineandcosineareorthogonalfunctions,allofthetermsontherightsideofEquation(8.2)willintegrateouttozeroexceptforthecosine-cosinetermswhenm =n,thatis,

āˆ«

āˆ«

āˆ«

Ļ€ Ļ€ = =

Ļ€ Ļ€ = ā‰ 

Ļ€ Ļ€ =

āˆ’

āˆ’

āˆ’

cos(2 )cos(2 )2,

cos(2 )cos(2 ) 0,

cos(2 )sin(2 ) 0, all ,

/2

/2

/2

/2

/2

/2

mf t nf t dtT

m n

mf t nf t dt m n

mf t nf t dt m n

o

T

T

o

o

T

T

o

o

T

T

o

(8.3)

Therefore,theintegrationoperationwillā€œfilterā€outallcomponentsofx(t)exceptforthefrequencywherem =n.ApplyingEquation(8.3)toEquation(8.2)gives

āˆ«

āˆ«

( )

( )

= Ļ€

= Ļ€

āˆ’

āˆ’

2 ( )cos 2

2 ( )sin 2

/2

/2

/2

/2

AT

x t nf t dt

BT

x t nf t dt

n o

T

T

n

T

T

o

(8.4)

Page 259: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 243

TocalculatetheDCcoefficientA0,weintegrateEquation(8.3)form =0toobtain

āˆ«=

āˆ’

1 ( )0

/2

/2

AT

x t dtT

T

(8.5)

Exampleā€‚8.1

Find the Fourier series for the periodic pulse train shown in Figure 8.2 with

period T, frequency =fT

o1

, ā€œonā€ time of Ļ„, and ā€œoffā€ time of T āˆ’ Ļ„.

By centering x(t) on the y axis, we ensure that x(t) is an even function. Thus, by symmetry, all of the odd terms in Equation (8.1) (i.e., the sine terms) will be zero. We begin by finding the DC term (for n = 0) by applying Equation (8.5) and integrating x(t) over one cycle:

āˆ«= ā‹…

=Ļ„

āˆ’Ļ„

Ļ„

AT

dt

T

110

/2

/ 2

For the higher-order terms:

āˆ« ( )

( )

( )

= ā‹… Ļ€

=Ļ€

Ļ€

=Ļ€

Ļ€ Ļ„

āˆ’Ļ„

Ļ„

āˆ’Ļ„

Ļ„

AT

nf t dt

Tnf tnf

nnf

n o

o

o

o

21 cos 2

2 sin 22

2sin

/2

/ 2

/ 2

/ 2

1

t (millisec)āˆ’Ļ„/2 Ļ„/2āˆ’T T

Figureā€‚8.2ā€‚ Aā€‚pulseā€‚trainā€‚withā€‚ā€œonā€ā€‚timeā€‚ofā€‚Ļ„ā€‚andā€‚periodā€‚T.

Page 260: Numerical and Analytical Methods with MATLAB for

244ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Thus, the solution for the first few terms of the Fourier series for the pulse train is

( ) ( )

( )

=Ļ„+Ļ€

Ļ€Ļ„Ļ€ +

Ļ€Ļ€Ļ„

Ļ€

+Ļ€

Ļ€Ļ„Ļ€ +

x tT T

f tT

f t

Tf t

o o

o

( )2sin sin 2

1sin

2sin 4

23

sin3

sin 6

The following MATLAB program calculates the Fourier coefficients for the pulse train where T = 1 ms and Ļ„ = 0.25 ms and then reconstructs the pulse train based on the Fourier coefficients.

%Example_8_1.m%ComputetheFourierseriesforapulsetrain.T=1e-3;%pulseperiodfo=1/T;%frequencyofpulsetraininHztau=0.25e-3;%"on"timeofasinglepulsen=1:10;%wewillcomputethefirst10coefficients%computetheDCcoefficient:A0=tau/T;%computecoefficients1thrunfori=1:length(n)An(i)=(2/(pi*n(i)))*sin(pi*n(i)*fo*tau);end%Plotthecoefficients:subplot(2,1,1);stem([0fo*n],[A0An]);xlabel('Hz');ylabel('Fouriercoefficients');axis([-20010200-.2.6]);%UsetheFouriercoefficientstoreconstitutethepulse%trainovertheinterval-1.5<t<1.5millisecwithn%coefficientst=-1.5e-3:1e-6:1.5e-3;waveform=zeros(1,length(t));%AddintheDCcoefficientwaveform=waveform+A0;%Addinsignalcomponentsfor1thrunthcoefficientsfori=1:length(n)waveform=waveform+An(i)*cos(2*pi*n(i)*fo*t);endsubplot(2,1,2);plot(t*1000,waveform);xlabel('t(millisec)');ylabel('reconstitutedx(t)');

-------------------------------------------------------------------

The first 10 calculated Fourier coefficients are shown in Figure 8.3a, and the reconstituted pulse using the 10 coefficients is shown in Figure 8.3b.

Page 261: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 245

8.3ā€‚ ā€‚Complexā€‚Exponentialā€‚Fourierā€‚Seriesā€‚andā€‚Fourierā€‚Transforms

Generally, aFourier seriesmaybe comprisedof theweighted sumofany set oforthogonal functions. Although sines and cosines are a common choice due totheirfamiliarity,thepreferredchoicefromamathematicalperspectiveisthesetofcomplexexponentialfunctions:

āˆ‘= Ļ€

=āˆ’āˆž

āˆž

( ) 2x t C en j n f t

n

o (8.6)

0 2000 4000 6000 8000 10000āˆ’0.2

0

0.2

0.4

0.6

Hz

Four

ier

coef

ficie

nts

(a)

āˆ’1.5 āˆ’1 āˆ’0.5 0 0.5 1 1.5āˆ’0.5

0

0.5

1

1.5

t (millisec)

reco

nstit

uted

x(t

)

(b)

Figureā€‚8.3ā€‚ (a)ā€‚Fourierā€‚coefficientsā€‚forā€‚theā€‚pulseā€‚trainā€‚ofā€‚Figureā€‚8.2ā€‚forā€‚T =ā€‚1ā€‚msecā€‚andā€‚Ļ„ =ā€‚0.25ā€‚msec.ā€‚(b)ā€‚Pulseā€‚trainā€‚reconstitutedā€‚usingā€‚theā€‚firstā€‚10ā€‚Fourierā€‚coef-ficients.ā€‚Noteā€‚thatā€‚theā€‚missingā€‚higher-orderā€‚termsā€‚causeā€‚theā€‚reconstitutedā€‚wave-formā€‚toā€‚beā€‚inaccurate,ā€‚especiallyā€‚atā€‚theā€‚sharpā€‚transitions.

Page 262: Numerical and Analytical Methods with MATLAB for

246ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Knowingtheidentities =+ āˆ’

cos2

xe ejx jx

and =āˆ’ āˆ’

sin2

xe e

j

jx jx

,itcanbeproven

that Equation (8.6) is equivalent to Equation (8.1) where =āˆ’2

,CA jB

nn n

=+

āˆ’ 2C

A jBn

n n ,and =0 0C A .Multiplyinganexponentialbyitscomplexconju-

gateandthenintegratingoveroneperiodimpliesequivalentorthogonalityrelations:

āˆ« =

=

ā‰ Ļ€ āˆ’ Ļ€

āˆ’

,0,

2 2

/2

/2

e e dtT m n

m nj mf t j nf t

T

T

o o (8.7)

IntegratingbothsidesofEquation(8.6)overoneperiodandapplyingEquation(8.7)givesanexpressionforthecomplexexponentialFouriercoefficientsforanyperiodicx(t):

āˆ«= āˆ’ Ļ€

āˆ’

1 ( ) 2

/2

/2

CT

x t e dtnj nf t

T

T

o (8.8)

Wenowmake twomodifications toEquation (8.8).First,wenormalize the

Fouriercoefficientsbymovingthe 1T

factorfromtherightsidetotheleft.Then,we define X(f ) as a function to represent the normalized Fourier coefficients.Equation(8.8)becomes

āˆ«= = āˆ’ Ļ€

āˆ’

( ) ( ) 2

/2

/2

X nf TC x t e dto nj nf t

T

T

o (8.9)

Next,wereplacenfowiththevariablef(forfrequency)andletT ā†’āˆž,therebyimplying that x(t) becomes an aperiodic signal. Then, the integration limits inEquation(8.9)becomeinfinity,andX( f )becomesacontinuousfunction:

āˆ«= āˆ’ Ļ€

āˆ’āˆž

āˆž

( ) ( ) 2X f x t e dtj ft (8.10)

Equation(8.10)isthedefinitionoftheFourier transformofthetime-domainsignalx(t).

Exampleā€‚8.2

Plot the normalized complex exponential Fourier coefficients for the pulse train shown in Figure 8.2. Assume Ļ„ = 0.25 msec and generate three plots for T = 1, 2, and 10 msec.

Page 263: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 247

As for Example 8.1, the DC component is =Ļ„

CT

0 . For the n ā‰  0 terms,

āˆ«= ā‹…

=āˆ’ Ļ€

=āˆ’

āˆ’ Ļ€

=Ļ€ Ļ„Ļ€

āˆ’ Ļ€

āˆ’Ļ„

Ļ„

āˆ’ Ļ€

āˆ’Ļ„

Ļ„

āˆ’ Ļ€ Ļ„ Ļ€ Ļ„

CT

e dt

Tej nf

e ej n

nfn

nj nf t

j nf t

o

j nf j nf

o

o

o

o o

11

12

2

sin

2

/ 2

/ 2

2

/ 2

/ 2

A program that computes and plots the coefficients follows:

%Example_8_2.m%ComputenormalizedexponentialFourierseries%coefficientsforapulsetraintau=0.25e-3;%"on"timeofasinglepulseT=[1e-32e-310e-3];%pulsetrainperiodsfo=1./T;%frequencyofpulsetraininHzn=-150:150;fori=1:length(T)Cn(i,:)=(1./(pi*n)).*sin(pi*n*fo(i)*tau);%Findthe"zero"entryinnandcomputeit%separately(becauseithasadifferentformulathan%therest):zeroeth_element=find(n==0);Cn(i,zeroeth_element)=tau/T(i);%Normalizethecoefficients:Cn_normalized(i,:)=Cn(i,:).*T(i);end%findreasonablelimitsforaxessothatall3plots%havethesamemin/maxx_axis_limits=[-3.8/tau3.8/tau];y_axis_limits=[1.5*min(Cn_normalized(1,:))...1.25*max(Cn_normalized(1,:))];%PlotseparatelyforeachvalueofT:subplot(3,1,1);stem(n*fo(1),Cn_normalized(1,:));ylabel('Fouriercoefficients';'forT=1ms');axis([x_axis_limitsy_axis_limits]);title('ExponentialFourierSeriesforPulse');subplot(3,1,2);stem(n*fo(2),Cn_normalized(2,:));axis([x_axis_limitsy_axis_limits]);ylabel('Fouriercoefficients';'forT=2ms');subplot(3,1,3);plot(n*fo(3),Cn_normalized(3,:));axis([x_axis_limitsy_axis_limits]);ylabel('Fouriercoefficients';'forT=10ms');xlabel('f(Hz)');

-------------------------------------------------------------------

Page 264: Numerical and Analytical Methods with MATLAB for

248ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Figure 8.4 shows the three sets of Fourier coefficients computed in Example 8.2 for pulse periods of T = 1, 2, and 10 msec. Note that by keeping the pulse width constant and increasing the pulse period, the Fourier coefficients get closer and closer together. When T = 10 msec, they are so close together that we have plotted them as a continuous function. In the limit T ā†’ āˆž, Figure 8.4c corresponds to the Fourier transform of the pulse.

ā€“1.5 ā€“1 ā€“0.5 0 0.5 1 1.5

Ɨ104

0

1

2

3Ɨ10ā€“4

Fou

rier

Coe

ffici

ents

for

T =

1 m

s

Exponential Fourier Series for Pulse

0

1

2

3Ɨ10ā€“4

0 5000 10000ā€“10000 ā€“5000 15000ā€“15000

Fou

rier

Coe

ffici

ents

for

T =

2 m

s

ā€“1.5 ā€“1 ā€“0.5 0 0.5 1 1.5

Ɨ104

0

1

2

3Ɨ10ā€“4

Fou

rier

Coe

ffici

ents

for

T =

10

ms

f (Hz)

Figureā€‚8.4ā€‚ Plotā€‚ofā€‚theā€‚Fourierā€‚seriesā€‚coefficientsā€‚forā€‚aā€‚pulseā€‚trainā€‚withā€‚0.25ā€‚msecā€‚onā€‚timeā€‚andā€‚(a)ā€‚periodā€‚ofā€‚1ā€‚msec,ā€‚(b)ā€‚periodā€‚ofā€‚2ā€‚msec,ā€‚andā€‚(c)ā€‚periodā€‚ofā€‚10ā€‚msec.ā€‚Forā€‚theā€‚lastā€‚case,ā€‚theā€‚coefficientsā€‚areā€‚soā€‚closeā€‚togetherā€‚thatā€‚theyā€‚areā€‚plottedā€‚asā€‚aā€‚continuousā€‚function.

Page 265: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 249

8.4ā€‚ ā€‚Propertiesā€‚ofā€‚Fourierā€‚TransformsQualitatively, theFourier transformisadescriptionof the frequencymakeupofx(t). Figure 8.5 shows the three signals of Figure 8.1 transformed into the fre-quencydomain.Notethatwhendescribingtheirproperties,theactualshapesoftheFouriertransformsareingeneralunimportant(andinthiscasewehavedrawnthem as rounded rectangles). For the moment, we are more interested in theirbeginningandendpoints.Notethatthetransformsarealwayssymmetricaroundtheyaxisbecausewealwaysassumethatx(t)originatesfromanactualwaveformthatisrealizableandreal(andthushasnoimaginarycomponent).Nevertheless,

3200ā€“3200f

200ā€“200

X( f )

(a)

fā€“20 20ā€“20000 20000

Y( f )

(b)

f

880

1320

1760

2200

2640

3080440

ā€“880

ā€“132

0ā€“1

760

ā€“220

0ā€“2

640

ā€“308

0

ā€“440

Z( f )

(c)

Figureā€‚8.5ā€‚ Fourierā€‚ transformsā€‚ forā€‚commonā€‚audioā€‚ signalā€‚ types:ā€‚ (a)ā€‚ speech;ā€‚ (b)ā€‚high-fidelityā€‚audio;ā€‚(c)ā€‚Aā€‚aboveā€‚middleā€‚Cā€‚onā€‚theā€‚piano.

Page 266: Numerical and Analytical Methods with MATLAB for

250ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Fouriertransformsdohaveanimaginarycomponent,andinFigure 8.5,wehaveonlyplottedthemagnitude(andnotthephase).Theideaofasignalhavingcom-plexorā€œnegativefrequencyā€mayappearconfusing,butitissimplyanartifactofourusingthecomplexexponentialas theorthogonal function.Whennecessary,wecanalwayschangeacomplexfrequencybacktoarealfrequencybyapplyingthe identity = +cos sine x j xjx ; inthemeantime,wecantakeadvantageof thesimplifiedmaththatcomes fromā€œbundlingā€thesinesandcosines together intooneexponentialterm.

Mathematically,theFouriertransformmaybeconsideredasubsetofthebilat-eral Laplace transformwheres =j2Ļ€f[1].ItdoesnotprovideascompleteananalysisastheLaplacetransform(e.g.,itcannotbeusedtopredictsystemstability),butitssimplicityallowsconvenient insight into signalbehavior.Aswithany transformtechnique,wecantransformfromonedomaintotheotheratwilltotakeadvan-tageoftheconveniencesofeach.

Wecanderivetheinverse Fourier transformbysubstitutingthedenormalized

Fouriertransform ( )X fT

backintoEquation(8.6)toobtain

āˆ‘

āˆ‘

=

=

Ļ€

=āˆ’āˆž

āˆž

Ļ€

=āˆ’āˆž

āˆž

( ) 1 ( )

( )

2

2

x tT

X nf e

X nf enfn

oj nf t

n

oj nf t o

n

o

o (8.11)

Letting ā†’nf fo and ā†’fn

df ,inthelimitthesumbecomesanintegral:

āˆ«= Ļ€

āˆ’āˆž

āˆž

( ) ( ) 2x t X f e dfj f t (8.12)

Equation(8.12)isthedefinitionoftheinverseFouriertransformofX( f ).Some importantFourier transformpairsare summarized inTable 8.2.Note

thatthesimilarityoftheforwardandinverseFouriertransforms(Equations(8.10)and(8.12)onlydifferbythesignoftheexponential)leadstothedualitypropertyinwhich each entry inTable 8.2 canbe considered a reversiblepair (hence thebidirectional arrow for each entry in the table).For example, given that apulse

(ofwidth2Ļ„)inthetimedomaintransformsto Ļ€ Ļ„Ļ€

sin2 ff

inthefrequencydomain,

wecanalsoinferthataā€œpulseā€inthefrequencydomain(ofwidth2Fo)transforms

to ā‰ ā‰ 

sin2 F tt

o inthetimedomain.

Page 267: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 251

8.5ā€‚ ā€‚FiltersFiltering is the application of a frequency-dependent function on a waveform. ThevarioustypesoffiltersareclassifiedandcharacterizedbytheshapeoftheirfrequencyresponseintheFourierdomainandaresummarizedinTable 8.3.Forexample,alow-passfilterhasaFouriertransformthathasavalueofoneatlowfrequenciesandavalueof

Table 8.2ā€‚ Commonā€‚Fourierā€‚Transformā€‚Pairs

Property Time Domain x(t) ā†” Frequency Domain X(f)

Linearity x(t) = Ay(t) + Bz(t) ā†” X(f) = AY(f) + BZ(f)

Duality X(t) ā†” x(āˆ’f)

Impulse x(t) = Ī“(t) ā†” X(f) = 1

Cosine = Ļ€x t f t( ) cos 2 o ā†” =Ī“ āˆ’ + Ī“ +

X ff f f f

( )( ) ( )

2o o

Sine = Ļ€x t f t( ) sin2 o ā†” =Ī“ āˆ’ āˆ’ Ī“ +

X ff f f f

j( )

( ) ( )2

o o

Pulse =ā‰¤ Ļ„

x tt

( )1

0 otherwiseā†” =

Ļ€ Ļ„Ļ€

X ff

f( )

sin2

Ideal low-pass filter

=Ļ€Ļ€

x tf t

t( )

sin2 o ā†” =ā‰¤

X ff f

( )1

0 otherwise

o

Convolution/multiplication

y(t) = x(t)āˆ—h(t) ā†” Y(f) = X(f)H(f)

Causal decaying exponential

= āˆ’Ī±y t u t e( ) ( ) t ā†” =Ļ€ + Ī±

Y fj f

( )1

2

Causal decaying cosine

= Ļ€āˆ’y t u t e f t( ) ( ) cos 2ato ā†” ( )

=Ļ€ +

Ļ€ + + Ļ€Y f

j f a

j f a f( )

( 2 )

2 (2 )o2 2

Causal decaying sine

= Ļ€āˆ’y t u t e f t( ) ( ) sin2ato ā†” ( )

=Ļ€

Ļ€ + + Ļ€Y f

f

j f a f( )

2

2 (2 )o

o2 2

Page 268: Numerical and Analytical Methods with MATLAB for

252ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

zero(ornearlyzero)athighfrequencies.Inthiscase,thelow-frequencyregioniscalledthepassbandbecausesignalsarepassedthroughthefilterunchanged,andthehigh-frequencyregioniscalledthestopbandbecausesignalsinthisregionarestoppedbythefilter.Conversely,ahigh-passfilterhasthestopbandatlowfrequenciesandthepassbandathighfrequencies.Inabandpassfilter,thepassbandhasbothalowandahighlimit.Aband reject(oppositeofbandpass)hasalowandhighlimitonthestopband.Anequal-izerhasmultiplepassbandsofvaryingmagnitudesandistypicallyusedtocompensatefornonlinearfrequencybehaviorinanamplifierorcommunicationchannel.

Figure 8.6ashowsanexampleofanideallow-passfilterwithcutofffrequencyfo and corresponding frequency response HI( f ) (where the I subscript denotesā€œidealā€).IfweapplythisfiltertoawaveformwithFouriertransformX( f )contain-ingfrequencieswithintherange < <1 2f f f ,thenthefilteroutputistheproduct

( ) ( )IH f X f ,andallfrequenciesgreaterthanfoareremoved.Unfortunately,thereisafundamentalproblemwiththisidealā€œbrickwallā€filterin

thefrequencydomain.WeknowfromTable 8.2thatmultiplicationinthefrequencydomaincorrespondstoconvolutioninthetimedomain.IfweexamineHI(f )inthe

time domain, we see that the corresponding function =Ļ€Ļ€

( ) sin2h t

f ttI

o extends

infinitelyforallĀ±t.Thus,toconvolvex(t)with ( )h tI ,weneedtoknowallvaluesofx(t),

Low-pass:

High-pass:

Bandpass:

Band reject:

Equalizer:

HEQ( f )

HLP( f )

HBP( f )

HHP( f )

HBR( f )

f

f

f

f

f

Table 8.3ā€‚ Frequencyā€‚Reponseā€‚forā€‚Commonā€‚Filterā€‚Types

Page 269: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 253

includingthosefort <0.Afilterthatdependsonvaluesfort <0iscalledanoncausalfilterandisimpossibletoimplement,bothwithnumericalalgorithmsandrealcircuitcomponents.

Given that we cannot implement an ideal filter, there are various alternativeapproachesthatcanbeusedinstead.Oneapproachistoapplyawindow functionto

( )h tI tomakeitcausal,andthesimplestwindowfunctionistomultiply ā‰ ā‰ 

sin2 f tt

o

byarectangularwindowtotruncatetheinfinitetailsof ( )h tI ,thusforcingittobecausal.AnotherapproachistouseaknownrealizablefiltercharacteristicsuchastheButterworthorChebyshev responses.Ineithercase,thenetresultistoremovethedis-continuityinthefrequencyresponseat f o .Thecorresponding ( )H fR (wheretheRmeansā€œrealizableā€)isasmoothfilterthatcanactuallybeimplemented.ThisisshowninFigure 8.6b,where ( )H fR nowhascurvededges,andtheresultingfilteredoutputalsohassimilaredges.

8.6ā€‚ ā€‚Discrete-Timeā€‚Representationā€‚ofā€‚Continuous-Timeā€‚Signals

Indigital signal processing(andinMATLAB),werepresentacontinuous-timesignalas a sequenceofnumbersby theprocessof sampling.Figure 8.7a showsa typicalcontinuous-timesignalx(t)(withthetimeargumentdenotedbyparentheses)anditsdiscrete-timecounterpartx[n](wherethediscreteargumentisdenotedwithsquarebrackets).Wederivex[n]fromx(t)byextractingthevaluesofx(t)atanevenlyspaced

f1 f2āˆ’f1āˆ’f2 foāˆ’fo āˆ’fo fof1āˆ’f1

X( f ) HI ( f ) X( f )HI ( f )

(a)

X( f ) X( f )

f1 f2āˆ’f1āˆ’f2 foāˆ’fo āˆ’fo fof1āˆ’f1

HR( f ) HR( f )

(b)

Figureā€‚8.6ā€‚ (a)ā€‚Anā€‚idealā€‚ā€œbrickā€‚wallā€ā€‚low-passā€‚filterā€‚withā€‚cutoffā€‚frequencyā€‚fo.ā€‚(b)ā€‚Aā€‚realizableā€‚low-passā€‚filterā€‚necessarilyā€‚hasā€‚aā€‚smoothā€‚transitionā€‚band.

Page 270: Numerical and Analytical Methods with MATLAB for

254ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

intervalofsizeT,calledthesampling time(orequivalentlyatasampling rate =1 ).fTS

Mathematically,weconvertfromcontinuoustodiscretetimewiththeformula x[n]=x(nT ) (8.13)wherenisaninteger.Notethatadiscretesignalx[n]doesnotinherentlycarryanytimeinformationbutratherisjustaseriesofvaluesforxindexedbythedimension-less integern.Thus,oncewesampleacontinuous-timesignal, it is importanttorememberthesampletimeTifweeverwishtoconvertthediscreteversionbacktocontinuoustime.

Wemustalsotakecaretochooseanappropriatesamplerate.Figure 8.7bshowswhatcanhappenifwechooseTtoolarge.Thecorrespondingdiscretesignaly[n]

ismissingthehigh-frequencysinecomponent(withfrequencyofexactly 1 )T

thatā€œridesā€ atop y(t). Thus, sampling a continuous-time signal does not guaranteeuniquenessinthediscretedomain,asevidencedinFigure 8.7bythefactthatx[n]andy[n]areidentical.The sampling theoremstatesthattofullydescribeacontin-uous-timesignaldiscretely,wemustchooseasamplingratethatisat leasttwice

ā€“1

1

ā€“1

1

x[n]x(t)

t n20 40 60 80 100 2 4 6

8 10T

(a)

20 40 60 80

ā€“1

1

2 4 68 10

ā€“1

1

y(t) y[n]

t n100

(b)

Figureā€‚8.7ā€‚ (a)ā€‚Aā€‚typicalā€‚continuous-timeā€‚signalā€‚x(t)ā€‚andā€‚itsā€‚correspondingā€‚dis-crete-timeā€‚signalā€‚x[n],ā€‚whichā€‚isā€‚derivedā€‚byā€‚samplingā€‚x(t)ā€‚everyā€‚Tā€‚seconds.ā€‚(b)ā€‚Ifā€‚y(t)ā€‚hasā€‚anā€‚additionalā€‚high-frequencyā€‚componentā€‚withā€‚aā€‚periodā€‚ofā€‚anā€‚exactā€‚fractionā€‚ofā€‚T,ā€‚thenā€‚thatā€‚componentā€‚isā€‚invisibleā€‚inā€‚theā€‚correspondingā€‚y[n].

Page 271: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 255

asfastasthehighest-frequencycomponentoftheoriginalsignal.Inpractice,weusuallychooseasamplingratethatisslightlyhigherthantheminimumrequiredto account for circuit imperfections and component variations. For example, inaudioCDs,whichcanreproducefrequenciesupto20,000Hz,thesamplingrateis44,100samples/sec(insteadoftheminimumvalueof40,000samples/sec).

Therearemanymotivationsforconvertingcontinuous-timesignalstodiscretetime,butourimmediatereasonissowecanuseadigitalcomputertocarryoutthesignalprocessingwithaprogramlikeMATLAB.

8.7ā€‚ ā€‚Fourierā€‚Transformsā€‚ofā€‚Discrete-Timeā€‚SignalsThecontinuous-timeFouriertransform(whichwenowrefertoastheCFT)intro-ducedinSection8.3canbeextendedtodiscrete-timesystemsasthediscrete-time Fourier transform(DTFT)X(Ļ•)andisdefinedas

āˆ‘Ļ† = āˆ’ Ļ€ Ļ†

=āˆ’āˆž

āˆž

( ) [ ] 2X x n e j n

n

(8.14)

ThecorrespondinginverseDTFTiscalculatedby

āˆ«= Ļ† Ļ†āˆ’

Ļ€ Ļ†[ ] ( )1/2

1/2

2x n X e dj n (8.15)

NotethattheDTFTinEquation(8.14)isdefinedasasummation(insteadofanintegral)duetothediscretenatureofx[n].Inaddition,becausex[n]isdimensionless,thecorrespondingX(Ļ•)isalsodimensionless.Equation(8.14)isperiodicinĻ•duetothe āˆ’ Ļ€ Ļ†2e j n term;thus, it issufficienttoexamineX(Ļ•)overtherange āˆ’ ā‰¤ Ļ† ā‰¤1

212

insteadofover all frequencies, as for theCFT. Ifx[n]wasderivedby sampling acontinuous-timesignalx(t)atasamplingratefS,thenĻ•correspondstothefrequency

range āˆ’ ā‰¤ ā‰¤2 2f

ffS S ,which corresponds to the rangeof useful frequencieswith

respecttothesamplingtheorem.ItisimportanttorealizethattheDTFTisacontinuousfunctionandnota

discreteone.Asanexample,supposea1000-Hzsinewaveissampledat44100samples/sec.Thisimpliesthatthecorrespondingdiscreteversionofthe1000-Hzsinewavewillrepeatevery44.1samples,andthecorrespondingX(Ļ•)willhave

nonzerocomponentsat Ļ† = Ā± 100044100

,which isclearlynotawholenumber.If

x[n]containsavarietyoffrequencycomponents,thentheywillallberepresentedinX(Ļ•)attheircorrespondingratiotofSandwillgenerateacontinuousfunction.

BecauseEquation (8.14) isperiodicwith respect toĻ•, thevaluesofX(Ļ•) forĻ† > 1

2 are merely repeated copies of the values in the region āˆ’ ā‰¤ Ļ† ā‰¤12

12 . The

Page 272: Numerical and Analytical Methods with MATLAB for

256ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

implicationofthisisthatwecantreatx[n]asaperiodicfunctionthatcanberep-resentedbyaFourierserieswhosecoefficientscanbefoundbysamplingX(Ļ•).ThisisareverseapplicationofthesametechniqueweusedinSection8.2toderivetheCFTastheā€œsmearā€oftheFouriercoefficientsofaperiodiccontinuous-timewave-form.Mathematically,theā€œunsmearā€oftheDTFTintoitsFouriercoefficientsiscalledthediscrete Fourier transform(DFT)andisdefinedas

āˆ‘= āˆ’ Ļ€

=

āˆ’

[ ] [ ] 2 /

0

1

X k x n e j nk N

n

N

(8.16)

āˆ‘= Ļ€

=

āˆ’

[ ] 1 [ ] 2 /

0

1

x nN

X k e j nk N

k

N

(8.17)

whereNisthenumberofpointsweusedtosampleX(Ļ•).WehaveusedtheletterktorepresenttheindexoftheDFTinthedimensionlessā€œdiscretefrequencyā€domain

(correspondingtothephysicalfrequencies0throughfSinstepsof āˆ’1

1NfS ).

Note thatwhereas theDTFTuses the range āˆ’ ā‰¤ Ļ† ā‰¤12

12

and is symmetric

aroundtheyaxis,byconventiontheDFTusestherange0ā‰¤k ā‰¤N āˆ’1andthusisdefinedfork ā‰„0,thatis,intherighthalfplane.ThereasonforthisisthatadiscretewaveformcanonlybesymmetricaroundtheyaxisifithasanoddvalueofN,andtheDFTisoftencalculatedusinganevenvalueforN(usuallyapoweroftwo).Theimplication(asweshallseeintheexample)isthattheresultingDFTwillbesym-

metricabout =āˆ’12

kN insteadofk =0.

Theprecedingderivationsmayappearcomplicatedandabstract,butthereisamajoradvantagetousingtheDFTinsteadoftheDTFT:TheDFTcanbecom-putedusing the fast Fourier transform (FFT)algorithm[2].TheFFTprovides acomputationally efficientway to calculateEquation (8.16)byusingonly integeradditionsandmultiplications,thusenablingfrequency-domaincomputationstobeeasilyimplementedwithalow-costdigital signal processor(DSP).WhilethetermFFTisoftenusedinterchangeablywithDFT,intruththeFFTissimplyoneofseveralknownmethodsthatmaybeemployedforcomputingtheDFT.

MATLABprovidesthefftfunctionforcalculatingFFTsofdiscretesignals.ExecutingX=fft(x)willreturnthen-pointFFTofthevectorx,wherenisthenumberofelementsinx.Alternatively,youmayexplicitlyspecifythenumberofpointsintheFFTbyaddingasecondargumenttofft.Thus,runningX=fft(x,64)willcalculatea64-pointFFTonthevectorx;ifxhasgreaterthan64elements,thentheextraelementswillbediscardedintheFFTcalculation,andifxhasfewerthan64elements,thenxwillbeautomaticallyextendedto64elements(bypaddingwithzeros)priortotheFFTcalculation.MATLABalsohasacorre-spondingifftfunctionforcomputingtheinverseDFT.

Page 273: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 257

Exampleā€‚8.3

Let x(t) be the triangular waveform in Figure 8.8 with width 1 msec, height 1 V, and total waveform length of 4 msec. Assuming a sampling rate of 10 kilosamples/sec:

1. Calculate Ļ†X( ) (the DTFT magnitude) directly from its definition in Equation (8.14).

2. Calculate X k[ ] (the DFT magnitude) directly from its definition in Equation (8.16).

3. Calculate X k[ ] using MATLABā€™s fft() function.

%Example_8_3.m%CalculatetheDTFTandDFTforatriangularwaveform.%First,definex(t)triangle_width=1e-3;triangle_height=1;T=1e-4;triangle_slope=triangle_height/(triangle_width/2);fs=1/T;t=0:T:4e-3;n=t/T;N=length(n);%definediscretetrianglewaveformx[n]x=zeros(1,N);x(1:6)=0:triangle_slope*T:triangle_height;x(6:11)=1:-triangle_slope*T:0;%definephiforDTFTwitharbitrarygranularityof200%stepsphi=-.5:.005:.5;%definekforDFTassamelengthasx[n]k=0:N-1;%initializeDTFTandDFTvarsX_DTFT=zeros(1,length(phi));X_DFT=zeros(1,length(k));%calculateDTFTandDFTbasedondefinitions(sumof%complexexponentials)fori=1:length(n)X_DTFT=X_DTFT+x(i)*exp(-j*2*pi*n(i)*phi);X_DFT=X_DFT+x(i)*exp(-j*2*pi*n(i)*k/N);end%Calculate41-pointFFTwithMATLAB'sfft()functionX_FFT=fft(x);

1 2 3 4

1

t (ms)

x(t)

Figureā€‚8.8ā€‚ Triangularā€‚continuous-timeā€‚waveformā€‚x(t).

Page 274: Numerical and Analytical Methods with MATLAB for

258ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%plotresultssubplot(4,1,1);stem(n,x);xlabel('n');ylabel('x[n]');subplot(4,1,2);plot(phi,abs(X_DTFT));xlabel('\phi');ylabel('X(\phi)(DTFT)');subplot(4,1,3);stem(k,abs(X_DFT));xlabel('k');ylabel('X[k](DFT)');subplot(4,1,4);%plotFFThorizaxisasproportionofsamplingratestem(k/(N-1)*fs,abs(X_FFT));xlabel('f=fs*(k/(N-1))(Hz)');ylabel('X[k](FFT)');

-------------------------------------------------------------------

Results are shown in Figure 8.9. Some observations are as follows:

ā—¾ The discrete-time version of the triangle function is denoted x[n] and is shown in Figure 8.9a.

ā—¾ The DTFT of x[n] is shown in Figure 8.9b and has the shape of x

xsin2

2 .

This makes sense because a triangle waveform can be constructed by convolving two rectangular pulses, and thus in the frequency domain

looks like the product of two xx

sin functions.

ā—¾ The results for the DTFT (Figure 8.9b) and DFT (Figure 8.9c) are iden-tically shaped, but the DFT plots the ā€œnegativeā€ frequencies on the right half of the plot instead of the left. However, since the DFT is always symmetrical, we can simply discard the right half of the plot (or at least ignore it in our heads).

ā—¾ The results for the sum-of-complex-exponentials DFT (Figure 8.9c) and the MATLAB-calculated FFT (Figure 8.9d) are identical, as expected. However, in Figure 8.9d, we chose to label the x axis in

terms of āˆ’k

NfS

1 (in Hertz) instead of the abstract dimensionless k parameter, thus providing more context for the plot.

8.8ā€‚ ā€‚Aā€‚Simpleā€‚Discrete-Timeā€‚FilterAsdescribedinSection8.3,afilterisasysteminwhichtheinput/outputrelation-shipissomefrequency-dependentfunction.Incontinuous-timefilterdesign,ananalog circuit containing capacitors, inductors, and amplifiers is typically usedto implement the desired response. The filter is characterized by its frequencyresponseH( f )andcorrespondingimpulseresponseh(t),providinganinput/out-put relationshipdeterminedbyY( f )=H( f )X( f ) in the frequencydomainory(t)=h(t)āˆ—x(t)inthetimedomain(wheretheā€œ*ā€indicatesconvolution).Ifx(t)istheDiracdeltafunctionĪ“(t),theny(t)=h(t)becauseanyfunctionconvolvedwithĪ“(t)isitself.

Page 275: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 259

0 5 10 15 20 25 30 35 400

0.5

1

n

x [n

]

(a)

ā€“0.5 0 0.50

2

4

6

Ļ†

X (

Ļ†) (

DT

FT

)

(b)

0 5 10 15 20 25 30 35 400

2

4

6

k

X [k

] (D

FT

)

(c)

f = fs*(k/(N ā€“ 1)) (Hz)

0 2000 4000 6000 8000 100000

2

4

6

X [k

] (F

FT

)

(d)

Figureā€‚8.9ā€‚ (a)ā€‚Discrete-timeā€‚versionā€‚ofā€‚theā€‚triangleā€‚waveformā€‚inā€‚Figureā€‚8.8.ā€‚(b)ā€‚Theā€‚DTFTā€‚magnitudeā€‚|X(š›Ÿ)|.ā€‚(c)ā€‚Theā€‚DFTā€‚magnitudeā€‚|X[k]|.ā€‚(d)ā€‚Theā€‚DFTā€‚asā€‚com-putedā€‚byā€‚MATLABā€™sā€‚fft()ā€‚function.ā€‚Noteā€‚thatā€‚inā€‚theā€‚lastā€‚case,ā€‚theā€‚frequencyā€‚axisā€‚hasā€‚beenā€‚rescaledā€‚fromā€‚0ā€‚toā€‚fSā€‚insteadā€‚ofā€‚zeroā€‚toā€‚N.

Page 276: Numerical and Analytical Methods with MATLAB for

260ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Incontinuous-timefilters,h(t)andĪ“(t)arelargelyamathematicalconveniencebecauseit is impossibletocreateadeltafunctionexactlyinthelab(thoughit isoftenapproximatedbyashortpulse).Ontheotherhand,indiscrete-timesystems,itispossibletorepresentthediscretedeltafunctionĪ“[n]accurately(alsocalledtheunit samplefunctionorKronecker deltafunction).ThediscretedeltafunctionĪ“[n]issimplyasequencewithavalueofoneatn =0andzerootherwise(seeFigure 8.10)andthusistriviallyimplementable.Inaddition,anydiscretesequencex[n]canbeexpressedasasumofdelayeddeltas.Forexample,thex[n]showninFigure 8.11acanbewrittenmathematicallyas

x[n]=0.5Ī“[n]+1.5Ī“[n āˆ’1]+Ī“[n āˆ’2]āˆ’0.5Ī“[n āˆ’3]

Therefore, ifwecandesignalinearsystemwithknownbehaviorforĪ“[n]withacorrespondingimpulseresponseh[n],thenwecanusethatsystemtoprocessanyx[n].Inthiscase,weknowtheoutputpreciselybecausex[n]isjustaweightedsumofdeltafunctions.

ThisconceptisillustratedbythesysteminFigure 8.11b,whichimplementstheimpulseresponseofFigure 8.11a.Conceptually,thissystemisbuiltfromamplifi-ers,anadder,anddelay elements(denotedbyā€œDā€inthediagram)whosepurposeistostorethevalueofasignalforexactlyoneā€œtickā€ofn.Inpractice,weusecomputerregistersforthedelayelementsandcomputerarithmeticforthemultiplicationandaddition.Thesystemworksasfollows:

1.Initially,assumethatallofthedelayelementscontainthevaluezero;thus,theoutputiszero

2.Atā€œtimeā€n =0,theinputdeltafunctionisone;thus,thesummedoutputofthesystemis0.5

3.Atn =1,theinputreturnstozero.However,theonefromn =0isstoredinthefirstdelayelement;thus,thesummedoutputis1.5

4.Atn =2,theinputremainszero,andtheoneisshiftedtothenextdelayele-ment,causingthesummedoutputtobe1.0.

ā€“1 1 2 3 4 5

1

Ī“[n]

n

Figureā€‚8.10ā€‚ Theā€‚discrete-timeā€‚versionā€‚ofā€‚theā€‚deltaā€‚functionā€‚consistsā€‚ofā€‚aā€‚singleā€‚sampleā€‚ofā€‚unityā€‚heightā€‚atā€‚n =ā€‚0ā€‚andā€‚zerosā€‚elsewhere.

Page 277: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 261

5.Atn =3, theonegetsshiftedtothefinaldelayelement,andthesummedoutputisāˆ’0.5.

6.Finally,forn >3,allofthedelayelementsagaincontainzeroandtheoutputreturnstozero.

Thus,theoutputsequenceofthissystemwithrespecttonduetoadeltafunctioninputwillbe0.5,1.5,1.0,āˆ’0.5,whichcorrespondstothesamesequenceash[n]inFigure 8.11a.

ThistypeoffilterisgeneralizedinFigure 8.12forNdelayelementsandiscalledanNth-order(orequivalentlyanN +1ā€œtapā€)finite impulse response(FIR)filter.Mathematically,thissystemcalculatestheconvolutiony[n]=h[n]āˆ—x[n].

ThereareseveralmethodsfordesigningFIRfilters[3],andthesimplestmethodwasdescribed inSection8.5:Beginwithan idealbrickwall frequency response

ā€“1 1 23

4 5

1

2

h[n]

n

ā€“1

(a)

D

D

D

+

0.5

1.5

1.0

ā€“0.5

Ī“[n]

0.5 for n = 01.5 for n = 11.0 for n = 2

āˆ’0.5 for n = 30 otherwise

y[n]=

Figureā€‚ 8.11ā€‚ (a)ā€‚ Typicalā€‚ impulseā€‚ responseā€‚ h[n]ā€‚ forā€‚ aā€‚ discrete-timeā€‚ filter.ā€‚ (b)ā€‚ Aā€‚circuitā€‚toā€‚implementā€‚aā€‚filterā€‚withā€‚impulseā€‚responseā€‚h[n]ā€‚consistsā€‚ofā€‚threeā€‚delayā€‚elements,ā€‚fourā€‚multipliers,ā€‚andā€‚anā€‚adder.

Page 278: Numerical and Analytical Methods with MATLAB for

262ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

( )H fI , convert ( )H fI to the time domain to obtain a noncausal impulseresponse ( )h tI ,thenapplyawindowfunctiontotruncatethetailsof ( )h tI ,thuscreatingarealizableimpulseresponse ( )h tR .Wealsoshift ( )h tR intimesothatitbeginsatt =0.Thus,foranideallow-passfilter(showninFigure 8.13a)withcutoff

frequency f o ,theidealimpulseresponseis =Ļ€Ļ€

( ) sin2h t

f ttI

o ,andthecorrespond-ingrealizableimpulseresponseis

=

Ļ€ āˆ’

Ļ€ āˆ’ā‰¤

( )

sin22

2

for

0 otherwise

h t

f tt

tt

t tR

ow

ww

(8.18)

wheretwisthewidthoftherectangulartruncationwindow(seeFigure 8.13b).Toimplementasadiscrete-timefilterwithsamplingratefS(andcorrespondingsam-

plingtime =1

TfS

),weconvert ( )h tR to [ ]h nR byapplyingt =nT;thus,

( )( )=Ļ€Ļ† āˆ’

Ļ€ āˆ’ā‰¤

[ ]sin2

for

0 otherwise

2

2h nn

nn W

R

oW

W

where Ļ† = f fo o S isthediscrete-timefiltercutofffrequency,and =W t Tw isthewindowwidth(seeFigure 8.13c).NotethatthenumberoftapsintheFIRfilterisW +1,correspondingtoWtapsforn =1,2,3,ā€¦,Wplusonemoreatn =0.

D

D

+

x[n]

y[n]

a0

a1

aN

Figureā€‚8.12ā€‚ Generalā€‚circuitā€‚toā€‚implementā€‚anā€‚N +ā€‚1ā€‚tapā€‚FIRā€‚filter.

Page 279: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 263

t

hI(t)

2 fo

1fo

(a)

t

hR(t)

tw

(b)

n

hR[n]

W

(c)

Figureā€‚8.13ā€‚ (a)ā€‚Idealā€‚ impulseā€‚responseā€‚hI(t)ā€‚ forā€‚anā€‚idealā€‚ low-passā€‚filter.ā€‚ (b)ā€‚Byā€‚shiftingā€‚andā€‚truncatingā€‚hI(t),ā€‚weā€‚obtainā€‚aā€‚realizableā€‚impulseā€‚responseā€‚hR(t).ā€‚(c)ā€‚Byā€‚samplingā€‚hR(t),ā€‚weā€‚obtainā€‚hR[n],ā€‚whichā€‚canā€‚beā€‚implementedā€‚asā€‚aā€‚discrete-timeā€‚FIRā€‚filter.

Page 280: Numerical and Analytical Methods with MATLAB for

264ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚8.4

Design a low-pass, discrete-time, rectangular-window FIR filter with cutoff frequency of =fo 1000 Hz. Assume a sampling rate of =fS 40000 samples/sec and use 401 taps.

A 401-tap filter implies that the impulse response should have a length of W = 400T. Thus, for a rectangular window, we create a realizable version of this filter by shifting h tI ( ) to the right by 200T and then truncating the tails for t < 0 and t > 400T to obtain hR (t). The resulting realizable 401-point hR[n] is

( )

( )=

Ļ€ āˆ’

Ļ€ āˆ’ā‰¤ ā‰¤h n

ff

n

nnR

o

S[ ]sin2 200

200for 0 400

0 otherwise

Next, we create an input signal x(t) to send into our filter. We want an input signal that contains components in both the passband and stopband; thus, we arbitrarily choose an x(t) containing components at 500, 1500, and 3000 Hz. Thus,

x(t) = sin 2Ļ€ 500t + sin 2Ļ€ 1500t + sin 2Ļ€ 3000t

In discrete time, the corresponding x[n] is

= Ļ€ + Ļ€ + Ļ€x n n n n[ ] sin 2

50044100

sin 2150044100

sin 2300044100

A MATLAB program to implement this FIR filter follows:

%Example_8_4.m%ThisexampleimplementsanFIRlow-passfilterusinga%truncatedsincfunction(equivalenttoanidealfilter%witharectangularwindow)clc;clear;%definesamplingrate:fs=40000;T=1/fs;%definecutofffrequencyoflow-passfilter:fo=1000;%definefrequenciesofinputsignalx(t):input_freqs=[50015003000];%definefilterorder(N):taps=401;N=taps-1;%Note:fromthispointforward,wewilloperateinthe%dimensionlessdiscrete-time"n"domain.First,we%redefinethefiltercutofffrequencyintermsofthe%dimensionlessPhiparameteroftheDTFT:phi_o=fo/fs;%Definehr[n]asashiftedsincfunctionover401tapsfori=1:tapsn=i-1;shifted_n=(n-N/2);hr(i)=sin(2*pi*phi_o*shifted_n).../(pi*shifted_n);%Note:sincesin(x)/xissingularforx=0,catch

Page 281: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 265

%thiscaseandinserttheappropriatelimitvalue.%Otherwise,ourhr[n]won'tworkbecauseitwill%haveasingle"NaN"valueatthepeak.ifshifted_n==0hr(i)=2*phi_o;endend%Runthefilterforalongtimesothatwecanbesure%toreachthesteadystate.Arbitrarilychoose20000%samples.max_n=fs/2;n=0:max_n;%Definex[n].First,rescaletheinputfrequenciestobe%fractionsoffs:input_phis=input_freqs/fs;x=zeros(1,length(n));fori=1:length(input_phis)x=x+sin(2*pi*input_phis(i)*n);end%Shiftx[n]to"turnon"atatimegreaterthanthe%numberoftapsofthefilter.Thisisequivalentto%settingtheinitialconditionsofthefiltertozero.x_shifted=zeros(1,length(n));x_shifted(taps:length(n))=x(1:length(n)-N);%Computey[n]bysimulatingthedelaycircuitofFigure%8.12.Thisisequivalenttoconvolvingx[n]withhr[n].y=zeros(1,length(n));fori=taps:length(n)forj=1:taps%calculatethevalueforeachtapandaddtothe%runningtotaly(i)=y(i)+hr(j)*x_shifted(i-j+1);endend%Convertthediscretesignalshr[n],x[n],andy[n]to%thetimedomainbyrescalingthehorizontalaxisand%connectingthedots.interesting_interval=1400*T;subplot(3,1,1);plot(T*n(1:taps),hr);%rescaletheaxestoseetheinterestingparts:axis([0interesting_interval-.02.06]);ylabel('h_R(t)');title('FIRfilterw/rectangularwindow,timedomain');subplot(3,1,2);plot(T*n,x_shifted);axis([0interesting_interval-33]);ylabel('x(t)');subplot(3,1,3);plot(T*n,y);ylabel('y(t)');xlabel('t(sec)');axis([0interesting_interval-1.51.5]);figure;%Seehowgoodourfilterisbycomputinga4096-point%DFTofx[n]andy[n]andplottingonsemilogaxes.%Rescalethehorizontalaxistobeinunitsoffrequency

Page 282: Numerical and Analytical Methods with MATLAB for

266ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%insteadofthedimensionless"k"parameteroftheDFT.fft_points=4096;scaled_freqs=0:fs/(fft_points-1):fs;interesting_freq=6000;subplot(3,1,1);HR=fft(hr,fft_points);semilogy(scaled_freqs,abs(HR));ylabel('|H_R(f)|');%rescaletheaxestoseetheinterestingparts:axis([0interesting_freq1e-41e1]);title('FIRfilterw/rectangularwindow,freqdomain');subplot(3,1,2);%Calculatethefftontheendpartofx[n]andy[n]so%thatwearesurethatweareinthesteadystate%portion.x_end=x(end-fft_points+1:end);X=fft(x_end);semilogy(scaled_freqs,abs(X));axis([0interesting_freq1e-11e4]);ylabel('|X(f)|');subplot(3,1,3);y_end=y(end-fft_points+1:end);Y=fft(y_end);semilogy(scaled_freqs,abs(Y));axis([0interesting_freq1e-11e4]);ylabel('|Y(f)|');xlabel('f(Hz)');

-------------------------------------------------------------------

The time-domain signals hR(t), x(t), and y(t) for this filter are shown in Figure 8.14. Note that these plots transform the discrete-time signals back to continuous time by rescaling the horizontal axis by a factor of nT. In addition, although we calculated y(t) for 0.5 sec, we only plotted the ā€œinter-estingā€ part of the plot (for t < 35 ms). As expected, the multifrequency signal x(t) is reduced by the filter to its low-frequency component at 500 Hz, as can be seen in the plot of y(t).

In Figure 8.15, we show the frequency-domain results for the filter by running the fft function on hR(n), xn, and y[n]. In this case, we run a 4096-point FFT on all three signals. Then, these discrete-frequency DFT results are rescaled to the frequency domain and plotted on semilog axes for the interesting portion (f < 6000 Hz). Note the following:

ā—¾ When viewed in the frequency domain, our truncated ideal impulse response causes ripples in both the passband and stopband and causes a nonzero stopband.

ā—¾ The magnitude of the input signal X(f) contains three identical com-ponents at 500, 1500, and 3000 Hz.

ā—¾ The magnitude of the output signal Y(f) contains the passband com-ponent at 500 Hz plus reduced (but nonzero) components at 1500 and 3000 Hz.

Dependingontheapplication,thisFIRfiltermayormaynotbesufficienttoprovidethedesiredresults.Forexample,inaudioapplications,thepassbandripple

Page 283: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 267

maycauseaudibleinaccuraciesintheresultingfilteredoutput.Ontheotherhand,inotherapplications,aminimaltransitionregionbetweenpassbandandstopband(called the transition band) may be the most desirable, regardless of the ripple.Onemethodforalteringthefilterfrequencyresponseisbyapplyingdifferentwin-dowfunctionstotheidealfilterresponse.AcomparisonofwindowsisshowninFigure 8.16,whichshowstheidealimpulseresponsehI(n),threedifferentwindowsw[n],thecorrespondingrealizableimpulseresponsehR(n),andtheresultingFouriertransform.The three examples shownare the rectangularwindow (also calledaā€œboxcarā€),whichwehavealreadydiscussed;aBartlettwindow(atriangle);andaHammingwindow,whichhasacosineshapewithanaddedDCcomponent.Thethreewindowsareexpressedmathematicallyas

=

= āˆ’ āˆ’

= āˆ’Ļ€

rectangular: [ ] 1

Bartlett: [ ] 22 2

Hamming: [ ] 0.56 0.46cos 2H

w n

w nN

Nn

N

w nn

N

R

B

0 0.005 0.01 0.015 0.02 0.025 0.03 0.035ā€“0.02

0

0.02

0.04

0.06

h R(t

)FIR Filter Using Rectangular Window, Time Domain Results

0 0.005 0.01 0.015 0.02 0.025 0.03 0.035

ā€“2

0

2

x(t)

0 0.005 0.01 0.015 0.02 0.025 0.03 0.035

ā€“1

0

1

y(t)

t (sec)

Figureā€‚8.14ā€‚ MATLAB-generatedā€‚plotā€‚ ofā€‚ anā€‚ FIRā€‚filterā€‚ andā€‚ itsā€‚ inputā€‚ andā€‚outputā€‚signals.ā€‚Byā€‚applyingā€‚hR(t)ā€‚toā€‚x(t),ā€‚weā€‚obtainā€‚theā€‚resultingā€‚y(t),ā€‚whichā€‚hasā€‚theā€‚com-ponentsā€‚aboveā€‚1000ā€‚Hzā€‚filteredā€‚out.

Page 284: Numerical and Analytical Methods with MATLAB for

268ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

wheren =0,1,2,ā€¦,N.Theresultingfrequencyresponsesarealllowpass,butwithvaryingshapes.Therectangularwindowgivesthemostrippleinthepassbandandstopbandbutalsohasthesharpesttransitionband.TheBartlettwindowcauseslessripplethantherectangularwindowbuthasawidertransitionband.TheHammingwindowhasthelargestdifferentialbetweenthepassbandandstopband;thatis,ithasthelargestdropbetweenthepassbandandthefirstlobeofthestopband.

0 1000 2000 3000 4000 5000 600010ā€“4

10ā€“2

100

|HR(

f)|

FIR Filter Using Rectangular Window, Frequency Domain Results

0 1000 2000 3000 4000 5000 6000

100

102

104

|X(

f)|

0 1000 2000 3000 4000 5000 6000

100

102

104

|Y(

f)|

f (Hz)

Figureā€‚8.15ā€‚ Fourierā€‚transformsā€‚ofā€‚theā€‚signalsā€‚ofā€‚Figureā€‚8.14ā€‚plottedā€‚onā€‚semilogā€‚axes.ā€‚ Theā€‚ topā€‚ plotā€‚ showsā€‚ thatā€‚ theā€‚ frequencyā€‚ responseā€‚ ofā€‚ theā€‚ shiftedā€‚ andā€‚ trun-catedā€‚idealā€‚impulseā€‚responseā€‚hasā€‚rippleā€‚inā€‚theā€‚passbandā€‚andā€‚stopband.ā€‚Theā€‚twoā€‚rightmostā€‚peaksā€‚visibleā€‚inā€‚|X(f)|ā€‚(middleā€‚plot)ā€‚areā€‚substantiallyā€‚reducedā€‚inā€‚|Y(f)|ā€‚(bottomā€‚plot).

Page 285: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 269

ProjectsProject.8.1

In telephony,DTMF (dual-tone multifrequency) is used to encode and transmitkeypressesfromalocalhandsettoaremotereceiveroverthetelephonenetwork.FigureP8.1showsa simplifiedrepresentationofa telephonekeypadwithsevenswitchesandsevensinusoidalvoltagesources.Theswitchesarearrangedsuchthatonanykeypress,twoswitchesforthecorrespondingrowandcolumnwillclose,

Rectangular (boxcar) window:

Bartlett (triangular) window:

Hamming (raised cosine + DC) window:

idealimpulse

responsewindow

realizableimpulse

response

frequencyresponse

HR(Ļ†)hI[n] w[n]

wH[n]

wB[n]

wR[n]

hR [n] = hI [n]w [n]

Figureā€‚ 8.16ā€‚ Anā€‚ exampleā€‚ ofā€‚ someā€‚ ofā€‚ theā€‚ windowā€‚ functionsā€‚ w[n]ā€‚ thatā€‚ mayā€‚ beā€‚appliedā€‚toā€‚anā€‚idealā€‚low-passā€‚impulseā€‚responseā€‚hI[n]ā€‚toā€‚createā€‚aā€‚realizableā€‚impulseā€‚responseā€‚hR[n]ā€‚forā€‚useā€‚inā€‚anā€‚FIRā€‚filter.ā€‚Noteā€‚thatā€‚toā€‚makeā€‚theā€‚plotsā€‚moreā€‚readable,ā€‚theā€‚discrete-timeā€‚waveformsā€‚areā€‚drawnā€‚asā€‚continuousā€‚(byā€‚ā€œconnectingā€‚theā€‚dotsā€).ā€‚Theā€‚correspondingā€‚realizableā€‚DTFTā€‚frequencyā€‚responsesā€‚HR(š›Ÿ)ā€‚areā€‚alsoā€‚shown.

Page 286: Numerical and Analytical Methods with MATLAB for

270ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

therebyconnectingtwoofthevoltagesourcestotheadderonthelowerright.TheresultingoutputvoltageVDTMFwillcontainthesumoftwodistinctfrequenciesthataresenttotheremotereceiver.Forexample,thefactthatā€œ2ā€isinthetoprowandcentercolumnofthebuttonarraywillcausesignalsof697Hzand1336Hztobesummedandsenttotheremotereceiver.Onreceivingthetransmittedsignal,thereceivercandeterminewhichbuttonwaspressedbydeterminingthetwouniquefrequenciesinthereceivedwaveform.

1. Write a MATLAB function named dtmf.m that generates the appropriateDTMFtonesforthenumerals0through9(donotworryaboutthe*and#buttonsfornow).Yourfunctionshouldtakeoneargument(anumberfrom0to9)andgenerateavectoroftheappropriatelengthcontainingthewaveform.Assumethefollowingparameters:

Samplingrate:8000samples/sec Toneduration:0.25sec Maximumsignalamplitude:1

ABC DEF

JKLGHI MNO

TUVPRS WXY

697 Hz

770 Hz

852 Hz

941 Hz

1209 Hz 1336 Hz 1477 Hz

VDTMF

Figureā€‚P8.1ā€‚ Aā€‚telephoneā€‚keypadā€‚consistsā€‚ofā€‚12ā€‚buttons,ā€‚7ā€‚switches,ā€‚7ā€‚sineā€‚waveā€‚generators,ā€‚andā€‚anā€‚adder.

Page 287: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 271

2. Use your DTMF function to create a single waveform that dials your owntelephonenumber.Youwillneedtorunyourfunctionmultipletimes(foreachdigitinyourphonenumber)andconcatenatetheresultsintoasinglevector.

3. Save thewaveform toafilewithMATLABā€™swavwrite() command.Thewavwrite()commandcanberunseveralways(runhelp wavwriteformoreinformation),butinthesimplestcasetakestwoarguments:avector(presumedtobe8000samples/sec)andafilename.ConfirmthatyoucanplaytheresultingWAVfilethroughyourcomputerspeakers.

4. ThewaveformyougenerateddoesnotgenerateaconformingDTMFsequence[4] because it does not contain the appropriate amount of silence betweentheindividualtones.Modifyyourdtmf.mfunctiontoadd0.25secofsilenceat theendofeachgenerated tone.Re-createyourWAVfilewith theaddedsilencebetweenthetones.Tryplayingtheresultingaudiointoyourowntele-phone(byholdingthehandsetuptoyourcomputerspeaker)andseeifyoucangetthegeneratedtonestodialyourphone.(Notethatthiswillonlyworkonlandlineswithadialtone,notonamobilephone.)

Project.8.2

DesignasystemtodetecttransmittedDTMFkeypresses.AssumethatfS=8000samples/sec.Proceedasfollows:

1. Create10testsignalsx0(t)throughx9(t)correspondingtothe10numericbut-tonsontheDTMFkeypadofFigureP8.1.Eachsignalshouldbe0.25seclongandshouldcontainthesumoftwosinewaves(eachwithanamplitudeofone)correspondingtotherowandcolumnfrequenciesforeachindividualbutton.Concatenateallofyourtestsignalstogethertoobtainonelongsignalof2.5secthatcontainsall10simulatedkeypressesinsuccession.(Alternatively,ifyoudidProject8.1,usethesignalthatyougeneratedinthatproblem.)

2. WriteaMATLABprogramthatdoesa1024-pointFFToneachsuccessivesetof1024elementsinyourinputsignalanddetectsthepresenceofanyofthesevenDTMFfrequencies.PrintyourdetectionresultstothescreenforeveryFFToperation.

3. WhathappenswhentheFFToverlapstwokeypresses?Add0.25secofsilenceinbetweeneachkeypresstoavoidthisproblemandrerunyourdetectionpro-gramtoseeifanyerroneousentriesareremoved.

4. ReducethesizeofyourFFTwindowto512,256,128,64,and32.WhatisthesmallestwindowthatyoucanuseandstillreliablydetectallsevenDTMFfrequencies?

Project.8.3

Designahigh-passFIRfilterwiththefollowingspecifications:

fS=8000samples/secfo=200HzTaps=201

Window:Bartlett(triangle)

Page 288: Numerical and Analytical Methods with MATLAB for

272ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Notethatahigh-passfiltercanbedecomposedintothedifferenceofanall-passfilterandalow-passfilter(seeFigureP8.3).Anall-passfilterhasavalueofoneforallfrequencies.

1. Find the impulse response of an all-pass filter by explicitly calculating theinverseDTFTaccordingtoEquation(8.15) forvaluesofn =āˆ’2,āˆ’1,0,1,2.Doesyoursolutionmakesense?

2. CalculatetheidealimpulseresponsehI[n]forthehigh-passfilterbysubtract-ing the corresponding low-pass impulse response from the all-pass impulseresponse.

3. Createarealizablehigh-passimpulseresponsehR[n]bymultiplyingtheidealresponsebyatriangularwindowwhosewidthisthenumberoftapsandwhoseheightisone.

4. Createatestinputsignalx(t)containingsinewavesat60,300,and1000Hz.Applyx(t) toyourhigh-pass impulseresponseandobtaintheoutputy(t)bysimulatingtheFIRfilterofFigure 8.12.

5. Performa1024-pointFFTonhR(t),x(t),andy(t)andplotthemagnitudesofthe transformson semilogaxes (usea linearhorizontal axis and logverticalaxis).Whatfrequencycomponentsmakeitthroughthehigh-passfilter?

Project.8.4

DesignabandpassFIRfilterthatdetectskeysfromthesecondrowoftheDTMFkeypadshowninFigureP8.1.AssumethatfS=8000samples/sec,andafilterwith401taps.Followthisprocedure:

1. First,createanidealbandpassresponseinthefrequencydomainsuchthatthepassband iscenteredon770Hzandhasa lowcutofffrequency fLandhighcutofffrequencyfH.ThefrequenciesfL andfH aredeterminedbythenecessitytorejecttheadjacentDTMFfrequenciesof697and852Hz.

2. BecauseFouriertransformsarelinear,abandpassresponsecanbecreatedbysubtractingtwolow-passresponses.Decomposeyourbandpassresponseintoalow-passresponsewithcutofffrequencyfHandasecondlow-passresponsewithcutofffrequencyfL.Createanidealimpulseresponsebysubtractingtheidealimpulseresponsesofthetwolow-passfilters.

3. CreatearealizableimpulseresponsebymultiplyingyouridealresponsebyoneofthewindowsinFigure 8.16.Explainwhichwindowyouchoseandwhyitisoptimalforthisapplication.

foāˆ’fo foāˆ’fo

1 1 1

HAP( f ) HLP( f ) HHP( f )

Figureā€‚P8.3ā€‚ Aā€‚high-passā€‚frequencyā€‚responseā€‚HHP(f)ā€‚canā€‚beā€‚constructedā€‚byā€‚sub-tractingā€‚aā€‚low-passā€‚responseā€‚HLP(f)ā€‚fromā€‚anā€‚all-passā€‚responseā€‚HAP(f)ā€‚.

Page 289: Numerical and Analytical Methods with MATLAB for

Fourier Transforms and Signal Processingā€ƒ ā—¾ā€ƒ 273

4. Create two test signals for yourfilter corresponding to the2 and5buttonsonthekeypadandrunthemthroughyourfilterbysimulatingtheFIRfiltercircuitofFigure 8.12.Plotthetime-domainresultsandconfirminyourfilteroutputthatyourfilterdetectsthe5andnotthe2.

Project.8.5

Use the technique employed inExample8.2andfind the complex exponentialFouriercoefficientsforthetriangularpulseofFigureP8.8.

Project.8.6

RerunExample8.4forthelow-passFIRfilter.Makethefollowingchangestothefilterparameters(oneatatime)andcommentqualitativelyontheeffectontheoutputplots.

1. ChangethesamplingratefSfrom40,000to44,100samples/sec. 2. Changethenumberoffiltertapsto101. 3. Changethenumberoffiltertapsto1601.

4. Changethethreeinputfrequenciesto200,500,and39,200Hz.

References 1. Siebert,W.M.,Circuits, Signals, and Systems,MITPress,Cambridge,MA,1986. 2. Cooley,J.W.,andTukey,J.W.,Analgorithmforthemachinecalculationofcomplex

Fourierseries,Mathematics of Computation,19:297ā€“301,1965. 3. Oppenheim, A.V., and Schafer, R.W., Digital Signal Processing, Prentice-Hall,

EnglewoodCliffs,NJ,1975. 4. Multifrequencypush-buttonsignalreception,ITU-TRecommendationQ.24,http://

www.itu.int.

Page 290: Numerical and Analytical Methods with MATLAB for
Page 291: Numerical and Analytical Methods with MATLAB for

275

Chapter 9

Curveā€‚Fitting

9.1ā€‚ ā€‚IntroductionTherearemanyoccasionsinengineeringthatrequireanexperimenttodeterminethebehaviorofaparticularphenomenon.Theexperimentmayproduceasetofdatapointsthatrepresentsarelationshipbetweenthevariablesinvolvedinthephenom-enon.Wemaythenwishtoexpressthisrelationshipanalytically.Amathematicalexpressionthatdescribesthedataiscalledanapproximating function.Therearetwoapproachestodetermininganapproximatingfunction:

1.Theapproximatingfunctiongraphsasasmoothcurve.Inthiscase,theplottedcurvewillgenerallynotpassthroughallthedatapoints,butweseektominimizetheresultingerrortogetthebestfit.Aplotofthedataonlinear,semilog,orlog-logcoordinatescanoftensuggestanappropriateformfortheapproximatingfunction.

2.Theapproximatingfunctionpassesthroughalldatapoints(asdescribedinSection9.3).However,ifthereissomescatterinthedatapoints,thisapproxi-matingfunctionmaynotbesatisfactory.

9.2ā€‚ ā€‚Methodā€‚ofā€‚Leastā€‚Squares9.2.1 Best-Fit Straight LineInthemethodofleastsquares,weseektofindthebest-fitstraightlinegivenasetofndatapoints( , ), ( , ), ,( , )1 1 2 2x y x y x yn nā€¦ .

Page 292: Numerical and Analytical Methods with MATLAB for

276ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Wewishtorepresenttheapproximatingcurveycasastraightlineoftheform

1 2y c c xc = + (9.1)

wherec1andc2areunknownconstantstobedetermined.LetDbethesumofthesquareoftheerrorsbetweentheapproximatinglineandtheactualpoints.Then,

( ) 2

1

D y y xi c i

i

n

āˆ‘[ ]= āˆ’=

(9.2)

( )1 22

1

y c c xi i

i

n

āˆ‘[ ]= āˆ’ +=

(9.3)

[ ( )] [ ( )] [ ( )]1 1 2 12

2 1 2 22

1 22y c c x y c c x y c c xn n= āˆ’ + + āˆ’ + + + āˆ’ + (9.4)

To obtain the best-fit straight-line approximating function, minimize D by

taking āˆ‚āˆ‚

= 01

Dc

and āˆ‚āˆ‚

= 02

Dc

.TakingthepartialderivativeofEquation(9.3)with

respecttoc1gives

0 2[ ( )][ 1]1

1

1 2Dc

y c c xi

n

i iāˆ‘āˆ‚āˆ‚

= = āˆ’ + āˆ’=

01

2

1

1y c x nci

i

n

i

i

n

āˆ‘ āˆ‘= āˆ’ āˆ’= =

or

āˆ‘ āˆ‘+ == =

1

1

2

1

nc x c yi

i

n

i

i

n

(9.5)

TakingthepartialderivativeofEquation(9.3)withrespecttoc2gives

0 2[ ( )][ ]2

1 2

1

Dc

y c c x xi i i

i

n

āˆ‘āˆ‚āˆ‚

= = āˆ’ + āˆ’=

0 1 1

1

22

11

x y c x c xi i

i

n

i

i

n

i

n

āˆ‘ āˆ‘āˆ‘= āˆ’ āˆ’= ==

Page 293: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 277

or

āˆ‘ āˆ‘ āˆ‘+ == = =1

12

1

2

1

x c x c x yi

i

n

i

i

n

i i

i

n

(9.6)

Equations(9.5)and(9.6)describeasystemoftwoalgebraicequationsintwounknownsthatcanbesolvedbythemethodofdeterminants(Cramerā€™srule):

1

2

2

2

2c

y x

x y x

n x

x x

y x x x y

n x x x

i i

i i i

i

i i

i i i i i

i i i

āˆ‘ āˆ‘āˆ‘ āˆ‘

āˆ‘āˆ‘ āˆ‘

āˆ‘ āˆ‘ āˆ‘ āˆ‘āˆ‘ āˆ‘ āˆ‘

( )( ) ( )( )( )( )

= =āˆ’

āˆ’ (9.7)

2

2

2c

n y

x x y

n x

x x

n x y x y

n x x x

i

i i i

i

i i

i i i i

i i i

āˆ‘āˆ‘ āˆ‘

āˆ‘āˆ‘ āˆ‘

āˆ‘ āˆ‘āˆ‘āˆ‘ āˆ‘āˆ‘( )( )( )( )

= =āˆ’

āˆ’ (9.8)

9.2.2 Best-Fit mth-Degree PolynomialWecangeneralizethisapproachforanmth-degreepolynomialfit.Inthiscase,taketheapproximatingcurveyctobe

y c c x c x c x c xc 1 2 32

43

m 1m= + + + + + + (9.9)

wherem ā‰¤n āˆ’1,andnisthenumberofdatapoints.Themeasuredvaluesare( , )x yi i fori =1,2,ā€¦,n.

Page 294: Numerical and Analytical Methods with MATLAB for

278ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Let ( ),y y xc i c i= betheapproximatedvalueofyiatthepoint ( , )x yi i .Then,

āˆ‘ āˆ‘ ( )[ ]= āˆ’ = āˆ’ + + + +

=

+

=

,2

1

1 2 32

12

1

D y y y c c x c x c xi c i

i

n

i i i m im

i

n

TominimizeD,take

ā€¦

āˆ‚āˆ‚

=āˆ‚āˆ‚

=āˆ‚āˆ‚

=+

0, 0, , 01 2 1

Dc

Dc

Dcm

Then,

āˆ‘

āˆ‘

āˆ‘

āˆ‘

( )

( )

( )

( )

[ ]

[ ]

āˆ‚āˆ‚

= = āˆ’ + + + āˆ’

āˆ‚āˆ‚

= = āˆ’ + + + āˆ’

āˆ‚āˆ‚

= = āˆ’ + + + āˆ’

āˆ‚āˆ‚

= = āˆ’ + + + āˆ’

=

+

=

+

=

+

+ =

+

0 2 1

0 2

0 2

0 2

1 1

1 2 1

2 1

1 2 1

3 1

1 2 12

1 1

1 2 1

Dc

y c c x c x

Dc

y c c x c x x

Dc

y c c x c x x

Dc

y c c x c x x

i

n

i i m im

i

n

i i m im

i

i

n

i i m im

i

m i

n

i i m im

im

Thissetofequationsreducesto

āˆ‘ āˆ‘ āˆ‘ āˆ‘

āˆ‘ āˆ‘ āˆ‘ āˆ‘ āˆ‘

āˆ‘ āˆ‘ āˆ‘ āˆ‘ āˆ‘

( ) ( ) ( )( ) ( ) ( ) ( )

( ) ( ) ( ) ( )

+ + + + =

+ + + + =

+ + + + =

+

++

+ ++

1 22

3 1

12

23

31

1

11

22

32

1

nc x c x c x c y

x c x c x c x c x y

x c x c x c x c x y

i i im

m i

i i i im

m i i

im

im

im

im

m im

i

(9.10)

Equation(9.10)canbesolvedbyGausselimination(asdescribedinChapter3).

Page 295: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 279

MATLABusesmeansquareerror (MSE)asameasureof theprecisionwithwhichthefittedpolynomialdescribesthedata.MSEisdefinedby

MSE= 1 ( ), 2

1n

y yi c i

i

n

āˆ‘ āˆ’=

(9.11)

whereyc,i=yc(yi).Toobtainthebestpolynomialdegree,runyourprogramforseveraldifferentm

valuesandusetheonewiththelowestMSE.

9.3ā€‚ ā€‚Curveā€‚Fittingā€‚withā€‚theā€‚Exponentialā€‚FunctionManysystems(e.g.,semiconductordevices)canbemodeledwithexponentialfunc-tions.Ifyourexperimentaldataappearstofallintothiscategory,itcanbefittedwithafunctionoftheform

12y ecx=Ī± āˆ’Ī± (9.12)

where 1Ī± and 2Ī± arerealconstants.Letusassumethatasetofnmeasureddatapoints( , ), ( , ), ,( , )1 1 2 2x y x y x yn nā€¦

exists.Then,let lnz yi i= and ln ln 1 2z y xc c= = Ī± āˆ’Ī± andlet ln1 1c = Ī± and .2 2c = āˆ’Ī± Then,Equation(9.12)becomeslinearinzc ,thatis,

1 2z c c xc = + (9.13)

Forthedatapoints( , ), ( , ), ,( , )1 1 2 2x y x y x yn nā€¦ , thenewsetofdatapointsbecomes( , ), ( , ), ,( , )1 1 2 2x z x z x zn nā€¦ .

Aswederivedintheprevioussection,thebest-fitapproximatingstraight-linecurvebythemethodofleastsquaresgives

1

2

22c

z x x x z

n x x

i i i i i

i i

āˆ‘ āˆ‘ āˆ‘ āˆ‘āˆ‘āˆ‘

( )( ) ( )( )( )

=āˆ’

āˆ’ (9.14)

and

22

2cn x z x z

n x x

i i i i

i i

āˆ‘ āˆ‘āˆ‘āˆ‘āˆ‘

( )( )( )

=āˆ’

āˆ’ (9.15)

Page 296: Numerical and Analytical Methods with MATLAB for

280ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Then,Ī± = exp( )1 1c and 2 2cĪ± = āˆ’ .TheMSEcanbedeterminedbyEquation9.11.ThisanalysiscanbeusedtodeterminethedampingconstantĪ¶ inaparallel

RLCcircuit(asanalyzedinAppendixA).Thiscanbeaccomplishedbyexaminingtheoscilloscopeoutputofthestepresponse(seeFigure 9.1).Thegoverningequationoftheenvelopeoftheresponseisoftheform

0y y e tn= āˆ’Ī¶Ļ‰ (9.16)

where

capacitor voltage

initial capacitor voltage (dependent on initial conditions)

damping factor

natural frequency = 1

y

y

LC

o

n

=

=

Ī¶ =

Ļ‰ =

ComparingEquation(9.15)withEquation(9.10),weseethat

1 0

2

y

n

Ī± =

Ī± = Ī¶Ļ‰

(t1, y1)(t2, y2)

(t3, y3)

Figureā€‚9.1ā€‚ Oscilloscopeā€‚screenā€‚shotā€‚ofā€‚theā€‚stepā€‚responseā€‚ofā€‚theā€‚capacitorā€‚voltageā€‚ofā€‚aā€‚parallelā€‚RLCā€‚circuit.ā€‚(Withā€‚permissionā€‚fromā€‚Tektronix,ā€‚Inc.)

Page 297: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 281

withtreplacingx.Therefore

22 LC

nĪ¶=

Ī±Ļ‰

= Ī± (9.17)

Bymeasuringndatapointsontheenvelope,i.e.,(t1,y1),(t2,y2)ā€¦ (tn,yn)wecandeterminethebestfitvalueforĪ±2,givingourbestestimateforthedampingfactor,Ī¶.

9.4ā€‚ ā€‚MATLABā€™sā€‚polyfitā€‚FunctionMATLABreferstocurvefittingwithapolynomialasā€œpolynomialregression.ā€Thepolyfitfunctionreturnsavectorofm + 1coefficientsthatrepresentthebest-fitpolynomialofdegreemforthe( , )x yi i setofdatapoints.Thecoefficientordercor-respondstodecreasingpowersofx,thatis,

1 21

32

1y a x a x a x a x acm m m

m mā€¦= + + + +āˆ’ āˆ’+ (9.18)

The vector ( , , , , )1 2 1A a a a am mā€¦= + containing the coefficients is obtained byrunningA=polyfit(X,Y,m),where ( , , , )1 2X x x xnā€¦= and ( , , , )1 2Y y y ynā€¦= .

MATLAB provides thepolyval(a,x) function to calculate the approxi-matedvalues ,yc i at( , , , )1 2x x xnā€¦ forthefittedcoefficients ā€¦ +( , , , )1 2 1a a am :

, 1 21

31

1y a x a x a x a x ac i im

im

im

m i mā€¦= + + + +āˆ’ āˆ’+

ForcalculatingtheMSE,polyvalisusefulasseeninExample9.1.

Exampleā€‚9.1

Given the following set of data points, find the best fit to polynomials of sec-ond, third, fourth, and fifth degree. Also, calculate the mean square error.

x y( , ) ( 10, 980), ( 8, 620), ( 6, 70), ( 4,80),

( 2,100), (0,90), (2,0), (4, 80), (6, 90), (8,10), (10,220)

= āˆ’ āˆ’ āˆ’ āˆ’ āˆ’ āˆ’ āˆ’

āˆ’ āˆ’ āˆ’

%Example_9_1.m%Thisprogramdeterminesthebestfitpolynomialcurve%passingthroughagivensetofdatapointsfor%polynomialdegrees2thru5.clear;clc;

Page 298: Numerical and Analytical Methods with MATLAB for

282ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%ProvideddatasetX=[-10-8-6-4-20246810];Y=[-980-620-7080100900-80-9010220];%Fittopolynomialsofdegreem:m=2:5;%Createasecondsetofxpointsoverthesameinterval%inordertoplotourfittedcurveX2=-10:0.5:10;%VectortokeeptrackofMSE(toprintatend)MSE=zeros(length(m));fori=1:length(m)fprintf('m=%i\n',m(i));%anmth-degreepolynomialhasm+1coefficients:A=zeros(m(i)+1);%dothefitA=polyfit(X,Y,m(i));%computetheMSEYc=polyval(A,X);MSE(i)=(1/length(X))*sum((Y-Yc).^2);%printtablefprintf('xyyc\n');fprintf('-----------------------------\n');forj=1:length(X)fprintf('%5.0f%5.0f%8.2f\n',...X(j),Y(j),Yc(j));endfprintf('\n\n');%plotsubplot(2,2,i);plot(X2,polyval(A,X2),X,Y,'o');xlabel('x');ylabel('y');grid;axis([-1010-1500500]);title(sprintf('Degree%dpolynomialfit',m(i)));end%printcomputedMSEfprintf('mMSE\n')fprintf('----------------------\n');fori=1:length(m)fprintf('%g%10.2f\n',m(i),MSE(i))end

-------------------------------------------------------------------

PROGRAM.OUTPUT

m MSE------------------- 2 32842.37 3 2659.97 4 2342.11 5 1502.95

As would be expected, the MSE decreases as the order of the fitted polyno-mial increases. The polynomial fits are plotted in Figure 9.2.

Page 299: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 283

Exampleā€‚9.2

Figure 9.3 shows an RC circuit, and Table 9.1 shows a set of steady-state voltage amplitudes and phases that were measured in the lab for VIN and VOUT at the given frequencies.

We wish to fit the data to the best-possible first-order frequency response.The RC circuit can be considered a first-order low-pass filter with a fre-

quency response of the form

H f

nj f d

( )2

0

0

=Ļ€ + (9.19)

ā€“10 0 10ā€“1500

ā€“1000

ā€“500

0

500

x

yDegree 2 Polynomial Fit

ā€“10 0 10ā€“1500

ā€“1000

ā€“500

0

500

x

y

Degree 3 Polynomial Fit

ā€“10 0 10ā€“1500

ā€“1000

ā€“500

0

500

x

y

Degree 4 Polynomial Fit

ā€“10 0 10ā€“1500

ā€“1000

ā€“500

0

500

x

y

Degree 5 Polynomial Fit

Figureā€‚ 9.2ā€‚ Polynomialā€‚ fitsā€‚ usingā€‚ MATLABā€™sā€‚ polyfitā€‚ functionā€‚ forā€‚ second-,ā€‚third-,ā€‚fourth-,ā€‚andā€‚fifth-orderā€‚polynomials.

+

āˆ’

C

R

VIN VOUT

Figureā€‚9.3ā€‚ RCā€‚circuitā€‚withā€‚inputā€‚sinusoidalā€‚voltageā€‚VINā€‚andā€‚outputā€‚VOUT.

Page 300: Numerical and Analytical Methods with MATLAB for

284ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

where H = VOUT / VIN is the frequency-dependent output-to-input ratio, and n0 and d0 are the numerator and denominator coefficients, respectively, to be determined. Because Equation (9.19) has the polynomial in the denomi-nator, we start by rearranging it into a polynomial of the form of Equation (9.18) so that we can apply polyfit. This gives

= Ļ€ +

H nj f

dn

1 12

0

0

0

(9.20)

Matching terms between Equations (9.20) and (9.18) shows that a j n21 0= Ļ€ and a d n2 0 0= ; thus, the inverse of the frequency response H1 can be fitted by using A=polyfit(f,1./H,1), where f is the vector of measured frequencies, and H is the vector containing measured values of V VOUT IN . The MATLAB program follows:

%Example_9_2.m%Fitlab-measuredfreqresponseto1storderresponseclear;clc;%Lab-measureddatafromTable9.1:f=[02e34e36e38e310e3];V_in=[555555];V_out=[52.11.3.8.6.5];Phi_degrees=[0-60-75-80-83-85];%RatioofV_outtoV_inisthemagnitudeofthe%frequencyresponse:H_mag=V_out./V_in;%Thephaseisthemeasuredphasedifference(converted%toradians)H_phase=Phi_degrees*pi/180;%ExpressthecomplexfreqresponseHas:%mag*exp(j*phase)H=H_mag.*exp(j*H_phase);%Dopolynomialfitto1/HA=polyfit(f,1./H,1);%Computecoefficientsoffittedfreqresponsebased%polyfitresults

Table 9.1ā€‚ Laboratory-Measuredā€‚Frequencyā€‚Responseā€‚ofā€‚RCā€‚Circuit

Frequency (Hz)

VIN (volts peak-to-peak)

VOUT (volts peak-to-peak)

Phase Difference between VOUT and VIN

0 5 5 0

2,000 5 2.2 ā€“60

4,000 5 1.2 ā€“75

6,000 5 0.8 ā€“80

8,000 5 0.6 ā€“83

10,000 5 0.5 ā€“85

Page 301: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 285

n0=2*pi*j/A(1);d0=2*pi*j*A(2)/A(1);%Printfittedfrequencyresponse:fprintf('Fittedfrequencyresponse:\n');fprintf('H(f)=%.0f/(j*2*pi*f+%.0f)\n',n0,d0);fprintf('Polelocation:%.0frad/sec(%.0fHz)\n',...d0,d0/(2*pi));%Forcomparisonpurposes,calculatethefittedcurve%withfineprecision.Use100log-spacedpointsfrom1Hz%to1MHzf_fine=logspace(0,6,100);H_fit=n0./(j*2*pi*f_fine+d0);H_fit_mag=abs(H_fit);H_fit_phase=angle(H_fit);%CreateBodeplot:subplot(2,1,1);loglog(f,H_mag,'o',f_fine,H_fit_mag);axis([1e01e61e-32]);legend('measured','fittedfunction');ylabel('|H(f)|');title('Fitofmeasureddatato1st-orderfreqresponse');subplot(2,1,2);semilogx(f,(180/pi)*H_phase,'o',...f_fine,(180/pi)*H_fit_phase);axis([1e01e6-10010]);legend('measured','fittedfunction');ylabel('\angleH(f)(degrees)');xlabel('frequency(Hz)');

-------------------------------------------------------------------

PROGRAM.RESULTS

Fittedfrequencyresponse: H(f)=6204/(j*2*pi*f+6842)Polelocation:6842rad/sec(1089Hz)

The resulting plot is shown in Figure 9.4.

9.5ā€‚ ā€‚Cubicā€‚SplinesSupposeforagivensetofdatapoints,allattempteddegreepolynomialapproxi-mating curves produced points that were not allowed. For example, suppose itis known that a particular property representedby thedata (such as voltage orabsolutetemperature)mustbepositive,andalltheattemptedpolynomialapproxi-mating curves produced some negative values. For this case, the polynomialapproximating functionwouldnot be satisfactory.Themethodof cubic splineseliminatesthisproblem.

Givenasetofn +1datapoints( , )x yi i fori =1,2,ā€¦,n +1,themethodofcubicsplinesdevelopsasetofncubicfunctionssuchthaty(x)isrepresentedbyadifferentcubicfunctionineachofthenintervals,andthesetofcubicspassesthroughthen + 1datapoints.

Page 302: Numerical and Analytical Methods with MATLAB for

286ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

This isaccomplishedby forcing the slopesandcurvatures tobe identical foreachpairofcubicfunctionsthatjoinatagivendatapoint.

Note: Curvature

1

2

2

232

K

d ydx

dydx

=Ā±

+

(9.21)

Weseethatifwesatisfythefollowingsetofequations,Equations(9.22),wewillautomaticallysatisfyboththeslopesandthecurvatureattheconnectingpoints.Thus,set

( ) ( )

( ) ( )

( ) ( )

int 1 int

int 1 int

int 1 int

y x y x

y x y x

y x y x

i i i i

i i i i

i i i i

[ ] [ ]

[ ] [ ]

[ ] [ ]

=

=

=

āˆ’

āˆ’

āˆ’

(9.22)

Atthepoint xi ,thevalues yi , yi ,and yi mustbethesameforboththeleftinterval(inti āˆ’1),andtherightinterval(inti).

100

10ā€“2

|H(f

)|Fit of Measured Data to 1st-Order Frequency Response

MeasuredFitted function

ā€“100

ā€“80

ā€“60

ā€“40

ā€“20

0

Frequency (Hz)

H(f

) (d

egre

es) Measured

Fitted function

100 101 102 103 104 105 106

100 101 102 103 104 105 106

Figureā€‚9.4ā€‚ Fittedā€‚frequencyā€‚responseā€‚forā€‚aā€‚first-orderā€‚RCā€‚circuit.

Page 303: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 287

Inthe(iāˆ’1)interval, 1x x xi iā‰¤ ā‰¤āˆ’ (seeFigure 9.5),and

( ) ( ) ( ) ( )1 1 1 1 12

1 13y x A B x x C x x D x xi i i i i i i= + āˆ’ + āˆ’ + āˆ’āˆ’ āˆ’ āˆ’ āˆ’ āˆ’ āˆ’ āˆ’ (9.23)

where 1Aiāˆ’ , 1Biāˆ’ , 1Ciāˆ’ ,and 1Diāˆ’ arethecoefficientsofthefittedcubicpolynomialbetween 1xiāˆ’ andxi .

Inthe(i)interval, 1x x xi iā‰¤ ā‰¤ + ,and

( ) ( ) ( ) ( )2 3y x A B x x C x x D x xi i i i i i i= + āˆ’ + āˆ’ + āˆ’ (9.24)

whereAi,Bi,Ci,andDiarethecoefficientsofthefittedcubicpolynomialbetweenxiand 1xi+ .

Thisgivesn āˆ’1equationsandn +1unknowns.

Thus,valuesfor2

2d ydx

at 1x and 1xn+ mustbeassumedtoobtainthefinaltwoequations.Severalalternativesexistforchoosingtheselasttwoequations:

a.Assume ( ) ( ) 01 1y x y xn= =+ .This iswidelyused and forces the splines toapproachstraightlinesattheendpoints.

b.Assume ( ) ( )1 2y x y x= and ( ) ( )1y x y xn n=+ . This forces the splines toapproachparabolasattheendpoints.

9.6ā€‚ ā€‚Theā€‚Functionā€‚interp1ā€‚forā€‚Cubicā€‚Splineā€‚Curveā€‚FittingMATLABā€™sbuilt-in functioninterp1 interpolatesbetweendatapointsbythecubicsplinemethod.

Usage:Yi=interp1(X,Y,Xi,'spline')

whereX,Yarethesetofdatapoints,andXiisthesetofXvaluesatwhichthesetofvaluesYiistobereturned.

yiā€“1

xiā€“1 xi+1xi

yi+1yi

y

x

inti

inti ā€“ 1

Figureā€‚9.5ā€‚ Twoā€‚adjacentā€‚intervalsā€‚inā€‚aā€‚cubicā€‚splineā€‚interpolation.

Page 304: Numerical and Analytical Methods with MATLAB for

288ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚9.3

%Example_9_3.m%Thisprogramusesinterpolationbycubicsplinesto%upsampleanaudiosignal.clear;clc;%Defineoriginaldatapointsfory(t)(timeinmicrosec)orig_t=[048121620242832364044485256];orig_y=[.7.9.9.7.30-.3-.7-.7-.30.3.7.7.3];%Defineupsampledtimepointsupsampled_t=0:60;%Calculateinterpolateddatapointsusingcubicsplinesinterp_y=interp1(orig_t,orig_y,upsampled_t,'spline');%Printoutputtoscreenfprintf('UPSAMPLINGVIACUBICSPLINEFIT\n');fprintf('time(microsec)origsampleupsample\n');fprintf('--------------------------------------\n');fori=1:length(upsampled_t)%Trytofindthecorrespondingtimepointinthe%originaldatasetforthisupsampledtimepointwith%MATLAB's"find"function.j=find(orig_t==upsampled_t(i));ifj>0%ifwefoundoriginalvalue,printbothorigand%interpolated.fprintf('%8.2f%10.1f%10.3f\n',...upsampled_t(i),orig_y(j),interp_y(i));else%otherwise,justprintinterpolatedvaluefprintf('%8.2f%10.3f\n',...upsampled_t(i),interp_y(i));endendplot(orig_t,orig_y,'o',upsampled_t,interp_y);xlabel('t(microsec)');ylabel('y(t)');grid;title('UpsamplingwithCubicSplineInterpolation');legend('original','upsampled','Location','SouthWest');

-------------------------------------------------------------------

PROGRAM.OUTPUT.(EXCERPT)

UPSAMPLINGVIACUBICSPLINEFIT

time(microsec) originalsample upsample 0.00 0.7 0.700 1.00 0.770 2.00 0.827 3.00 0.870 4.00 0.9 0.900 5.00 0.918 6.00 0.923 7.00 0.917 8.00 0.9 0.900 9.00 0.872

Page 305: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 289

10.00 0.830 11.00 0.774 12.00 0.7 0.700 13.00 0.608 14.00 0.506 15.00 0.400 16.00 0.3 0.300 . . . .

9.7ā€‚ ā€‚Curveā€‚Fittingā€‚withā€‚Fourierā€‚SeriesSupposeanexperimentaldatasetu(t)producesaplotasshowninFigure 9.6,anditisdesiredtoobtainananalyticalexpressionthatcomesclosetofittingthedata.Letusassumethatthedatarangesoverthesymmetricinterval[āˆ’L,L].Ifnot,wecanmakeitsobyshiftingtheorigin.Inthiscase,theoriginalabscissadatawerefor0ā‰¤tā‰¤10.5sec,andthedatawereshiftedbylettingx =t āˆ’5.25.Then,thexdomainissubdividedinto70equalintervalswithĪ”x =10.5/70=0.15sec.

Thus, 1x xi iāˆ’+ isuniformovertheentiredomain.Anattempttofitapolyno-mial-approximatingcurvetothesedatadidnotproduceanapproximatingcurvethatresembledthedataandwasthusnotsuccessful.However,theuseofaFourierseriesgivesareasonableanalyticalexpressionapproximatingthedata.If uc istheapproximatingcurve,thenbyaFourierseries,

āˆ‘= +

Ļ€+

Ļ€

=

āˆž

( ) cos sin0

1

u x a am xL

bm xLc m m

m

(9.25)

where

āˆ«=āˆ’

12

( )0a Lu x dx

L

L

(9.26)

āˆ«=

Ļ€

āˆ’

1 ( )cosaL

u xm xL

dxmL

L

(9.27)

āˆ«=

Ļ€

āˆ’

1 ( )sinbL

u xm xL

dxmL

L

(9.28)

Using30termsintheseriesandSimpsonā€™sruleofintegration,anapproximatingcurveasshowninFigure 9.7isobtained.

Page 306: Numerical and Analytical Methods with MATLAB for

290ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

6

5

4

3

2

1

0

ā€“1ā€“6 ā€“4 ā€“2 0

x2 4 6

u c(x)

Ɨ104

Figureā€‚9.7ā€‚ Fourierā€‚seriesā€‚fitā€‚ucā€‚versusā€‚xā€‚forā€‚theā€‚dataā€‚inā€‚Figureā€‚9.6.

6

5

4

3

2

1

0

ā€“1ā€“6 ā€“4 ā€“2 0

x2 4 6

u(x)

Ɨ104

Figureā€‚9.6ā€‚ Experimentalā€‚dataā€‚ofā€‚uā€‚versusā€‚x.

Page 307: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 291

TheĻ€

+Ļ€

cos sinam xL

bm xLm m termscanbesimplifiedbyapplyingthe

trigonometricidentity cos sin sin( ),2 2a b a bĪ² + Ī² = + Ī²+ giving

2 2c a bm m m( )= +

Aplotofcmversusā‰ mL

(neglectingthephasefactorĻ†)isshowninFigure 9.8.

ProjectsProject.9.1

FigureP9.1showsaresistor-diodecircuitusingatype1N914silicondiode(D1)anda10kĪ©resistor(R1).TableP9.1showsalistoflaboratorymeasurementsofV2forvariousappliedvoltagelevelsofV1atroomtemperature(300K).

7000

6000

5000

4000

3000

Four

ier C

oeffi

cien

t Val

ue C

m

2000

1000

00 2 4 6 8 10

n*pi/L12 14 16 18

Figureā€‚9.8ā€‚ Fourierā€‚seriesā€‚coefficientā€‚amplitudesā€‚versusā€‚ ā‰ nL

.

+

āˆ’ D11N914

R110 K

+

āˆ’V2

V1

Figureā€‚P9.1ā€‚ Diode-resistorā€‚circuitā€‚forā€‚laboratoryā€‚measurementā€‚ofā€‚diodeā€‚I-Vā€‚curve.

Page 308: Numerical and Analytical Methods with MATLAB for

292ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

1. UseKirchhoffā€™svoltagelawtocalculatethediodecurrentiDintermsofV1andV2. 2. UsethetechniquedescribedinSection9.3tofindtheleast-squarefitofiDandvD(=V2)

totheformula

expi I v

VD S

D

T= (P9.1)

Tableā€‚P9.1ā€‚ Laboratoryā€‚Measurementsā€‚ofā€‚Resistor-Diodeā€‚Circuit

V1 (volts) V2 (volts)

0.189 0.189

0.333 0.317

0.393 0.356

0.819 0.464

1.067 0.487

1.289 0.501

1.656 0.518

1.808 0.522

2.442 0.541

3.949 0.566

4.971 0.579

6.005 0.588

6.933 0.595

7.934 0.602

9.014 0.607

10.040 0.613

11.009 0.619

15.045 0.634

19.865 0.647

24.64 0.657

29.79 0.666

Page 309: Numerical and Analytical Methods with MATLAB for

Curve Fittingā€ƒ ā—¾ā€ƒ 293

Inthiscase,youareusingtherawdatatofindbest-fitvaluesforISandVT.Plotboththelabdataandyourfittedcurveonthesameaxes.

3. V kT qT = isknownasthethermal voltage(wherekistheBoltzmannconstantandqistheunitelectriccharge).Foryourbest-fitvalueforVT,whatisthecorrespondingtemperaturevalueT(inkelvin)?Doesthisvalueseemreasonable?

4. Amoreaccurateequationtomodelthediodeis

= expi I

vnVD S

D

T

wherenistheideality factor.Findthebest-fitvaluefornwhenT =300K.

5. ThecompleteI-Vmodelforthediodeis

= āˆ’exp 1i I

vnVD S

D

T

Isitreasonablethatweneglectedtheāˆ’1terminourcurvefit?Why?

Project.9.2

Themeasuredopen-loopfrequencyresponseofthe741opampisshowninFigureP9.2.

1. Find themagnitude (indecibels) andphase (indegrees)of the frequency responsebymeasuringdirectlyfromtheplot.Notethatthephasereadings(ontherightsideoftheplot)aredenotedasā€œPhaseLag,ā€whichmeansthatthereadingsshouldbeinterpretedasnegativedegrees.EnterthereadingsastwovectorsinMATLAB.

2. AmplifiergainAisusuallyexpressedindecibels(dB),where

20 logdBA A=

Convertyourdecibelreadingstoabsolutegainsbydividingby20andthenraisingto the power of 10. Also, convert your degree readings to radians. Then, express thefrequencyresponseincomplexpolarform.Rememberthat = Ļ†| |z z e j ,where | |z isthemagnitudeandĻ•isthephaseangle.

3. UseMATLABā€™spolyfitfunctiontofindafittoafrequencyresponseoftheform

( )

( 2 ) 20

21 0

H f dj f n j f n

=Ļ€ + Ļ€ +

Hint:getyourfitworkingforfā‰¤1000handthenaddthepointsforthehigherfre-quenciesoneatatime.Becausethepolynomialisinthedenominator,trytofit1 ( )H f insteadofH( f ).

Page 310: Numerical and Analytical Methods with MATLAB for

294ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

4. Find the locations of the poles for your fitted H( f ) by solving for the roots of thedenominator.

5. Plotthemeasuredresultsandthefittedresultsonthesamesetofaxes.Doesthefitseemreasonable?Atwhatfrequenciesdoes,thefitfail,andwhy?

Project.9.3

Reusethedata fororig _ tandorig _ y fromExample9.3toperformacurvefitusingFourierseries.Beginbyshiftingtsothatthedataaresymmetricaroundtheoriginsuchthatāˆ’L ā‰¤t ā‰¤L(whereL =28Ī¼sec).Then,proceedasfollows:

1. WriteaMATLABprogramtocalculatethefirstmFouriercoefficients.UseSimpsonā€™srule(asdescribedChapter5)tocalculatethecoefficients 0a , , ,...,1 2a a am,and , ,...,1 2b b bm asinEquations(9.26)ā€“(9.28).

2. GeneratethreesetsofFouriercoefficientsform =2,m =4,andm =6. 3. Generatethreefittedcurves(form =2,4,6)bysubstitutingyourcoefficientsbackinto

Equation(9.25).Plotonthesamesetofaxes.Whenplottingthefittedcurves,use150points on the horizontal axis over the range āˆ’L ā‰¤ t ā‰¤ L (instead of the 15 points inorig _ t).Alsoplotorig _ yonthesameaxes,usingtheƗsymboltoindicatethepoints.

4. Explainqualitativelywhathappensforthecasewhenm =6.

120

100

80

60

40

20

0

Ope

n-lo

op G

ain

(dB)

0

45

90

135

180

Phas

e La

g (D

egre

es)

0.1 1 10 100 1k 10k 100k 1M 10MFrequency (Hz)

GAIN

PHASE

VS = Ā±15 VRL = 2 kĪ©TA = 25Ā°CCL = 100 pF

Figureā€‚ P9.2ā€‚ Frequencyā€‚ responseā€‚ ofā€‚ theā€‚ 741ā€‚ opā€‚ amp.ā€‚ (Withā€‚ permissionā€‚ fromā€‚Analogā€‚Devices,ā€‚Inc.)

Page 311: Numerical and Analytical Methods with MATLAB for

295

Chapter 10

Optimization

10.1ā€‚ ā€‚IntroductionTheobjectiveofoptimizationistomaximizeorminimizesomefunctionf(calledtheobject function).Youareprobablyfamiliarwithdeterminingthemaximaandmin-imaoffunctionsusingtechniquesfromdifferentialcalculus.However,theproblembecomesmorecomplicatedwhenweplaceconstraintsontheallowablesolutionstof.Asanexample,supposethereisanelectronicscompanythatmanufacturesseveraldifferenttypesofcircuitboards.Eachcircuitboardmustpassthroughseveraldif-ferentdepartments(suchasdrilling,pick-and-place,testing,etc.)beforeshipping.Thetimerequiredforeachcircuitboardtopassthroughthevariousdepartmentsisalsoknown.Thereisaminimumproductionquantitypermonththatthecompanymustproduce.However,thecompanyiscapableofproducingmorethanthemini-mumproductionrequirementforeachtypeofcircuitboardeachmonth.Theprofitthecompanywillmakeoneachcircuitboarditproducesisknown.Theproblemistodeterminetheproductionamountofeachtypeofcircuitboardpermonththatwillresultinthemaximumprofit.Asimilartypeofproblemmaybeoneinwhichtheobjectistominimizethecostofproducingaparticularproduct.Thesetypesofoptimizationproblemsarediscussedingreaterdetailinthischapter.

Inmostoptimizationproblems,theobjectfunction fwillusuallydependonseveralvariables, , , , ,1 2 3x x x xnā€¦ .Thesearecalledthecontrol variablesbecausetheirvaluescanbeselected.Optimizationtheorydevelopsmethodsforselectingoptimalvaluesforthecontrolvariables , , , ,1 2 3x x x xnā€¦ thateithermaximizeorminimizetheobjectivefunctionf.Inmanycases,thechoiceofvaluesfor , , , ,1 2 3x x x xnā€¦ isnotentirelyfreebutissubjecttosomeconstraints.

Page 312: Numerical and Analytical Methods with MATLAB for

296ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

10.2ā€‚ ā€‚Unconstrainedā€‚Optimizationā€‚ProblemsIncalculus,itisshownthatanecessary(butnotsufficient)conditionforftohaveamaximumorminimumatpointPisthateachofthefirstpartialderivativesatPbezero,thatis,

( ) ( ) ( ) 0

1

fx

P fx

P fx

P2 n

āˆ‚āˆ‚

=āˆ‚āˆ‚

= =āˆ‚āˆ‚

= (10.1)

where the notationāˆ‚āˆ‚

( )fx

Pi

indicates the partial derivative with respect to xi

evaluatedatpointP,thatis,āˆ‚āˆ‚ =

fxi x P

.Ifn =1andtheobjectfunctionisy =f(x),

thenanecessaryconditionforanextremum(maximumorminimum)at 0x isfor( ) 00y x = .

Fory tohavealocalminimumat 0x , ( ) 00y x = and ( ) 00y x > .Fory tohavealocalmaximumat 0x , ( ) 00y x = and ( ) 00y x < .Forfinvolvingseveralvariables,theconditionforftohavearelativeminimumis

morecomplicated.First,Equation(10.1)mustbesatisfied.Second,thequadraticform

āˆ‘āˆ‘= āˆ‚

āˆ‚ āˆ‚āˆ’ āˆ’

==

( ) ( ( ))(( ( ))2

11

Qf

x xP x x P x x P

i jj

n

i i j j

i

n

(10.2)

must be positive for all choices of xi and x j in the in the vicinity of point P,andQ=0onlywhen ( )x x Pi i= fori =1,2,ā€¦,n.ThisconditioncomesfromaTaylor series expansionof ( , , , )1 2f x x xnā€¦ aboutpointPusingonly termsup toāˆ‚

āˆ‚ āˆ‚( ).

2 fx x

Pi j

Thisgives

ā€¦ āˆ‘ āˆ‘āˆ‘ [ ]= +āˆ‚āˆ‚

āˆ’ +āˆ‚āˆ‚ āˆ‚

āˆ’ āˆ’= ==

( , , , ) ( ) ( )[ ( )] ( ) ( ( ))( ( ))1 2

1

2

11

f x x x f Pfx

P x x Pf

x xP x x P x x Pn

ii i

i

n

i ji i j j

j

n

i

n

(10.3)

If ( , , , )1 2f x x xnā€¦ hasarelativeminimumatpointP,thenāˆ‚āˆ‚

=( ) 0fx

Pi

for

i =1,2,ā€¦,nand ā€¦ āˆ’ >( , , , ) ( ) 01 2f x x x f Pn forall( , , , )1 2x x xnā€¦ inthevicinityofpointP.But, ā€¦ āˆ’ =( , , , ) ( )1 2f x x x f P Qn .Thus,for f x x xn( , , , )1 2 ā€¦ tohavearelativeminimumatpointP,Qmustbepositiveforallchoicesof xi and x j inthevicinityofpointP.

Sincethisanalysisisquitecomplicatedwhenf isafunctionofseveralvariables,aniterativeschemeisfrequentlyusedasamethodofsolution.Onesuchmethodisthemethodofsteepestdescent.Inthismethod,wefirstneedtoguessforapointwhereanextremumexists.Usingagridtoevaluatethefunctionatdifferentvaluesofthecontrolvariablescanbehelpfulinestablishingagoodstartingpointfortheiterationprocess.

Page 313: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 297

10.3ā€‚ ā€‚Methodā€‚ofā€‚Steepestā€‚DescentConsiderafunctionfofthreevariablesx, y,and z.Fromcalculus,weknowthatthegradientoff,writtenasāˆ‡f,isgivenby

=āˆ‚āˆ‚

+āˆ‚āˆ‚

+āˆ‚āˆ‚

Ė† Ė† Ė†e e effx

fy

fzx y z

where Ė† , Ė† , and Ė†e e ex y z areunitvectorsinthex,y,andzdirections,respectively.At ( , , )0 0 0x y z ,wealsoknowthat ( , , )0 0 0f x y z pointsinthedirectionofthe

maximumrateofchangeoffwithrespecttodistance.AunitvectorĆŖgthatpointsinthisdirectionis

ĆŖg

=| |

ff

where =āˆ‚āˆ‚

+āˆ‚āˆ‚

+āˆ‚āˆ‚

| |2 2 2

ffx

fy

fz

.

Tofindarelativeminimumviathemethodofsteepestdescent,westartatsomeinitialpointandmoveinsmallstepsinthedirectionofsteepestdescent,whichisā€“ĆŖg.Let x y zn n n( , , )1 1 1āˆ’ āˆ’ āˆ’ bethenewpositiononthenthiterationand x y zn n n( , , )theoldposition.Then,

( , , )

| ( , , ) |

( , , )

| ( , , ) |

( , , )

| ( , , ) |

1

1

1

x x

fx

x y z

f x y zs

y y

fy

x y z

f x y zs

z z

fz

x y z

f x y zs

n n

n n n

n n n

n n

n n n

n n n

n n

n n n

n n n

= āˆ’

āˆ‚āˆ‚

= āˆ’

āˆ‚āˆ‚

= āˆ’

āˆ‚āˆ‚

+

+

+

(10.4)

whereĪ”sissomesmalllength.

Page 314: Numerical and Analytical Methods with MATLAB for

298ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Exampleā€‚10.1

Given

f x x x x x x x x x x x( , ) 4 4.5 4 2 2 21 2 1 2 12

22

1 2 14

12

2= + āˆ’ + + āˆ’ + āˆ’

Determine the minimum of f by the method of steepest descent, starting at point x x( , ) (6,10)1 2 = . Use a Ī”s = 0.1 and a maximum of 100 iterations.

%Example_10_1.m:%Thisprogramdeterminesarelativeminimumbythe%methodofsteepestdecent.Thefunctionis:%f(x1,x2)=4+4.5*x1-4*x2+x1^2+2*x2^2%-2*x1*x2+x1^4-2*x1^2*x2%Note:thisfunctionhasknownminimaat%(x1,x2)=(1.941,3.854)and(-1.053,1.028).The%functionalvaluesattheminimapointsare0.9855and%-0.5134respectively.clear;clc;%Definefunctionanditspartialderivativesfx_func=@(x1,x2)4+4.5*x1-4*x2+x1^2+2*x2^2...-2*x1*x2+x1^4-2*x1^2*x2;dfx1_func=@(x1,x2)4.5+2*x1-2*x2+4*x1^3-4*x1*x2;dfx2_func=@(x1,x2)-4+4*x2-2*x1-2*x1^2;%Definesteppingparametersds=0.1;max_iterations=100;%Firstguessx1=6;x2=10;fx=fx_func(x1,x2);%Printheadingsandinitialguesstoscreenfprintf('x1x2fx\n');fprintf('0:%7.4f%7.4f%10.4f\n',x1,x2,fx);forn=1:max_iterations%computepartialderivativesdfx1=dfx1_func(x1,x2);dfx2=dfx2_func(x1,x2);%computemagnitudeofgradientgradf_mag=sqrt(dfx1^2+dfx2^2);%computenextvaluesofx1andx2asperEqn10.4x1n=x1-dfx1/gradf_mag*ds;x2n=x2-dfx2/gradf_mag*ds;fxn=fx_func(x1n,x2n);fprintf('%2d:%7.4f%7.4f%10.4f\n',...n,x1n,x2n,fxn);%ifnewvalueislargerthanprevious,thenminimum%hasbeenfoundif(fxn>fx)fprintf('Aminimumhasbeenfoundafter');fprintf('%diterations\n\n',n);break;%otherwise,storenewvaluesovercurrentones%andcontinueelse

Page 315: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 299

x1=x1n;x2=x2n;fx=fxn;endendifi>=max_iterationsfprintf('Error:nosolutionfoundafter');fprintf('%diterations\n',i);elsefmin=fx_func(x1,x2);fprintf('Therelativeminimumoccursat');fprintf('x1=%.4fx2=%.4f\n',x1,x2);fprintf('Theminimumvalueforf=%.4f\n',fmin);end

-------------------------------------------------------------------

PROGRAMā€‚OUTPUTā€‚(EXCERPT)

x1 x2 fx0: 6.0000 10.0000 683.00001: 5.9003 10.0077 622.71922: 5.8006 10.0155 566.25283: 5.7009 10.0233 513.4609 . . .89: 1.9936 4.0234 1.000190: 1.9638 3.9279 0.988391: 1.9495 3.8289 0.9901

Aminimumhasbeenfoundafter91iterationsTherelativeminimumoccursatx1=1.9638x2=3.9279Theminimumvalueforf=0.9883.

To obtain a more accurate result, we could rerun the program with revised starting values (from iteration 91) and use a smaller Ī”s. Alternatively, instead of starting at some arbitrary point as specified in the example, we can first use a grid program to establish a good starting point. In addition, a grid program may indicate that there is more than one relative minimum point.

Exampleā€‚10.2

%Example_10_2.m:Thisprogramcalculatesthevaluesof%aspecifiedfunctionf(x1,x2)of2variablesfor%determiningagoodstartingpointforthemethodof%steepestdecent.Therangeofinterestisfrom%-10.0<=x1<=10.0and-10.0<=x2<=10.0.clear;clc;%Definefunctionofinterest:fx_func=@(x1,x2)4+4.5*x1-4*x2+x1^2+2*x2^2...-2*x1*x2+x1^4-2*x1^2*x2;%Definegridendpointsandstepsizex1min=-10.0;x1max=10.0;dx1=2.0;

Page 316: Numerical and Analytical Methods with MATLAB for

300ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

x2min=-10.0;x2max=10.0;dx2=2.0;%Definegridandcalculatef(x1,x2)ateachpointx1=x1min:dx1:x1max;x2=x2min:dx2:x2max;fori=1:length(x1)forj=1:length(x2)f(i,j)=fx_func(x1(i),x2(j));endend%Printheadingfprintf('-----------------------------------');fprintf('-----------------------------------');fprintf('------------------------------------\n');fprintf('x2|');fprintf('x1\n');fprintf('-----------------------------------');fprintf('-----------------------------------');fprintf('------------------------------------\n');fprintf('|');fori=1:length(x1)fprintf('%7.1f',x1(i));endfprintf('\n');fprintf('-----------------------------------');fprintf('-----------------------------------');fprintf('------------------------------------\n');%Printvaluesoff(x1,x2)forj=1:length(x2)fprintf('%6.1f|',x2(j));fori=1:length(x1)fprintf('%8.1f',f(i,j));endfprintf('\n');end

-------------------------------------------------------------------

PROGRAMā€‚RESULTS

ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€” x2| x1ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€” |-10.0-8.0-6.0-4.0-2.00.02.04.06.08.010.0ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”-10.0|12099.05488.02149.0738.0295.0244.0393.0934.02443.05880.012589.0-8.0|11659.05184.01949.0610.0207.0164.0289.0774.02195.05512.012069.0-6.0|11235.04896.01765.0498.0135.0100.0201.0630.01963.05160.011565.0-4.0|10827.04624.01597.0402.079.0 52.0129.0502.01747.04824.011077.0-2.0|10435.04368.01445.0322.039.0 20.073.0390.01547.04504.010605.00.0|10059.04128.01309.0258.015.0 4.033.0294.01363.04200.010149.02.0|9699.03904.01189.0210.07.0 4.09.0214.01195.03912.09709.04.0|9355.03696.01085.0178.015.0 20.01.0150.01043.03640.09285.06.0|9027.03504.0997.0162.039.0 52.09.0102.0907.03384.08877.08.0|8715.03328.0925.0162.079.0100.033.070.0787.03144.08485.010.0|8419.03168.0869.0178.0135.0164.073.054.0683.02920.08109.0

Since the functional value at (x1,x2)=(0,2) is lower than the functional values at surrounding points, we suspect that there is a relative minimum in the

Page 317: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 301

vicinity of (x1,x2)=(0,2). A second relative minimum appears to be in the vicinity of (x1,x2)=(2,4).

10.4ā€‚ ā€‚MATLABā€™sā€‚fminuncā€‚FunctionMATLABprovidesthefunctionfminunc(FUN,X0)tosolveunconstrainedopti-mizationproblems.Thetwoargumentstofminuncarethefunctiontooptimize(FUN)andaninitialguess(X0).FUNcanbeafunctiondefinedinaseparate .mfileormaybedefinedanonymouslywithinthescript.Theoutputoffminuncistheminimumthatisclosesttotheinitialguess.NotethatMATLABdoesnothaveaseparatefunctiontofindmaxima.Tofindamaximum,redefineyourfunctiontoreturnthenegativevalueandthenusefminunctofindtheminimum.

Exampleā€‚10.3

Given

y x x x x( ) 40 200 123 2= + āˆ’ +

Determine the minima and maxima.

%Example_10_3.m:Findtheminimaandmaximaof%y=x^3+40x^2-200x+12clc;clear;%First,plotthefunctionsothatwecanmakesome%usefulinitialguesses:x=-40:40;fori=1:length(x)y(i)=x(i)^3+40*x(i)^2-200*x(i)+12;endplot(x,y);xlabel('x'),ylabel('y'),grid,title('yvsx');%Next,findtheminimumandmaximumusingMATLAB's%anonymousfunctionmethod(findfirstguessesby%eyeballingplot).[xmin,minvalue]=fminunc(@(x)x^3+40*x^2-200*x+12,2);%Note:Tofindamaximum,insteadfindtheminimumof%thenegativeofthefunction.[xmax,maxvalue]=fminunc(@(x)-(x^3+40*x^2-200*x+12),...-30);%Printresultsfprintf('xmin=%.1fminvalue=%.1f,',xmin,minvalue);fprintf('xmax=%.1fmaxvalue=%.1f\n',xmax,-maxvalue);

-------------------------------------------------------------------

PROGRAMā€‚OUTPUT

xmin=2.3minvalue=-224.2,xmax=-29.0maxvalue=15063.0Determinemaximumandminimumvaluesofyandcomparewiththeresultsfromthefminuncfunction.

Page 318: Numerical and Analytical Methods with MATLAB for

302ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

10.5ā€‚ ā€‚Optimizationā€‚withā€‚ConstraintsInmanyoptimizationproblems,thevariablesinthefunctiontobemaximizedorminimizedarenotall independentbutarerelatedbyoneormoreconditionsorconstraints.Asimpleexamplethatillustratestheconstraintconceptfollows.

Exampleā€‚10.4

Suppose we wish to determine the maximum and minimum values of the objective function

f(x,y) = 2x + 3y (10.5)

with the following constraints:

Lower bounds (LB): x ā‰„ 0, y ā‰„ 0Upper bounds (UB): x ā‰¤ 3, y ā‰¤ 3Constraint 1 (L1): x + y ā‰¤ 4Constraint 2 (L2): 6x + 2y ā‰„ 8Constraint 3 (L3): x + 5y ā‰„ 8

The bounds are graphed in Figure 10.1. The MATLAB code that produces Figure 10.1 follows. Letters at the points of intersection were obtained by using the insert option on the MATLAB figure.

0 0.5 1 1.5 2 2.5 3ā€“5

ā€“4

ā€“3

ā€“2

ā€“1

0

1

2

3

4

L1

L2

L3

UB

LB

x

y

AB

CD

Figureā€‚10.1ā€‚ Allowableā€‚regionā€‚forā€‚controlā€‚variablesā€‚inā€‚determiningā€‚maximumā€‚andā€‚minimumā€‚pointsā€‚ofā€‚theā€‚objectā€‚function.

Page 319: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 303

%Example_10_4.m%Todrawlines,specifytwopointsontheline%upperboundonyx(1)=0;y(1)=3;x(2)=3;y(2)=3;%upperboundonxx1(1)=3;y1(1)=0;x1(2)=3;y1(2)=3;%lowerboundonyx2(1)=0;y2(1)=0;x2(2)=3;y2(2)=0;%lowerboundonxx3(1)=0;y3(1)=0;x3(2)=0;y3(2)=3;%lineL1x4(1)=0;y4(1)=4;x4(2)=3;y4(2)=1;%lineL2x5(1)=0;y5(1)=4;x5(2)=3;y5(2)=-5;%lineL3x6(1)=0;y6(1)=8/5;x6(2)=3;y6(2)=1;%plottheallowableregionplot(x,y,x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6)xlabel('x'),ylabel('y'),title('yvsx');

For each constraint, we replace the inequality with an equal sign to draw lines for LB, UB, L1, L2, and L3 and then add an arrow to indicate the region corresponding to the inequality. This specifies the allow-able region in which to consider the maximum and minimum values for function f.

We see in the graph that the allowable region for (x,y) in determining the maximum and minimum values for the object function f is the region enclosed by the polygon ABCD. For the specified object function, the minimum value of f is either on line L3 (between points D and C) or on line L2 (between points A and D). We can see this if we place a point P on line L3 and a point Q directly above it; then, the x values at points P and Q will be the same, but the y value at point Q will be larger than the y value of point P. Thus, f will be greater at point Q than f at point P. Thus, the minimum value of f is either on line L3 or on line L2.

The equation describing line L3 is

y

x85 5

= āˆ’ (line L3)

Substituting this expression for y into Equation (10.5) gives the value of f on line L3, which is

f

x245

75

= + (on L3)

The minimum value for f occurs at the lowest allowable x value on L3, which is at point D. Point D results from the intersection of line L3 and line L2. The equation describing line L2 is

y = 4 āˆ’ 3 x

(line L2)

Page 320: Numerical and Analytical Methods with MATLAB for

304ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

The x coordinate at point D can be obtained by equating the y expressions

for line L1 and line L2 giving the x value at point D, or = =xD1214

0.8571. At point D, the value of f is 6.00.

Substituting the expression for y on line L2 into Equation (10.5) gives the equation for f on line L2, which is

f = 12 āˆ’ 7x

(on line L2)

The minimum value for f on line AD occurs at the maximum allow-able value for x on AD, which is point D. Thus, in the allowable region, f 6.000.min =

From Figure 10.1, we see that the maximum value of f will be either at point B or somewhere else on line L1. The equation describing line L1 is

y = 4 āˆ’ x

(on line L1)

Substituting this expression for y into Equation (10.5) gives

f = 12 āˆ’ x

(on line L1)

The maximum f occurs where x is a minimum on line L1, which is at point B. At point B, x = 1. Thus, fmax = 11.0.

10.6ā€‚ ā€‚Lagrangeā€‚MultipliersA more general and mathematical discussion of the optimization problem withconstraintsfollows.Supposewearegiventheobjectfunction f x x x xn( , , , , )1 2 3 ā€¦ inwhichthevariablesx x x xn, , , ,1 2 3 ā€¦ aresubject toNconstraints,say

( , , , , ) 0

( , , , , ) 0

( , , , , ) 0

1 1 2 3

2 1 2 3

1 2 3

x x x x

x x x x

x x x x

n

n

N n

ā€¦

ā€¦

ā€¦

Ī¦ =

Ī¦ =

Ī¦ =

(10.6)

Theoretically,theNxā€™scanbesolvedintermsoftheremainingxā€™s.Then,theseN variablescanbeeliminatedfromtheobjectivefunctionf bysubstitution,andtheextremeproblemcanbesolvedasiftherewerenoconstraints.Thismethodisreferredtoastheimplicit methodandinmostcasesisimpractical.

Page 321: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 305

ThemethodofLagrange multipliersprovidesthemeansforsolvinganextremaproblemwithconstraintsanalytically.Suppose f x x x xn( , , , , )1 2 3 ā€¦ istobemaxi-mizedsubjecttoconstraints ( , , ),1 1 2x x xnā€¦Ī¦ ( , , ), ,2 1 2x x xnā€¦ ā€¦Ī¦ ( , , )1 2x x xn nā€¦Ī¦asinEquation(10.6).WedefinetheLagrange functionFas

ā€¦ ā€¦ ā€¦

ā€¦ ā€¦

= +Ī» Ī¦

+ Ī» Ī¦ + + Ī» Ī¦

( , , , , ) ( , , , , ) ( , , , , )

( , , , , ) ( , , , , )

1 2 3 1 2 3 1 1 1 2 3

2 2 1 2 3 1 2 3

F x x x x f x x x x x x x x

x x x x x x x x

n n n

n N N n

where iĪ» aretheunknownLagrangemultiplierstobedetermined.Wenowset

ā€¦

ā€¦

āˆ‚āˆ‚

=āˆ‚āˆ‚

=āˆ‚

=āˆ‚āˆ‚

=

Ī¦ = Ī¦ = Ī¦ = Ī¦ =

0, 0, 0, , 0

0, 0, 0, , 0

1 3

2 3

Fx

Fx

Fdx

Fx2 n

1 N

(10.7)

(Note:āˆ‚āˆ‚Ī»

= 0Fj

implies j 0Ī¦ = .)

Thissetofn + Nequationsgivesallpossibleextremaoff[1].

Exampleā€‚10.5

A silo is to consist of a right circular cylinder of radius R and length L, with a hemispherical roof (see Figure 10.2). Assume that the silo is to have a specified volume V = 8400 m3. Find the dimensions R and L that make its surface area S a minimum. Assume that the silo has a floor of the same

material. Note: = Ļ€V R43

sphere3 and S R4sphere

2= Ļ€ .

R

L

Figureā€‚10.2ā€‚ Siloā€‚consistingā€‚ofā€‚aā€‚rightā€‚circularā€‚cylinderā€‚toppedā€‚byā€‚aā€‚hemisphere.

Page 322: Numerical and Analytical Methods with MATLAB for

306ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Solution:

= Ļ€ +Ļ€V R R L23

3 2 (10.8)

R R L V

23

03 2Ī¦= Ļ€ +Ļ€ āˆ’ = (10.9)

S RL R R

RL R

2 2

2 3

2 2

2

= Ļ€ +Ļ€ + Ļ€

= Ļ€ + Ļ€ (10.10)

In this case, the surface area S is the function to be minimized, and the vol-ume V is the constraint. The Lagrange function is

F S

RL R R R L V2 323

2 3 2

= + Ī»Ī¦

= Ļ€ + Ļ€ +Ī» Ļ€ +Ļ€ āˆ’ (10.11)

The variables are R, L, and Ī». Taking partial derivatives with respect to R and L gives

FR

L R R RL2 6 (2 2 ) 02āˆ‚āˆ‚

= Ļ€ + Ļ€ + Ī» Ļ€ + Ļ€ = (10.12)

FL

R R RR

2 0 2 or22āˆ‚

āˆ‚= Ļ€ + Ī»Ļ€ = ā†’ Ī» = āˆ’ Ī» = āˆ’ (10.13)

Substituting the value of Ī» from Equation (10.13) into (10.12) gives

L R

RR RL2 6

2(2 2 ) 02Ļ€ + Ļ€ āˆ’ Ļ€ + Ļ€ = (10.14)

Equation (10.14) reduces to R āˆ’ L = 0 or R = L.Substituting this result into Equation (10.8) gives

V R R

R

23

53

3 3

3

= Ļ€ + Ļ€

= Ļ€

Page 323: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 307

For V 8400 m3= ,

R

8400 35

11.7065m1/3

=ƗĻ€

=

Substituting the values for R and L into Equation (10.10) gives S = 2152.6 m2.

10.7ā€‚ ā€‚MATLABā€™sā€‚fminconā€‚FunctionMATLABā€™sfunctionforsolvingoptimizationproblemswithconstraintsisfmincon.Thefminconfunctiontakesasargumentsauser-definedfunctionFUN,astartingpointX0,plusadditionalargumentsthatdependonthetypeofconstraintsdefinedintheproblem.

ThefunctionFUN definestheobject functiontobeminimized.ThevectorX0isaninitialguessofthecontrolvariablesthatminimizestheobjectfunction.MATLABā€™sfminconhandlesfourtypesofconstraints:

1.Inequality constraints:The constraints involveoneormore inequalities oftheform Źŗ*A X B .Supposetheproblemspecifiesthree linear inequalityconstraintsoftheform

11 1 12 2 1 1

21 1 22 2 2 2

31 1 32 2 3 3

a x a x a x b

a x a x a x b

a x a x a x b

n n

n n

n n

+ + + ā‰¤

+ + + ā‰¤

+ + + ā‰¤

TheseconstraintswouldbespecifiedinMATLABforusewithfminconas

A=[a11a12ā€¦a1n ;a21a22ā€¦a2n ;a31a32ā€¦a3n] B=[b1;b2;b3]

2.Equalityconstraints:Theconstraints involveoneormoreequalitiesof theform =*A X Beq eq.Supposetheproblemspecifiestwolinearequalitycon-straintsoftheform

a x a x a x b

a x a x a x b

n n

n n

11 1 12 2 1 1

21 1 22 2 2 2

+ + + =

+ + + =

Page 324: Numerical and Analytical Methods with MATLAB for

308ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

where aij and bi are theelementsof A eq and Beq, respectively.Thesecon-straintswouldbespecifiedinMATLABforusewithfminconas

Aeq=[ 11 12 1a a a n; 21 22 2a a a n]

Beq=[ 1b ;

2b ]

3.Bounds:Theconstraintsinvolvelowerorupperlimitsoftheform ā‰„X LBand ŹŗX UB.Then,youwouldspecifytheboundsinMATLABforusewithfminconas

LB=[ 1 2l l ln] UB=[ 1 2u u un ]

wherex l x l x ln n, , ,1 1 2 2 ā€¦ā‰„ ā‰„ ā‰„ and x u x u x un n, , ,1 1 2 2 ā€¦Źŗ Źŗ Źŗ .

4.Nonlinearconstraints:Theconstraintsaredefinedbythefunction[C,Ceq] =NONLCON(X),whereNONLCON is a (user-defined)MATLABfunction thatspecifies the nonlinear inequality constraints C and the nonlinear equalityconstraintsCeq.Supposetheproblemspecifiestwononlinearinequalitycon-straints andonenonlinear equality constraint.Thenonlinear inequality andequalityconstraintfunctionsf1,f2,andf3needtobesetupsuchthat

ā‰¤ ā‰¤ =( , ,..., ) 0, ( ,..., ) 0 and ( ,..., ) 01 1 2 2 1, 2 3 1, 2f x x x f x x x f x x xn n n

Then, in the function NONLCON, set C(1) f x x xn( , ,..., )1 1 2= , C(2)f x x xn( , ,..., )2 1 2= ,andCeq(1) f x x xn( , , ..., ) .3 1 2=

Adescriptionofthemanyinvocationsoffminconcanbeobtainedbytypinghelp fminconintheCommandwindow,someofwhicharedescribednext.

Usage 1X=FMINCON(FUN,X0,A,B)startsatX0andfindsaminimumXtothefunctionFUN,subjecttothelinearinequalitiesA*X<=B.FUNacceptsinputXandreturnsascalarfunctionvalueFevaluatedatX.X0maybeascalar,vector,ormatrix.

Thisfirstversionisusedonlyifalltheconstraintsarelinearinequalities;thatis,A*X<=B.Inthiscase,thescriptstartsatX0andfindscontrolvariablesXthatminimizetheobjectfunctioncontainedinFUNandreturnstheXvaluestothecallingprogram.TheinitialguessX0isacolumnvector,andA,Bdescribeasystemofequationsdefiningtheinequalityconstraints.

Page 325: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 309

Usage 2X=FMINCON(FUN,X0,A,B,Aeq,Beq)minimizesFUNsubjecttothelinearequalitiesAeq*X=BeqaswellasA*X<=B.(SetA=[]andB=[]ifnoinequalitiesexist.)

Thesecondversionisusediftherearealsolinearequalityconstraints;thatis,Aeq*X=Beq,whereAeqandBeqdescribeasystemofequationsdescribingtheequalityconstraints.Iftherearenoinequalityconstraints,thenuse[]forAandB.

Usage 3X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB)definesasetoflowerandupperboundsonthedesignvariables,X,sothatasolutionisfoundintherangeLB<=X<=UB.UseemptymatricesforLBandUBifnoboundsexist.SetLB(i)=-InfifX(i)isunboundedbelow;setUB(i)=InfifX(i)isunboundedabove.

ThethirdversionisusedifyouwishtosetlowerandupperlimitsLBandUBtothecontrolvariables,whereLBandUBarevectorscontainingtheboundsonX.

Usage 4X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON)subjectstheminimizationtotheconstraintsdefinedinfunctionNONLCON.ThefunctionNONLCONacceptsXandreturnsthevectorsCandCeq,representingthenonlinearinequalitiesandequalitiesrespectively.FMINCONminimizesFUNsuchthatC(X)<=0andCeq(X)=0.(SetLB=[]and/orUB=[]ifnoboundsexist,dothesameforA,B,Aeq,Beqiftherearenolinearinequalityorlinearequalityconstraints.)

ThefourthversionisusediftherearenonlinearconstraintsasdefinedinthefunctionNONLCONofXasdemonstratedinExamples10.7and10.8.

Notethatinallusagesprovided,wehaveinvokedfminconasreturningasinglevector,thatis,theformX=fmincon(FUN,X0,...).However,forconvenience,we can also use the form[X,FVAL] = fmincon(FUN,X0,...), which alsoreturnsFVAL,whichistheminimumvalueoftheobjectfunction.

Exampleā€‚10.6

In this example, we use fmincon to determine the maximum and minimum values of the object function of Example 10.4 subject to the constraints specified in that example.

Page 326: Numerical and Analytical Methods with MATLAB for

310ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

%Example_10_6.m:Linearprogrammingexampleusing%MATLAB'sfminconfunctionforoptimization%Objectfunction:2*x(1)+3*x(2)%Lowerbounds%x(1)>=0x(2)>=0%Upperbounds%x(1)<=3x(2)<=3%Inequalityconstraints%x(1)+x(2)<=4%6*x(1)+2*x(2)>=8%x(1)+5*x(2)>=8clear;clc;lb=[0;0];%Lowerboundub=[3;3];%Upperboundx0=[0;0];%InitialguessAeq=[];%NolinearequalityconstraintsBeq=[];%NolinearequalityconstraintsA=[11;-6-2;-1-5];%LinearinequalityconstraintsB=[4;-8;-8];%Linearinequalityconstraints[xmin,fvalmin]=fmincon(@object_fmin,...x0,A,B,Aeq,Beq,lb,ub);[xmax,fvalmax]=fmincon(@object_fmax,...x0,A,B,Aeq,Beq,lb,ub);%Printminandmaxvalues:fprintf('MIN\n');fprintf('-------------------------------\n');fprintf('xmin(1)=%.4fxmin(2)=%.4f\n',xmin(1),xmin(2));fprintf('fmin=%.4f\n\n',fvalmin);fprintf('MAX\n');fprintf('-------------------------------\n');fprintf('xmax(1)=%.4fxmax(2)=%.4f\n',xmax(1),xmax(2));fprintf('fmax=%.4f\n',-fvalmax);%object_fmin.m%ThisfunctionworkswithExample_10_6.mfunctionf=object_fmin(x)f=2*x(1)+3*x(2);%object_fmax.m%ThisfunctionworkswithExample_10_6.mfunctionf=object_fmax(x)f=-(2*x(1)+3*x(2));

-----------------------------------------------------------------------

PROGRAMā€‚RESULTS

MIN-------------------------------xmin(1)=0.8571xmin(2)=1.4286fmin=6.0000MAX-------------------------------xmax(1)=1.0000xmax(2)=3.0000fmax=11.0000

Page 327: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 311

Exampleā€‚10.7

Solve for the minimum surface area of the silo in Example 10.4 using MATLABā€™s fmincon function.

%Example_10_7.m:Thisprogramminimizesthematerial%surfaceareaofasilo.Thesiloconsistsofaright%cylindertoppedbyahemisphere.Solvewherethesilo%volumeis8400m^3.%DefinethevectorX=[R,L]whereRisradiusandLis%length(asdrawninFigure10.1)%Thefunctionobjfun_silocalculatesthesilosurface%areaandistheobjectivefunctiontobeminimized.%Thefunctionconfun_silodefinestheconstraintthat%thesilovolumebefixedat8400.clear;clc;globalV;V=8400;%Definebounds:radiusandlengthmustbepositive.LB=[0,0];UB=[];%InitialguessesforRandL:Xo=[10.020.0];fprintf('Thisprogramminimizesthesurfacearea\n');fprintf('ofasiloconsistingofarightcylinder\n');fprintf('toppedbyahemisphere.Thesilovolume\n');fprintf('isfixedat%.0fm^3.\n\n',V);%Runtheoptimization.Wehavenolinearconstraints,%sopass[]forthosearguments:[X,fval]=fmincon(@objfun_silo,Xo,...[],[],[],[],LB,UB,@confun_silo);%Printresults:fprintf('Silovolume:%9.3fm^3\n',V);fprintf('Minimumsurfacearea:%9.3fm^2\n',fval);fprintf('Optimumradius:%9.3fm\n',X(1));fprintf('Optimumlength:%9.3fm\n',X(2));----------------------------------------------------------------------%objfun_silo.m(objectfunctionforExample10.7)functionSA=objfun_silo(X)%Calculatesurfaceareaofsilo.Thevariablesare:%radiusR=X(1),lengthofcylinderL=X(2)SA=2.0*pi*X(1)*X(2)+3.0*pi*X(1)^2;-----------------------------------------------------------------------%confun_silo.m(constraintfunctionforExample10.7)function[c,ceq]=confun_silo(X)%Variablesare:%radiusR=X(1),lengthofcylinderL=X(2).globalV;%Nonlinearequalityconstraints:ceq=pi*X(1)^2*X(2)+2.0/3.0*pi*X(1)^3-V;%Nononlinearinequalityconstraints:c=[];

-----------------------------------------------------------------------

Page 328: Numerical and Analytical Methods with MATLAB for

312ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

PROGRAMā€‚RESULTS

OptimizationProblem:Thisprogramminimizesthesurfaceareaofasiloconsistingofarightcylindertoppedbyahemisphere.Thesilovolumeissetat8400 m^3Silovolume: 8400.000m^3Minimumsurfacearea: 2152.651m^2Optimumradius: 11.707 mOptimumlength: 11.706 m

Exampleā€‚10.8

Suppose we now reverse Example 10.7 and determine the maximum volume of the silo described in Example 10.7 subjected to the constraint that the surface area of the silo is to be less than a specified amount, say 2152.6 m2. The solution to the problem using MATLABā€™s fmincon follows:%Example_10_8.m:Thisprogrammaximizesthevolumeofa%silo.Thesiloconsistsofarightcylindertoppedbya%hemisphere.Thevariablestooptimizeareradius'R'%andcylinderheight'L'.%LetX(1)=RandX(2)=L.%Eqnforsurfacearea:S=3*pi*X(1)^2+2*pi*X(1)*X(2);%Constraint:3*pi*X(1)^2+2*pi*X(1)*X(2)<=2152.6m^2.%Weneedtosetuptheconstraintintheform:%3*pi*X(1)^2+2*pi*X(1)*X(2)-2152.6<=0%Wewishtomaximizethevolumeundertheconstraint.%Theequationforthevolume,V,ofthesiloisgivenby%V=2.0/3.0*pi*X(1)^3+pi*X(1)^2*X(2).%SincewewishtomaximizeV,wewillneedtoplacea%minussigninfrontoftheexpressionforVandthen%minimize.clear;clc;globalSAmax;SAmax=2152.6;%Definebounds:radiusandlengthmustbepositive.LB=[0,0];UB=[];%TakeaninitialguessatthesolutionXo=[10.020.0];fprintf('Thisprogrammaximizesthevolumeofasilo\n');fprintf('consistingofarightcylindertoppedbya\n');fprintf('hemisphere.Themaximumsurfaceareais\n');fprintf('fixedat%.1fm^3.\n\n',SAmax);%Runtheoptimization.Wehavenolinearconstraints,%sopass[]forthosearguments:[X,fval]=fmincon(@objfun_silo2,...Xo,[],[],[],[],LB,UB,@confun_silo2);SA=3*pi*X(1)^2+2*pi*X(1)*X(2);%Printresults:fprintf('Maximumsurfacearea:%9.3fm^2\n',SA);fprintf('Maximumvolume:%9.3fm^3\n',-fval);

Page 329: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 313

fprintf('Optimumradius:%9.3fm\n',X(1));fprintf('Optimumlength:%9.3fm\n',X(2));

-----------------------------------------------------------------------

%objfun_silo2.m(objectfunctionforExample10.8)functionV=objfun_silo2(X)%Computevolumeofsilo.Thevariablesare:%radiusR=X(1),lengthofcylinderL=X(2)V=-(2.0/3.0*pi*X(1)^3+pi*X(1)^2*X(2));

-----------------------------------------------------------------------

%confun_silo2.m(constraintfunctionforExample10.8)function[c,ceq]=confun_silo2(X)globalSAmax;%Variablesare:%radiusR=X(1),lengthofcylinderL=X(2)%Nonlinearinequalityconstraint:c=3*pi*X(1)^2+2*pi*X(1)*X(2)-SAmax;%Nononlinearequalityconstraints:ceq=[];

-----------------------------------------------------------------------

PROGRAMā€‚RESULTS

OptimizationProblem:Thisprogrammaximizesthevolumeofasiloconsistingofarightcylindertoppedbyahemisphere.Themaximumsurfaceareaissetat2152.6m^3Maximumsurfacearea:2152.600m^2Maximumvolume: 8399.701m^3Optimumradius: 11.706mOptimumlength: 11.706m

Exampleā€‚10.9

Two machine shops, Machine Shop A and Machine Shop B, are to manu-facture two types of motor shafts, shaft S1 and shaft S2. Each machine shop has two turning machines: Turning Machine T1 and Turning Machine T2. The following table lists the production time for each shaft type on each machine and at each location:

Time to Manufacture (minutes)

Machine Shop A Machine Shop B

Shaft S1 Shaft S2 Shaft S1 Shaft S2

Turning Machine T1 4 9 5 8

Turning Machine T2 2 6 3 5

Page 330: Numerical and Analytical Methods with MATLAB for

314ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Shaft S1 sells for $35, and shaft S2 sells for $85. Determine the number of S1 and S2 shafts that should be produced at each machine shop and on each machine that will maximize the revenue for 1 hour of shop time.

%Example_10_9.m:ShaftProductionProblem%Thisprogrammaximizestherevenue/hrforthe%productionoftwotypesofshafts,typeS1andtypeS2.%Therearetwomachineshopsproducingtheseshafts,%shopAandshopB.Eachshophastwotypesofturning%machines,T1andT2,capableofproducingtheseshafts.%ShopA:%MachineT1takes4minutestoproducetypeS1shafts%and9minutestoproducetypeS2shafts.%MachineT2takes2minutestoproducetypeS1shafts%and6minutestoproducetypeS2shafts.%ShopB:%MachineT1takes5minutestoproducetypeS1shafts%and8minutestoproducetypeS2shafts.%MachineT2takes3minutestoproducetypeS1shaft%and5minutestoproducetypeS2shafts.%ShaftS1sellsfor$35andshaftS2sellsfor$85.%WewishtodeterminethenumberofS1&S2shaftsthat%shouldbeproducedateachshopandbyeachmachine%thatwillmaximizetherevenue/hrforshaftproduction.%Let:%X(1)=#ofS1shaftsproduced/hrbymachineT1atshopA%X(2)=#ofS2shaftsproduced/hrbymachineT1atshopA%X(3)=#ofS1shaftsproduced/hrbymachineT2atshopA%X(4)=#ofS2shaftsproduced/hrbymachineT2atshopA%X(5)=#ofS1shaftsproduced/hrbymachineT1atshopB%X(6)=#ofS2shaftsproduced/hrbymachineT1atshopB%X(7)=#ofS1shaftsproduced/hrbymachineT2atshopB%X(8)=#ofS2shaftsproduced/hrbymachineT2atshopB%Letr=totalrevenue/hrforproducingtheseshafts:%r=35*(X(1)+X(3)+X(5)+X(7))+85*(X(2)+X(4)+X(6)+X(8))clear;clc;%Objectivefunction:totalrevenueperhourfor%manufacturedshafts.Havethefunctionreturna%negativenumberbecausewearemaximizinginsteadof%minimizing.revenue=@(x)-(35*(x(1)+x(3)+x(5)+x(7))+85*(x(2)+x(4)ā€¦+x(6)+x(8)));%TakeaguessatthesolutionXo=[00000000];%Lowerandupperbounds:LB=[00000000];UB=[];%Wehavelinearinequalityconstraints.Werequirethat%eachmachinemakeanintegralnumberofshaftsper60%minutes,so:%4*X(1)+9*X(2)<=60

Page 331: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 315

%2*X(3)+6*X(4)<=60%5*X(5)+8*X(6)<=60%3*X(7)+5*X(8)<=60A=[49000000;00260000;00005800;00000035];B=[60606060]';%Wehavenolinearequalityconstraints,sopass[]for%thosearguments.[X,rmax]=fmincon(revenue,Xo,A,B,[],[],LB,UB);fprintf('OptimizationResults:\n\n');fprintf('No.ofS1shaftsproducedatshopA');fprintf('bymachineT1:%2.0f\n',X(1));fprintf('No.ofS2shaftsproducedatshopA');fprintf('bymachineT1:%2.0f\n',X(2));fprintf('No.ofS1shaftsproducedatshopA');fprintf('bymachineT2:%2.0f\n',X(3));fprintf('No.ofS2shaftsproducedatshopA');fprintf('bymachineT2:%2.0f\n',X(4));fprintf('No.ofS1shaftsproducedatshopB');fprintf('bymachineT1:%2.0f\n',X(5));fprintf('No.ofS2shaftsproducedatshopB');fprintf('bymachineT1:%2.0f\n',X(6));fprintf('No.ofS1shaftsproducedatshopB');fprintf('bymachineT2:%2.0f\n',X(7));fprintf('No.ofS2shaftsproducedatshopB');fprintf('bymachineT2:%2.0f\n\n',X(8));fprintf('Themaxrevenueperhour:$%.0f/hour\n',-rmax);

---------------------------------------------------------

PROGRAMā€‚OUTPUT

OptimizationResults:No.ofS1shaftsproducedatshopA,T1:0No.ofS2shaftsproducedatshopA,T1:7No.ofS1shaftsproducedatshopA,T2:30No.ofS2shaftsproducedatshopA,T2:0No.ofS1shaftsproducedatshopB,T1:0No.ofS2shaftsproducedatshopB,T1:8No.ofS1shaftsproducedatshopB,T2:0No.ofS2shaftsproducedatshopB,T2:12Themaxrevenueperhour:$3274/hour

Note: When the program is run, MATLAB gives diagnostic warnings to the screen that can be ignored. If a satisfactory solution is obtained, MATLAB will inform you by saying

Localminimumfoundthatsatisfiestheconstraints.

Page 332: Numerical and Analytical Methods with MATLAB for

316ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

ExercisesExercise.10.1

UseMATLABā€™sfminunc() function tofind themaximaandminimaof thefollowingfunctions:

1. ( ) 10 20 154 3f x x x x= + āˆ’ āˆ’

2. =āˆ’

āˆ’ +( ) sin ( 0.75)

1.5 0.5625

2

2f xx

x x 3. = āˆ’( ) sin2 (for ā‰„ 0)0.5f x e x xx

Exercise.10.2

Usethemethodofsteepest-descenttoobtaintheapproximatepositionthatmakesf arelativeminimumwhere

( , ) 8 20 17 32 401 2 12

1 2 22

1 2f x x x x x x x x= āˆ’ + āˆ’ +

Use( , ) (6,4)1 2x x = asthestartingpoint,ds =0.05,and200steps.

Exercise.10.3

UseLagrangemultiplierstofindthevolumeofthelargestboxthatcanbeplacedinsidetheellipsoid

+ + = 1

2

2

2

2

2

2xa

yb

zc

sothattheedgeswillbeparalleltothecoordinateaxis.

ProjectsProject.10.1

AsiloconsistsofarightcircularcylindertoppedbyarightcircularconeasshowninFigure P10.1.Theradiusofboth thecylinderand thebaseof thecone isR.ThelengthofthecylinderisL,andtheheightoftheconeisH.Thecylinder,thecone,andthesilofloorareallmadeofthesamematerial.WriteaprogramusingMATLABā€™sfminconfunctiontodeterminethevaluesofR,H,andLthatwillresultintheminimumsurfacesiloareaforaninternalsilovolumeof7000m3.

Note:Forarightcircularcone,

3

2

2 2

VR H

S R R H

=Ļ€

= Ļ€ +

Page 333: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 317

Project.10.2

Aretailstoresellscomputerstothepublic.Thereareeightdifferentcomputertypesthatthestoremaycarry.TableP10.2liststhetypeofcomputer,thesellingprice,andthecosttothestore.Thestoreplanstospend$20,000permonthpurchasingthecomputers.

Thestoreplanstospendnomorethan30%ofitscostsoncomputertypesC1andC2,nomorethan30%oncomputertypesC3andC4,nomorethan10%oncomputertypesC5andC6,andnomorethan30%oncomputertypesC7andC8.Thestoreestimatesthatitcansell30%moreoftypeC1thanC2,20%moreoftypeC3thantypeC4,20%moreoftypeC5thanC6,and60%moreoftype

L

H

R

Figureā€‚P10.1ā€‚ Siloā€‚consistingā€‚ofā€‚aā€‚rightā€‚circularā€‚cylinderā€‚toppedā€‚byā€‚aā€‚rightā€‚cir-cularā€‚cone.

Tableā€‚P10.2ā€‚ Retailā€‚Priceā€‚andā€‚Manufacturingā€‚Costā€‚forā€‚Computerā€‚Typesā€‚C1ā€‚throughā€‚C8

Computer Type Selling Price ($) Cost ($)

C1 675 637

C2 805 780

C3 900 874

C4 1025 990

C5 1300 1250

C6 1500 1435

C7 350 340

C8 1000 1030

Page 334: Numerical and Analytical Methods with MATLAB for

318ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

C7thanC8.UsethefminconfunctioninMATLABtodeterminethenumberofeachtypeofcomputerthatwillprovidethestorewiththemostprofit.Printoutthenumberofeachtypeofcomputerthestoreshouldpurchasepermonth,thetotalprofitpermonthandthetotalcostpermonthtothestore.

Project.10.3

The Jones Electronics Corporation has a contract to manufacture four differentcomputercircuitboards.Themanufacturingprocessrequireseachoftheboardstopassthroughthefollowingfourdepartmentsbeforeshipping:etchingandlamina-tion(etcheswiringintoboard);drilling(drillsholestosecurecomponents);assem-bly(installstransistors,microprocessors,etc.);andtesting.ThetimerequirementinminutesforeachunitproducedanditscorrespondingprofitvaluearesummarizedinTableP10.3a.

Eachdepartmentislimitedto3daysperweektoworkonthiscontract.TheminimumweeklyproductionrequirementtofulfillacontractisshowninTableP10.3b.

WriteaMATLABprogramthatwill

1. Determinethenumberofeachtypeofcircuitboardforthecomingweekthatwillprovidethemaximumprofit.Assumethatthereare8hoursperday,5daysperweekavailableforfactoryoperations.Note:Notalldepartmentsworkonthesameday.

2. Determinethetotalprofitfortheweek.

Tableā€‚P10.3bā€‚ Minimumā€‚Weeklyā€‚Productionā€‚Requirementā€‚forā€‚Variousā€‚Circuitā€‚Boardā€‚Types

Circuit Board Minimum Production Count

Board A 10

Board B 10

Board C 10

Board D 10

Tableā€‚P10.3aā€‚ Manufacturingā€‚Timeā€‚forā€‚Variousā€‚Circuitā€‚Boardā€‚Typesā€‚inā€‚Eachā€‚Department

Circuit Board

Etching and Lamination (minutes)

Drilling (minutes)

Assembly (minutes)

Testing (minutes)

Unit Profit ($)

Board A 15 10 8 15 12

Board B 12 8 10 12 10

Board C 18 12 12 17 15

Board D 13 9 4 13 10

Page 335: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 319

3. Determinethetotalnumberofminutesittakestoproducealltheboards. 4. Determinethetotalnumberofminutesspentineachofthefourdepartments. 5. Printtherequestedinformationtoafile.

Project.10.4

TheXYZoilcompanyoperatesthreeoilwells(OW1,OW2,OW3)andsuppliescrudeoiltofourrefineries(refineryA,refineryB,refineryC,refineryD).Thecostofshippingthecrudeoilfromeachoilwelltoeachoftherefineries,thecapacityofeachofthethreeoilwells,andthedemand(equalityconstraint)forgasolineateachrefineryaretabulatedinTableP10.4a.Thecrudeoilateachrefineryisdistilledintosixbasicproducts:gasoline,lubricatingoil,kerosene,jetfuel,heatingoil,and

Tableā€‚P10.4aā€‚ Costā€‚ofā€‚Shippingā€‚perā€‚100ā€‚Litersā€‚($)

Oil WellRefinery

ARefinery

BRefinery

CRefinery

DOil Well

Capacity (liters)

OW 1 9 7 10 11 7000

OW 2 7 10 8 10 6100

OW 3 10 11 6 7 6500

Demand (liters of gasoline)

2000 1800 2100 1900

Tableā€‚P10.4bā€‚ Costā€‚ofā€‚Distillationā€‚perā€‚100ā€‚Litersā€‚($)

Oil Well Refinery A Refinery B Refinery C Refinery D

OW 1 15 16 12 14

OW 2 17 12 14 10

OW 3 12 15 16 17

Tableā€‚P10.4cā€‚ Distillationā€‚Productsā€‚perā€‚Literā€‚ofā€‚Crudeā€‚Oil

Product Percentage per Liter from Distillation

Oil Well Gasoline

Lubricating Oil Kerosene Jet Fuel

Heating Oil Plastics

OW 1 43 10 9 15 13 10

OW 2 38 12 5 14 16 15

OW 3 46 8 8 12 12 14

Page 336: Numerical and Analytical Methods with MATLAB for

320ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

plastics.ThecostofdistillationperliterateachrefineryfromeachoftheoilwellsisgiveninTableP10.4b.ThepercentageofeachdistilledproductperliteristabulatedinTableP10.4c.TheprofitfromeachproductistabulatedinTableP10.4d.

UsingthefminconfunctioninMATLAB,determinethelitersofoiltobepro-ducedateachoilwellandshippedtoeachofthefourrefineriesthatwillsatisfythegasolinedemandandwillproducethemaximumprofit.Printoutthefollowingitems:

1. Thelitersproducedateachoilwell 2. Thelitersofgasolinereceivedateachrefinery 3. Thetotalcostofshippinganddistillationofallproducts 4. Thetotalrevenuefromthesaleofalloftheproducts 5. Thetotalprofitfromalloftheproducts

Project.10.5

Asecond-ordercontrolsystemhasafrequencyresponseofthefollowinggeneralform:

( )

2

2

2 2H ss s

n

n n=

Ļ‰+ Ī¶Ļ‰ +Ļ‰

(P10.5a)

where nĻ‰ isthenaturalfrequency(inradians/second),andĪ¶isthedampingfactor.Thestep responseofasystemisdefinedasitstime-domainresponsetoaunitstep

input.Inthes domain,thiscorrespondstotheproductH(s)U(s),where =( ) 1U s

s

istheLaplacetransformoftheunitstepfunctionu(t).Tofindthetime-domainstepresponsey(t),wefindtheinverseLaplacetransformofH(s)U(s):

L

L

( )=

=Ļ‰

+ Ī¶Ļ‰ +Ļ‰Ć—

āˆ’

āˆ’

( ) ( ) ( )

21

1

12

2 2

y t H s U s

s s sn

n n

(P10.5b)

Byperformingapartial-fraction expansiononEquation (P10.5b) andusinginverseLaplacetransformtables,weobtain

( )( )=

āˆ’ Ī¶ āˆ’ Ļ‰ +Ī¶

Ī¶ āˆ’Ī¶ āˆ’ Ļ‰ Ī¶ >

āˆ’ āˆ’Ļ‰ Ī¶ =

āˆ’ āˆ’Ī¶ Ļ‰ +Ī¶

āˆ’ Ī¶āˆ’ Ī¶ Ļ‰ Ī¶ <

āˆ’Ļ‰

āˆ’Ļ‰

āˆ’Ļ‰

( )

1 cosh 11sinh 1 1

1 1 1

1 cos 11

sin 1 1

22

2

22

2

y t

e t t

e t

e t t

tn n

tn

tn n

n

n

n

(P10.5c)

Tableā€‚P10.4dā€‚ Productā€‚Revenueā€‚perā€‚Literā€‚($)

Gasoline Lubricating Oil Kerosene Jet Fuel Heating Oil Plastics

0.40 0.20 0.20 0.50 0.25 0.15

Page 337: Numerical and Analytical Methods with MATLAB for

Optimizationā€ƒ ā—¾ā€ƒ 321

Thesettling time ts isdefinedasthetimeittakesfory(t)tosettletoitsfinalvaluewithinsomearbitraryrange,typically5%or10%.FigureP10.5showsthestepresponseforthreevaluesofĪ¶forĻ‰ = 1n .

Inthisproblem,wewishtofindtheoptimumvalueofĪ¶tominimizetheset-tlingtime.

1. WriteaMATLABfunctionnamedstep _ response(zeta,wn,t)thatcalculatestheunitstepresponseofH(s)asperEquation(P10.5c)asafunc-tionofĪ¶and nĻ‰ overthegivenintervalt.ConfirmthatyourfunctioniscorrectbyplottingthestepresponseforĪ¶ =0.2,Ī¶ =1,andĪ¶ =2.AssumeĻ‰ = 1n andusethetimeinterval0ā‰¤t ā‰¤20secinstepsof0.1sec.YourresultsshouldmatchFigureP10.5.

2. Write another MATLAB function named find _ settling _ time(zeta,wn,t,Etol)thatfindsthesettlingtimetSofawaveformgener-atedbystep _ response()tothetolerancespecifiedbytheEtolargument.Thewaveformy(t)maybeconsideredsettledwhenthemagnitudeofitsdeviationfromthefinalvalueislessthanthedesiredtolerance,thatis,

( ) ( )( )

y t yy

Etolāˆ’ āˆžāˆž

< (P10.5d)

5 10 15 20

1

Ī¶ = 0.2

y(t)

t (sec)

Ī¶ = 1

Ī¶ = 2

Figureā€‚P10.5ā€‚ Settlingā€‚timeā€‚ofā€‚anā€‚RLCā€‚circuitā€‚forā€‚Ī¶ =ā€‚0.2,ā€‚Ī¶ =ā€‚1,ā€‚andā€‚Ī¶ =ā€‚2.

Page 338: Numerical and Analytical Methods with MATLAB for

322ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

wherey(āˆž)isthefinalsettledvalueofs(t),andEtol isthedesirederrortolerance(e.g.,5%or10%).Thus,forexample,tofindthetimetSittakesfory(t)tosettleto5%ofitsfinalvalue,thefunctionshouldusethetechniquesdescribedinChapter4tofindtherootoftheequation

( ) 11

0.05 0y t āˆ’āˆ’ = (P10.5e)

Notethatintheunderdampedcase,y(t)mayoscillateinandoutoftolerancebeforefinallysettling.Thus,youshouldsearchfortherootofEquation(P10.5e)startingfromtherightsideofthewaveform(i.e.,startingatt =āˆž)ratherthanstartingatt =0.Then,youaresuretofindthefinalsettledvalueaftertheoscilla-tionshavediedaway.

3. Plottsfor0.2ā‰¤Ī¶ ā‰¤2instepsof0.01forasettlingtoleranceof5%.AssumethatĻ‰ = 1.n YoumightseesomediscontinuitiesinyourplotforĪ¶ ā‰¤1.Whatisthecauseofthediscontinuities?

4. UseMATLABā€™sfminunc()functiontofindthevalueofĪ¶thatminimizesthesettlingtime.Comparethisvaluewithyourplotfrompart3above.Doesyouranswerlookcorrect?

5. Usethecurve-fittingtechniquesofChapter8tofityourdatafortsversusĪ¶toafourth-orderpolynomialwithMATLABā€™spolyfit()function.Rerunyourminimizationonthefittedpolynomial.Doestheanswerseemmoreaccurate?

Reference 1. Wylie,C.R.,Advanced Engineering Mathematics,McGrawHill,NewYork,p.596.

Page 339: Numerical and Analytical Methods with MATLAB for

323

Chapter 11

Simulink

11.1ā€‚ ā€‚IntroductionSimulinkĀ®isusedwithMATLABĀ®tomodel,simulate,andanalyzedynamicsys-tems.Commonusesareforsolvingdifferentialequations,modelingfeedbacksys-tems,andsignalprocessing.

WithSimulink,modelscanbebuiltfromscratchoradditionscanbemadeto existing models. Simulations can be made interactive, so a change in para-meterscanbemadewhilerunningthesimulation.Simulinksupportslinearandnonlinearsystems,modeledincontinuoustime,sampletime,orcombinationsofthetwo.

Simulinkprovidesagraphicaluserinterface(GUI)forbuildingmodelsasblockdiagrams,usingclick-and-dragmouseoperations.Byusingscopesandotherdis-play blocks, simulation results can be seen interactively while the simulation isrunning.Theprogramincludesacomprehensivelibraryofcomponents(ā€œblocksā€)from which to construct models. Additional application-specific ā€œtoolboxesā€ arealsoavailable.

11.2ā€‚ ā€‚Creatingā€‚aā€‚Modelā€‚inā€‚Simulink 1.ClickontheSimulinkicononthemenubarintheMATLABwindowor

typesimulink in theMATLABCommandwindow.ThisbringsuptheSimulinkLibraryBrowserwindow(seeFigure 11.1).

Page 340: Numerical and Analytical Methods with MATLAB for

324ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

2.ClickonFileintheSimulinkLibraryBrowserwindow.SelectNewā€“Model(foranewmodel)orOpen foranexistingmodel.Thiswillbringupanuntitledmodelwindow(forthecaseofanewmodel)oranexistingmodelwindow.

3.Tocreateanewmodel,youneedtocopyblocksfromtheLibraryBrowserwindow into thenewmodelwindow.This canbedonebyhighlighting aparticularblockanddraggingitintothemodelwindow.Tosimplifythecon-nectionsofblocks,youmayneedtorotateablock90Ā°or180Ā°.Todothis,highlighttheblock,clickonFormatinthemenubar,andthenselectRotate Block(for90Ā°)orFlip Block(for180Ā°).

Simulinkhasmanycategoriesfordisplayingthelibraryblocks;thoseofinterestforthischapterareCommonlyUsedBlocks,Continuous,Discontinuities,MathOperations,Ports&Subsystems,SignalRouting,Sinks,Sources,andUser-DefinedFunctions.

CommonblocksthatwillbeusedrepeatedlyinthischapterareConstant,Clock (from the Sources library); Product, Gain, Sum (from the MathOperations library); Integrator (fromtheContinuous library);Scope,Display,

Figureā€‚11.1ā€‚ Simulinkā€‚Libraryā€‚Browserā€‚andā€‚untitledā€‚modelā€‚window.ā€‚(Fromā€‚MATLAB,ā€‚withā€‚permission.)

Page 341: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 325

ToWorkspace(fromtheSinklibrary);Relay(fromtheDiscontinuitieslibrary);Switch,Mux(fromtheSignalRoutinglibrary),andFcn(fromtheUser-DefinedFunctionslibrary).

11.3ā€‚ ā€‚Typicalā€‚Buildingā€‚Blocksā€‚inā€‚Constructingā€‚aā€‚Model 1.Additionoftwoconstantswithdisplayedoutput(seeFigure 11.2).Tosetthe

valueforaconstant,doubleclickontheblockandedittheconstantvalue.Toruntheprogram,clickonSimulation inthemenubarandselectStart;alternatively,clickthePlaybutton()inthemenubar.

2.Subtraction(seeFigure 11.3).TomaketheSumblockperformadifference,doubleclickontheblockandeditthelistofsigns.

3.Productoftwoblocks(seeFigure 11.4). 4.Divisionoftwoblocks(SeeFigure 11.5).

Display

50

Constant1

20

Constant

30

Figureā€‚11.2ā€‚ Constants,ā€‚Sum,ā€‚andā€‚Displayā€‚blocksā€‚forā€‚addition.

Display

10

Constant1

20

Constant

30

Figureā€‚11.3ā€‚ Constants,ā€‚Sum,ā€‚andā€‚Displayā€‚blocksā€‚forā€‚subtraction.

Page 342: Numerical and Analytical Methods with MATLAB for

326ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

5.Integrateasinewave(seeFigure 11.6).Inthesinewaveblockparameters,setthefrequencyto2rad/s.Toviewtheoutputwaveform,firstclickthePlaybutton()andthendoubleclickonthescopeblocktoopentheplot.Then,rightclickontheplotandselectautoscale.Theresultingwaveformistheintegralofsin 2x:

āˆ« = āˆ’ = āˆ’ āˆ’ = āˆ’sin2 dx 1

2cos2 1

2(cos2 1) 1

2(1 cos2 )

0 0x x t t

t t

(11.1)

Notethatbecausetheintegratorhasa(default)initialconditionofzero,theresultingwaveformwillvaryfromzerotoone.

Product Display

600

Constant1

20

Constant

30

Figureā€‚11.4ā€‚ Constants,ā€‚Product,ā€‚andā€‚Displayā€‚blocksā€‚forā€‚multiplication.

Product Display

1.5

Constant1

20

Constant

30

Figureā€‚11.5ā€‚ Constants,ā€‚Product,ā€‚andā€‚Displayā€‚blocksā€‚forā€‚division.

Sine Wave ScopeIntegrator

1s

Figureā€‚11.6ā€‚ Sineā€‚wave,ā€‚Integration,ā€‚andā€‚Scopeā€‚blocks.

Page 343: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 327

6.Solutionofasimpleordinaryfirst-orderdifferentialequation.ThemethodofsolutionisillustratedinExample11.1,whichconsidersthestepresponseofanRCcircuit.

Exampleā€‚11.1

For the series RC circuit of Figure 11.7, we examine the capacitor voltage vC with respect to time in response to a unit step input voltage. The governing equation (as derived in Example 6.1) is

dvdt RC

v vCi C

1( )= āˆ’ (11.2)

where

R = 10 kĪ© C = 4.7 Ī¼F

=

ā‰¤

>v

t

ti

0 V for 0

1V for 0

The block diagram for Equation (11.2) is shown in Figure 11.8, and the resulting scope output is shown in Figure 11.9.

+vi vC

+

āˆ’

CR

i

ā€“

Figureā€‚11.7ā€‚ First-orderā€‚RCā€‚circuit.

vc

vidvc/dt

1/RCStep

ScopeProduct Integrator

1s

Constant

21.28

Figureā€‚11.8ā€‚ Blockā€‚diagramā€‚forā€‚solvingā€‚Equationā€‚(11.2).

Page 344: Numerical and Analytical Methods with MATLAB for

328ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

11.4ā€‚ ā€‚Tipsā€‚forā€‚Constructingā€‚andā€‚Runningā€‚Models 1.Toconnectlinesfromtheoutputofablocktotheinputofasecondblock,

placethecursorontheoutputofthefirstblock,rightclickonthemouse,anddragthelinetotheinputofthesecondblock.

2.Toconnectapointonalinetotheinputofablock,placethecursorontheline,rightclickonthemouse,anddragthelinetotheinputoftheblock.

3.Toaddalphanumericinformationabovealine,usetheleftbuttonanddou-bleclickabovethelineandatextboxwillappear.Typeinthedesiredlabelandclickelsewhereto complete.

4.Toviewtheresultsonascope,doubleclickonthescopetomakeagraphappear.Toselectthegraphaxis,rightclickonthegraphandselectaxis prop-ertiesorautoscale.Inmostcases,selectingautoscaleissufficient.Youmayalsoclickonthebinocularsicontoautoscalethegraph.

5.Tosetinitialconditionsforanintegrator,doubleclickontheblockandedittheinitialconditionline.

6.By default, Simulink runs over a time interval of 0 to 10 sec. Thesetimes are inappropriate for many models (e.g., high-frequency circuits).To edit the start and stop times, click on Simulation in the menu bar,select Configuration Parameters, and edit the start and stop time boxes.Alternatively,youcanadjustthestoptimeinthemenubar(thestarttimedefaultstozero).

Figureā€‚11.9ā€‚ Scopeā€‚outputā€‚ofā€‚RCā€‚circuit.

Page 345: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 329

7.Torunthesimulation,clickonSimulationinthemenubarandchooseStart.Alternatively,clickthePlaybutton()inthemenubar.

11.5ā€‚ ā€‚Constructingā€‚aā€‚SubsystemSupposewebuildalargesystemconsistingofmanyblocks,andwewishtoreducethenumberofblocksappearingintheoverallblockdiagram.Thiscanbedonebycreatingasubsystem.Thesubsystemwillappearasasingleblock.Tocreateasub-system,placethecursorinthevicinityoftheregionthatistobecomeasubsystemandrightclickthemouse.Thisproducesasmalldashedboxthatcanbeenlargedbydraggingthemouseovertheregionenclosingthenumberofblockstobeincludedinthesubsystem(Figure 11.10).Whenthemousebuttonisreleased,adrop-downmenuappears.SelectCreate Subsystemtocausethemultipleblockstobereplacedwithasinglesubsystemblock.

In Figure 11.11, the constant, product, and integrator blocks have beencombined into the subsystem. This particular subsystem has one input andone output, but in general, a subsystem may have multiple inputs and out-puts.Bydoubleclickingonthesubsystem,youmayviewitscomponents(seeFigure 11.12).

vc

vidvc/dt

1/RCStep

ScopeProduct Integrator

1s

Constant

21.28

Figureā€‚11.10ā€‚ Constructingā€‚aā€‚subsystem.

vc

vi

Subsystem

In1 Out1Step

Scope

Figureā€‚11.11ā€‚ Blockā€‚diagramā€‚withā€‚subsystemā€‚forā€‚solvingā€‚Equationā€‚(11.2).

Page 346: Numerical and Analytical Methods with MATLAB for

330ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

11.6ā€‚ ā€‚Usingā€‚theā€‚Muxā€‚andā€‚Fcnā€‚BlocksAnalternativetotheblockdiagramforExample11.1isshowninFigure 11.13.Inthissolution,Simulinkā€™sMuxandFcnblocksareusedtosolvetheproblem.TheMuxblock allows you to select amongmultiple inputs (to adjust thenumber ofinputs,doubleclickontheblockandeditthenumberofinputs).Theuppermostinputisdesignatedu[1],theonebelowisdesignatedu[2],andsoon.Inthisexample,theoutputfromtheMuxblockshouldgototheinputoftheFcnblock.

ThepurposeoftheFcnblockistoallowarbitrarymathematicalandMATLABfunctionstobedefinedwithinthemodel.Inthiscase,themathexpressionintheFcnblockisusedtoimplementEquation(11.2)intermsoftheu[]ā€™s.

11.7ā€‚ ā€‚Usingā€‚theā€‚Transferā€‚Fcnā€‚BlockAcommonmethodfor solvingcircuitproblems is to substitutecomplex imped-ancesforthecapacitorsandinductorsandthensolvelikearesistivecircuit.FortheRCcircuit,theimpedanceoftheresistorissimplyZ RR = ,andtheimpedanceof

1/RC

vi

vc

dvc/dt

Step

ScopeIntegrator

1s

Fcn

u(2)*(u(1) ā€“ u(3))

Constant

21.28

Figureā€‚ 11.13ā€‚ Blockā€‚ diagramā€‚ forā€‚ solvingā€‚ Equationā€‚ (11.2)ā€‚ usingā€‚ theā€‚ Muxā€‚ andā€‚Fcnā€‚blocks.

dvc/dt

1/RCOut1

1

Product Integrator

1s

Constant

21.28

In1

1

Figureā€‚11.12ā€‚ Subsystemā€‚model.

Page 347: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 331

thecapacitoris 1Z CsC = (wheres =jĻ‰).Then,thecapacitorvoltageissimplytheoutputofaresistivedivider:

1

1

1

1

( )

v ZZ Z

v

CsR Cs

v

RCs RC

v

H s v

CC

R Ci

i

i

i

=+

=+

=+

=

where =+

( ) 1/1/

H sRC

s RC is commonly referred to as the transfer function. In

Simulink, theTransferFcnblockallowsdirect entryof a transfer function intoyourmodelasshowninFigure 11.14.

11.8ā€‚ ā€‚Usingā€‚theā€‚Relayā€‚andā€‚Switchā€‚BlocksRelaysandswitchesareusedindesignstoenablealow-powerdevice(e.g.,anelec-troniccontroller)tocontrolahigh-powersystem(e.g.,aboilerorfurnace).SimulinkhasRelayandSwitchblocksthatcanbeusedtosimulatethesetypesofsystems.

Exampleā€‚11.2

In a home heating system, a temperature sensor is used to switch the boiler on and off to heat the house to a comfortable temperature. However, because most boilers do not turn on and off instantaneously (i.e., they take a few minutes to heat up after turning on and take time to cool after turning off), the control of the room temperature requires some hysteresis to avoid cycling the boiler on and off too often (which causes excessive wear on the boiler). This concept can be represented by a simple differential equation in

Transfer Fcn

21.28

s + 21.28

Step Scope

Figureā€‚11.14ā€‚ Blockā€‚diagramā€‚usingā€‚theā€‚Transferā€‚Fcnā€‚block.

Page 348: Numerical and Analytical Methods with MATLAB for

332ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

which the temperature T is set to fluctuate at a constant rate between 20Ā°C and 22Ā°C :

= =ā‰¤

āˆ’ ā‰„dTdt

c cT

Twhere

30 if 20

30 if 22

The block diagram for this system consists of an Integrator, a Constant, a Relay, a Product, and a Scope (Figure 11.15). The Relay is used to invert the sign on c depending on whether the relay is on or off. The Relay parameters may be edited by double clicking on the Relay block and setting the param-eters to the following values:

Switch point on = 22Switch point off = 20Output when on = ā€“1Output when off = +1

We assume that the initial room temperature is T = 18Ā°C, and this value is entered into the parameters for the Integrator block. At the start of the simu-lation, T ā‰¤ 20; thus, the Relay switch is off, and the output of the Relay is +1, causing T to increase. The Relay output will remain +1 until T reaches 22, at which point the Relay will turn on and its output will be āˆ’1, causing T to decrease. The Relay output will remain āˆ’1 until T reaches 20, at which point the Relay will turn off and its output becomes +1 again. This process will continue until the simulation end time is reached. The output of the Scope is shown in Figure 11.16.

Exampleā€‚11.3

Some problems may involve a function that varies in time for t t0 1Źŗ Źŗ and is constant for t t t1 2< ā‰¤ . This type of function can best be modeled with the Switch block that implements a DPST (double-pole, single-throw) switch with an additional terminal to control the opening and closing of the switch.

Scope

Relay

Product Integrator

1s

Constant

30

Figureā€‚11.15ā€‚ Blockā€‚diagramā€‚usingā€‚theā€‚Relayā€‚blockā€‚fromā€‚Exampleā€‚11.2.

Page 349: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 333

Suppose

yt t

t

5 for 0 10

50 for 10 20=

ā‰¤ ā‰¤

< ā‰¤

The Simulink model for this problem is shown in Figure 11.17. The parameters for the Switch are as follows (note that terminal u1 is the top switch input, u2 is the middle [control] input, and u3 is the bottom switch input):

Figureā€‚11.16ā€‚ Scopeā€‚outputā€‚ofā€‚Exampleā€‚11.2.

Switch Scope

Gain

5

Constant

50

Clock

Figureā€‚11.17ā€‚ Blockā€‚diagramā€‚usingā€‚theā€‚Switchā€‚blockā€‚fromā€‚Exampleā€‚11.3.

Page 350: Numerical and Analytical Methods with MATLAB for

334ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

Criteria for passing first input: u2 ā‰„ ThresholdThreshold: 10

The resulting output is shown in Figure 11.18. Note that we use the Clock block to obtain a value for y that is proportional to the elapsed time.

11.9ā€‚ ā€‚Trigonometricā€‚Functionā€‚BlocksFunctionssuchassine,cosine,andtangentcanbeobtainedviatheTrigonometricFunctionblock located in Simulinkā€™sMathOperations library.The input tothisblockistheargumenttothedesiredtrigfunction.Iftheargumentinvolvesthe independentvariable t (as in sin Ļ‰t), thenwecanuse theClockblocktoobtainthevalueoft.ThisisshowninFigure 11.19,wherewecomputethevalueofcos2t.

Exampleā€‚11.4:ā€‚ Simulationā€‚ofā€‚anā€‚RLCā€‚Circuit

In Section 2.17, we studied the parallel RLC circuit. If we use a sinusoidal input current to the circuit in Figure 2.14 and assume that the switch closes at t = 0, the governing equation is

d idt RC

didt LC

iLC

I tL LL o

1 1 1sin

2

2 + + = Ļ‰ (11.3)

Figureā€‚11.18ā€‚ Scopeā€‚outputā€‚ofā€‚Exampleā€‚11.3.

Page 351: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 335

where the circuit is ā€œdrivenā€ by a sinusoidal current of frequency Ļ‰ and magnitude I0. The Simulink model in Figure 11.20 solves this second-order differential equation with the following circuit values and initial conditions:

C = 1 Ī¼FL = 10 mHR = 2000 Ī©Io 5mA=Ļ‰ = 2000 radian/seciL(0) 2mA=iL(0) 0=

The output of the simulation is shown in Figure 11.21. Simulation and workspace parameters for this example are as follows:

Simulation time:Start time: 0.0Stop time: 0.015

Solver options:Type: Variable stepSolver: ode45 (Dormand-Prince)Maximum step size: autoMinimum step size: autoInitial step size: autoRelative tolerance: 1e-3Absolute tolerance: auto

Workspace parameters:Variable name: iLimit data points to last: infDecimation: 1Sample time (-1 for inherited): -1

Save format: array

Note that you can export Simulink output values into MATLAB variables for further manipulation or for printing. You can do this with the To Workspace

cos 2t2t

Trigonometricfunction

cos

ScopeProduct

Constant

2

Clock

Figureā€‚ 11.19ā€‚ Blockā€‚ diagramā€‚ usingā€‚ theā€‚ Clock,ā€‚ Product,ā€‚ andā€‚ Trigonometricā€‚Functionā€‚blocks.

Page 352: Numerical and Analytical Methods with MATLAB for

336ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

d2i/d

t2di

/dt

i

t

1/LC

1/R

C

Io/L

C

i(0)

= 2e

ā€“ 3

w

Io *

sin

wt/L

C

Trig

onom

etric

func

tion

sin

To

wor

kspa

ce

i

Sco

pe1

Sco

pe

Pro

duct

3

Pro

duct

2

Pro

duct

1

Pro

duct

Inte

grat

or1

Inte

grat

or

1 s1 s

Con

stan

t3

2000C

onst

ant2

5e ā€“

3/(

10e

ā€“ 3*

1e ā€“

6)

Con

stan

t1

1/(2

000*

1e ā€“

6)

Con

stan

t

1/(1

0e ā€“

3*1

e ā€“

6)

Clo

ck

Figu

reā€‚1

1.20

ā€‚B

lock

ā€‚dia

gram

ā€‚forā€‚

solv

ingā€‚

theā€‚

seco

nd-o

rder

ā€‚dif

fere

ntia

lā€‚equ

atio

nā€‚of

ā€‚Equ

atio

nā€‚(1

1.3)

.

Page 353: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 337

block as shown in Figure 11.20. After the simulation is run, those vari-ables become available for use in any MATLAB program. When using To Workspace, be sure that the Save Format property is set to Array.

ExercisesExercise.11.1

ImplementthefollowingfunctioninSimulink:

= + +5 4 22y t t

1. UsingoneClockblock,threeConstants,twoMultipliers,andaSum. 2. UsingoneClockblock,threeConstants,aMuxblock,anFcnblock,aScope

block,andtwoToWorkspaceblocks.Thescopeblockshouldgiveaplotofyversust.Also,createaMATLABprogramthatconstructsatableofyversustintheCommandwindow.

3. UsingoneConstantandtwoIntegrators.

ProjectsProject.11.1

Adecision circuitisusedinacommunicationsystemtodecidewhetherareceiveddigital signal is a logicaloneor zero. It thenoutputs itsdecisionusingonboardlogiclevels.Forexample,intheRS-232serialcommunicationprotocol[1], thenominallogiclevelstorepresentalogicaloneorzeroareĀ±12V.However,typicallogiclevelsonacomputermotherboardare+5Vand0V.Wecanusearelayblock

Figureā€‚11.21ā€‚ Scopeā€‚outputā€‚ofā€‚Exampleā€‚11.4.

Page 354: Numerical and Analytical Methods with MATLAB for

338ā€ƒ ā—¾ā€ƒ Numerical and Analytical Methods with MATLAB

inSimulinktoexaminethebehaviorofadecisioncircuitthatimplementstheserequirementsinthepresenceofnoisethatisinducedintheRS-232cableduetofluorescentlights,radiowaves,andsoon.

1. UseSimulinkā€™sSignalGeneratorblock(fromtheSourceslibrary)togenerateabinarysignalofalternatingonesandzerosusingRS-232logiclevelsatarateof1200bits/sec.(Note:1200bits/secisnotthesameas1200Hz.)

2. Add white noise to your RS-232 signal with a Band-limited White Noiseblock (from the Sources library) and a Sum block. Set the parameters onthewhitenoisetobe2 10 4Ɨ āˆ’ forthenoisepowerand1 10 5Ɨ āˆ’ forthesampletime.ViewtheresultingnoisybinarysignalwithaScopeblockandconfirmthatitstilllookslikeabinarysignal(albeitwithnoise).

3. UseaRelayblocktoconvertyourRS-232binarysignalfrom+12V(foraone)andā€“12V(forazero)into+5V(foraone)and0V(forazero).Use0Vforboththeswitch-onandswitch-offpointsfortherelay.Runthesimulationfor0.01secandviewtheresultingoutputfromtherelaywithascope.Youshouldseesomeerrorsontherelayoutputduetothenoiseontheinput.

4. Wenowquantifythebiterrorsontherelayoutputasfollows: a. First,weneed togenerateaā€œperfectā€ (i.e.,noiseless)versionof the

relay output for comparison purposes. Thus, make a copy of yourexistingblocks(includingSignalGenerator,Relay,andScope)withinthecurrentmodelbutomittheNoiseGeneratorinthecopy.Then,runthesimulationagainfor0.01secandconfirmthatyouhavebothperfectandnoisyversionsattheoutputsofyourtworelays.

b. Next,createanerrorsignalbysubtractingthetworelayoutputswithaSumblock.

c. Next,generatethemagnitudeoftheerrorsignalwithanAbs(abso-lutevalue)block(fromtheMathOperationslibrary).Thepurposeofthisistomakesurethattheerrorsignalisalwayspositivesothatitmaybeeasilycounted.

d. Finally, send the output of your Abs block to an Integrator block(withaninitialconditionofzero)anduseaDisplayblocktomoni-tortheoutputofyourintegrator.Thepurposeoftheintegratoristoprovidearunningtotalofallofthedetectederrors.

5. Runthesimulationfor0.01seconyourcompletemodelcontainingdualrelayswithcumulativeerrordetection.Attheendofthesimulation,youshouldwindupwithapositivevalueattheoutputoftheintegrator.Also,tryrunningtheintegrationfor1secandseethatyouhaveevenmoreerrors.

6. Onemethodofimprovingtheerrorperformanceofthisdecisioncircuitistoinserthysteresisintotherelaytoincreasethenoisemargins.Toobservethis,modifytherelayswitch-onandswitch-offvaluesto+0.5andā€“0.5andrerunthesimulationfora1-secintervalandconfirmthatyouseefewererrors.Trythe various sets of switch-on and switch-off values listed in Table 11.1 andcompletethetable.Whathappensifyouusetoomuchhysteresis?

Project.11.2

RepeatProject6.3foraSallen-Keycircuitwithastepandimpulseinput,butthistimeuseSimulinktoconstructasimulationofthesystem.Scopeoutputshouldbeforvoutandv1versust.Settheendtimetot = 0.0001secandprintouttheblockdiagram,impulseresponse,andstepresponse.

Page 355: Numerical and Analytical Methods with MATLAB for

Simulinkā€ƒ ā—¾ā€ƒ 339

Project.11.3

Aswingingkitchendoorinarestaurantweighsm =20kgandhasaspringtocauseittocloseautomatically(withspringconstantk =300N/m)andapistondampertopreventitfromslamming(withdampingcoefficientc =150N-sec).WewishtosimulatethisdoorasanRLCcircuitinSimulink.Assumethatthedoorpositionxvariesovertherangeā€“1ā‰¤x ā‰¤1meter,whereā€“1and1correspondtothedoorbeingfullyopenineitherdirection,andzerocorrespondstotheclosedposition.

1. SetupamodelinSimulinktodescribethesecond-orderdifferentialequationforaseriesRLCcircuit(refertoAppendixAfortheproperequation).AssumethatthedoorpositionxisanalogoustothecapacitorvoltagevC.ForR,L,andC,usetheanalogousvaluesc,m,and1/k,respectively.Usetheinitialconditionx =1(i.e.,thedoorisfullyopenatt =0)andnoforcingfunction(analogoustozeroinputvoltage).Runthesimulationfor5sec.Isthisdoorunderdampedoroverdamped?

2. Now,assumethatthepistondamperbreaksoffthedoor,causingazerovalueforthedampingcoefficientc.Whathappenswhenyourerunthesimulation?Isthiswhatwouldhappeninreallife?Whyorwhynot?

3. Afterreplacingthedamagedpistondamper,therepairpersonmistakenlysetsthedampingcoefficientto50N-sec.Whathappenswhenyourerunthesimu-lation?Doesthismatchwhatwouldhappeninreallife?

4. Interpret these results back to the RLC circuit. What happens in an RLCcircuitforL =20,C=1/150,andaninitialcapacitorvoltageof1VwhenRchangesvaluefrom150Ī©to0Ī©to50Ī©?

Reference 1. McNamara, J., Technical Aspects of Data Communication, 3rd ed., Butterworth-

Heinemann,Oxford,UK,1988.

Table 11.1ā€‚ Cumulativeā€‚Errorsā€‚forā€‚theā€‚Decisionā€‚Circuitā€‚ofā€‚Problemā€‚11.1ā€‚forā€‚Variousā€‚Amountsā€‚ofā€‚Hysteresis

Switch-on and Switch-off Values

Cumulative Error Detected at Integrator Output (per second)

0, 0

+0.5, āˆ’0.5

+2, āˆ’2

+5, āˆ’5

+8, āˆ’8

Page 356: Numerical and Analytical Methods with MATLAB for
Page 357: Numerical and Analytical Methods with MATLAB for

341

Appendixā€‚A:ā€‚RLCā€‚Circuits

Theresistor-inductor-capacitor(RLC)circuitisusedrepeatedlyasanexampleinthistextanditsbehaviorisderivedindetailinthisappendix.Inelectricalengi-neering,thissimplesecond-ordersystemisuseddirectlyincircuittheory,signalprocessing,andcontroltheory.Inaddition,manynon-circuitproblemslendthem-selvestobeingmodeledwithRLC,includingphase-lockloops,transmissionlines,and non-electrical problems such as the spring-dashpot problem in mechanicalengineering,theresonanceofsoundwavesinacoustics,andeventheflowofauto-mobilesonahighwayduringatrafficjam.

TherearetwobasictopologiesofRLCcircuits:seriesandparallel(seeFigureA.1).Allotherconfigurationscangenerallybereducedtoeitherofthesetwobytransform-ingwithThƩveninorNortonequivalentcircuits[1](FigureA.2),soweonlyanalyzethebasictwohere.Intheseriescase,theinputvariableisavoltageandtheoutputisthecurrent;intheparallelcase,theoppositeistrue(currentin,voltageout).

A.1ā€‚ ā€‚Directā€‚Analysisā€‚withā€‚Differentialā€‚EquationsStartingwiththeseriescircuit,wemodeltheresistor,inductor,andcapacitorvolt-age-currentrelationsusingtheirrespectiveconstituentrelations:

=v i RR R (A.1)

=v L

didtLL (A.2)

=i C

dvdtCC (A.3)

Page 358: Numerical and Analytical Methods with MATLAB for

342ā€ƒ ā—¾ā€ƒ Appendix A

C

āˆ’

+vR

āˆ’

+vL

āˆ’

+vC

L

R

+ā€“vin

C

iL iCiR

LRiin

(a) (b)

Figureā€‚A.1ā€‚ (a)ā€‚Seriesā€‚RLCā€‚circuit,ā€‚(b)ā€‚Parallelā€‚RLCā€‚circuit.

C

L

R

+ā€“

C

LRiin iin Ɨ R

(a)

CLR

CL

R

+ā€“vin

vinR

(b)

Figureā€‚A.2ā€‚ Anyā€‚RLCā€‚networkā€‚canā€‚usuallyā€‚beā€‚convertedā€‚toā€‚eitherā€‚theā€‚seriesā€‚orā€‚theā€‚parallelā€‚configurationā€‚byā€‚applyingā€‚(a)ā€‚ThĆ©veninā€™sā€‚andā€‚(b)ā€‚Nortonā€™sā€‚theoremsā€‚toā€‚con-vertā€‚aā€‚seriesā€‚voltageā€‚sourceā€‚andā€‚resistorā€‚intoā€‚aā€‚parallelā€‚currentā€‚sourceā€‚andā€‚resistor.ā€‚

Page 359: Numerical and Analytical Methods with MATLAB for

Appendix Aā€ƒ ā—¾ā€ƒ 343

where vR, vL and vc are the voltages across the resistor, inductor, and capacitorrespectively, iR, iL and iC are their respective currents, andR,L andC are theirrespectivecomponentvaluesinohms,farads,andhenries.

ApplyingKirchhoffā€™svoltagelawaroundtheRLCloopgives

āˆ’ āˆ’ āˆ’ = 0V v v vin R L C (A.4)

Intheseriescase,allofthecomponentshavetheidenticalcurrentandthuswedefine = = =I i i iout R L C . SubstitutingEquations (A.1) and (A.2) into (A.4) andrearranginggives

+ + =I R L

dIdt

v Voutout

C in (A.5)

NowsubstitutingEquation(A.3)into(A.5)gives

+ + =

2

2RCdvdt

LCd vdt

v VC CC in

+ + =

12

2d vdt

RLdvdt LC

vVLC

C CC

in (A.6)

Equation (A.6) is a second-order differential equation for vC which can besolvedviastandardtechniques.Theā€œdrivingfunctionā€Vin(t)andthetwoinitialconditionsvC(0)andiL(0)arenecessarytoobtainacompletesolution.TosolveforvC(t),wechooseaparticularsolutionwhichsatisfiesthedifferentialequationfornonzeroVin(t),andthenwechooseahomogenoussolution(bysettingVin(t)=0)whichallowsustosatisfytheinitialconditions.ThisapproachisdemonstratedinExample6.1.Finally,oncewehavesolvedEquation(A.6)forvC,wecanobtainIoutbyapplyingEquation(A.3).

By a similar analysis, we can solve the parallel RLC circuit by applyingKirchhoffā€™scurrentlawtoobtain

+ + =

1 12

2d idt RC

didt LC

iILC

L LL

in (A.7)

NotethatEquations(A.6)and(A.7)havesimilarformandthusbysolvinga single differential Equation, we can solve both the series and parallel RLCcircuits.

Page 360: Numerical and Analytical Methods with MATLAB for

344ā€ƒ ā—¾ā€ƒ Appendix A

A.2ā€‚ ā€‚Analysisā€‚viaā€‚Circuitā€‚TheoryAcommonmethodforsolvingRLCcircuitsistoapplysimplecircuittheorywherewemodeltheresistor,inductor,andcapacitorwiththeircompleximpedancesZR,ZL,andZC :

=

=

=1

Z R

Z Ls

ZCs

R

L

C

wheres =jĻ‰isthecomplexfrequency.ApplyingOhmā€™slawtotheseriesRLCcir-cuitofFigureA.1agives

=+ +

=+ +

1

IV

Z Z Z

V

R LsCs

outin

R L C

in

=+ +

1

12

IV

Ls

sRLs

LC

out

in (A.8)

Similarly,applyingOhmā€™slawintheparallelcasegives

( )=

=+ +

1 1

V I Z Z Z

I

R LsCs

out in R L C

in

=+ +

1

1 12

VI

Cs

sRC

sLC

out

in (A.9)

Notethattheinput-outputrelationsinEquations(A.8)and(A.9)havesimilarformandareconsideredtobeā€œsecond-orderā€systemsbecausethehighesttermin

Page 361: Numerical and Analytical Methods with MATLAB for

Appendix Aā€ƒ ā—¾ā€ƒ 345

theirdenominatorsiss2.Wecanrewritetheseequationsintothegeneralformforsecond-ordersystems:

=

+ Ī¶Ļ‰ +Ļ‰( )

22 2H sKs

s sn n (A.10)

whereH(s)isthetransfer function, Ļ‰n isthenatural frequency,Ī¶ isthedamping factor,andKisaconstantscalingfactor.MatchingtermsbetweenEquations(A.3),(A.2),and(A.1),wesee:

Ļ‰ = Ī¶ = =

Ļ‰ = Ī¶ = =

Series RLC circuit: 1 ,2

, 1

Parallel RLC circuit: 1 , 12

, 1

LCR C

LK

L

LC RLC

KC

n

n

Thephysicalmeaningsfornaturalfrequencyanddampingfactorbecomeappar-entwhenweobservethefrequencybehaviorforH(s).TheBodeplotforEquation(A.10) is shown inFigureA.3,whereweassumethat Ļ‰ = 1000n andĪ¶has the

ā€“140

ā€“120

ā€“100

ā€“80

ā€“60

ā€“40

Mag

nitu

de (d

B)

100 101 102 103 104 105 106ā€“90

ā€“45

0

45

90

Phas

e (de

g)

Bode Diagram

Frequency (rad/sec)

Ī¶ = 0.1

Ī¶ = 0.1

Ī¶ = 1

Ī¶ = 1

Ī¶ = 10

Ī¶ = 10

Figureā€‚A.3ā€‚ Bodeā€‚plotā€‚ofā€‚anā€‚RLCā€‚circuitā€‚forā€‚š›šnā€‚=ā€‚1000ā€‚rad/sā€‚andā€‚Ī¶ā€‚valuesā€‚ofā€‚0.1,ā€‚1,ā€‚andā€‚10.

Page 362: Numerical and Analytical Methods with MATLAB for

346ā€ƒ ā—¾ā€ƒ Appendix A

values0.1,1,and10.NotethattheplotsarecenteredaroundĻ‰nandfalloffsym-metricallyasĻ‰ā†’0andĻ‰ā†’āˆž.Thus,H(s)isabandpass filterwithapassbandcen-teredaroundĻ‰n .ThisisconfirmedwhenweexamineEquation(A.10)atthelowandhighfrequencylimitsandat = Ļ‰s j n :

Ļ‰ =+ Ī¶Ļ‰ +Ļ‰

=

Ļ‰ =āˆž

āˆž + Ī¶Ļ‰ āˆž +Ļ‰=

Ļ‰ Ļ‰ =Ļ‰

Ļ‰ + Ī¶Ļ‰ Ļ‰ +Ļ‰=

Ī¶Ļ‰

Ļ‰ā†’

Ļ‰ā†’āˆž

at low frequencies: lim ( ) (0)0 2 (0)

0

at high frequencies: lim ( ) ( )2 ( )

0

at : ( )( ) 2 ( ) 2

0 2 2

2 2

2 2

H jK

H jK

H jKj

j jK

j n n

j n n

n nn

n n n n n

Thus,H(s)approacheszeroatlowandhighfrequenciesandhasapeakvalueatthenaturalfrequencywhichisdependentonthedampingfactor.Traditionally,thevaluesforĪ¶areclassifiedintothreetypes:underdamped(Ī¶<1),overdamped(Ī¶>1),andcriticallydamped(Ī¶ =1).FortheunderdampedcaseinFigureA.3(Ī¶ =0.1),H(s)hasatallnarrowpeakthatindicatesresonanceatthenaturalfre-quency,i.e.,onlyinputsignalsat(orverynearto)thenaturalfrequencywillbepassedbythefilter.Fortheoverdampedcase(Ī¶ =10),thereisnopeakatallbutratherthere issimplyawideflatpassband.Thecriticallydampedcase(Ī¶ =1)hasthenarrowestpassbandwithoutresonance,the implicationsofwhichwillbecomeclearmomentarilywhenweexaminethetransientresponse.

AnalternativerepresentationofthestandardformofEquation(A.10)is

=+Ļ‰

+Ļ‰( )

2 2H s

Ks

sQ

snn (A.11)

whereQisthequality factorandisanindicationoftheheightandwidthofthereso-nantpeakintheBodeplot.NotethatbycomparingEquations(A.11)and(A.10),

weseethat =Ī¶12

Q andthusthequalityfactoranddampingfactoraresimplytwo

differentwaysofexpressingthesameidea.ThechoicebetweenwhethertouseQorĪ¶isdependentontheapplication,withQusuallybeingusedinfilterdesignandĪ¶incontroltheory.Ahigh-Qfilter( > 1/2Q )isonewhichhashighresonanceandistypicallyusedinoscillatordesignortunablecircuits,andalow-Qfilter( <1/2)Q hasnoresonanceatall.Anintermediate Q factor( = 1/2Q )correspondstoacriti-callydampedresponse.

Thedampingfactorisfurtherillustratedbyexaminingthestepresponses(t).Fromsystemtheory,weknowthat

s(t)=h(t)*u(t)

Page 363: Numerical and Analytical Methods with MATLAB for

Appendix Aā€ƒ ā—¾ā€ƒ 347

whereh(t)isthesystemimpulseresponse(i.e.,theinverseLaplacetransformofH(s)),u(t)istheunitstepfunction,andtheā€œ*ā€operatorindicatesconvolution.Inordertoavoiddoingtheconvolution,wesolveintheLaplacedomainwheretheconvolutionoperatortransformstomultiplication.Thus,thes-domainstepresponseS(s)is

= Ɨ( ) ( ) 1

S s H ss

wherewehaveusedthetransformrelation L( ) =( ) 1u t

s.Byfactoringthedenomi-

natorofH(s),weobtain

( )( )( ) ( )

=+ Ļ‰ Ī¶ + Ī¶ āˆ’ +Ļ‰ Ī¶ āˆ’ Ī¶ āˆ’

Ɨ( )1 1

12 2

S sKs

s s sn n

(A.12)

Performingapartial-fractionexpansionforthecasewhereĪ¶ā‰ 1gives

( ) ( )

=Ļ‰ Ī¶ āˆ’

āˆ’

+Ļ‰ Ī¶ + Ī¶ āˆ’+

+Ļ‰ Ī¶ āˆ’ Ī¶ āˆ’( )

2 11

1

1

12 2 2S s

K

s sn n n

(A.13)

KnowingtheLaplacetransformrelation L = āˆ’( ) 1e s aat ,wecaninversetrans-

formEquation(A.13)toobtain

=

Ļ‰ Ī¶ āˆ’āˆ’ +

( ) ( )āˆ’ Ī¶+ Ī¶ āˆ’ Ļ‰ āˆ’ Ī¶āˆ’ Ī¶ āˆ’ Ļ‰( )

2 12

1 12 2

s tK

e en

t tn n (A.14)

In the casewhereĪ¶ >1,Equation (A.14) canbe algebraically rearranged toobtainasinhfunction,andinthecasewhereĪ¶ <1,Equation(A.14)canberear-rangedintoasinefunction.

InthespecialcasewhereĪ¶ =1,Equation(A.12)becomes:

=

+Ļ‰Ć—( )

( )1

2S sKs

s sn (A.15)

This equation can be inverse transformed with the Laplace transform relation

L =āˆ’

( ) 1( )2

tes a

at.

Page 364: Numerical and Analytical Methods with MATLAB for

348ā€ƒ ā—¾ā€ƒ Appendix A

Summarizing,thestepresponseoftheRLCcircuitforallvaluesofĪ¶andzeroinitialconditionsis

=

Ļ‰ āˆ’Ī¶āˆ’ Ī¶ Ļ‰ Ī¶ <

Ī¶ =

Ļ‰ Ī¶ āˆ’Ī¶ āˆ’ Ļ‰ Ī¶ >

āˆ’Ī¶Ļ‰

āˆ’Ī¶Ļ‰

āˆ’Ī¶Ļ‰

( )2 1

sin 1 for 1

for 1

2 1sinh 1 for 1

22

22

s t

Ket

KteKe

t

t

nn

t

t

nn

n

n

n

(A.16)

ThestepresponseisplottedinFigureA.4whereweassumethatĻ‰ = 1000n andĪ¶hasthevalues0.1,1,and10.Notethatfortheunderdampedcase(Ī¶ =0.1),thetran-sientresponsehasanoscillatorycomponent(duetothesineterm)whichdiesoutovertime(duetotheexponentialterm).Intheoverdampedcase(Ī¶ =10),theresponsehasnooscillatorybehaviorandisasumofdecayingexponentials.Thecriticallydampedcase(Ī¶ =1)canbeseentohavethefastestdecaywithoutanyoscillatorycomponent.

NotethatinEquation(A.16),thesinetermintheunderdampedcasehasanā€œeffectiveā€frequencythatisdependentonthedampingfactorandthenaturalfre-quency.Wemaydefinethisā€œdampedfrequencyā€Ļ‰d as

Ļ‰ = āˆ’Ī¶ Ļ‰1 2d n (A.17)

0 0.01 0.02 0.03 0.04 0.050

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8Step Response of 2nd-Order System for Ī¶ =0.1,1,10

Time (seconds)

s(t)

Ī¶ = 0.1

Ī¶ = 1

Ī¶ = 10

Figureā€‚A.4ā€‚ Stepā€‚responseā€‚ofā€‚anā€‚RLCā€‚circuitā€‚forā€‚š›š =ā€‚1000ā€‚rad/sā€‚andā€‚Ī¶ā€‚valuesā€‚ofā€‚0.1,ā€‚1,ā€‚andā€‚10.

Page 365: Numerical and Analytical Methods with MATLAB for

Appendix Aā€ƒ ā—¾ā€ƒ 349

andthusfortheunderdampedcase,thestepresponsemayberewrittenas

=

Ļ‰Ļ‰ Ī¶ <

āˆ’Ī¶Ļ‰

( )2

sin for 1s tKe

tt

dd

n

(A.18)

Becausethedampingfactorcanbehardtomeasuredirectly,thedampedfre-quencycanbeusefulformeasuringĪ¶becauseitmaybeeasilyreadfromtheoscil-latory step response on an oscilloscope screen. If both the damped and naturalfrequenciesareknown,thenfromEquation(A.17),

Ī¶ = āˆ’

Ļ‰Ļ‰

1 d

n

A.3ā€‚ ā€‚Application:ā€‚Signalā€‚ProcessingIntheprevioussection,wederivedthebandpassresponsefor thestandard-formtransferfunctionofEquation(A.10).However,itisalsopossibletoobtainalow-passandhighpassresponsefromanRLCcircuit.FigureA.5showstheseriesRLCcircuitwherethesystemoutputsaretakenasthevoltagesvR,vL ,andvC acrossthethreecircuitelements.Applyingtherelation foravoltagedivider for impedancecircuits,wecanobtain

=+ +

=+ +

1 12

vV

R

R LsCs

RLs

sRLs

LC

R

in (A.19)

=+ +

=+ +

1 1

2

2

vV

Ls

R LsCs

s

sRLs

LC

L

in (A.20)

=+ +

=+ +

1

1

1

12

vV

Cs

R LsCs

LC

sRLs

LC

C

in (A.21)

NotethatEquations(A.19),(A.20),and(A.21)allhavethesamedenominator(andthusthesamenaturalfrequencyanddampingfactor)butdifferentnumera-tors.TheresultingBodemagnitudeplots(FigureA.5)showthattheresistorvolt-agehasabandpass response, the inductorvoltagehasahigh-pass response, andthecapacitorvoltagehasalow-passresponse.Fortheunderdampedcase,allthreeresponseswillhavearesonantpeakatthenaturalfrequency.

Page 366: Numerical and Analytical Methods with MATLAB for

350ā€ƒ ā—¾ā€ƒ Appendix A

100 101 102 103 104 105 106

100 101 102 103 104 105 106

100 101 102 103 104 105 106

10ā€“2

10ā€“1

100

Series RLC Circuit for Ī¶ = 0.1, 1, 10

10ā€“6

10ā€“4

10ā€“2

100

102

10ā€“6

10ā€“4

10ā€“2

100

102

Frequency (rad/sec)

Ī¶ = 0.1

Ī¶ = 0.1

Ī¶ = 0.1

Ī¶ = 10

Ī¶ = 10

Ī¶ = 10

Ī¶ = 1

Ī¶ = 1

Ī¶ = 1

|vR|

|vL|

|vC|

Figureā€‚ A.5ā€‚ Bodeā€‚ plotā€‚ (magnitudeā€‚ portionā€‚ only)ā€‚ showingā€‚ theā€‚ bandpass,ā€‚ high-pass,ā€‚andā€‚low-passā€‚responsesā€‚forā€‚š›š =ā€‚1000ā€‚rad/sā€‚andā€‚Ī¶ā€‚valuesā€‚ofā€‚0.1,ā€‚1,ā€‚andā€‚10.

Page 367: Numerical and Analytical Methods with MATLAB for

Appendix Aā€ƒ ā—¾ā€ƒ 351

A.4ā€‚ ā€‚Application:ā€‚Spring-Dashpotā€‚SystemAproblem frommechanical engineeringwhichmaybemodeledwith anRLCcircuitistheā€œspring-dashpotā€systemconsistingofamass,aspring,andadamper.Acommonhouseholdexampleof a spring-dashpot system is apneumaticdoorclosingmechanism(FigureA.6)wherethedooristhemass,aspringclosesthedoor, and a pneumatic piston is used to adjust the closing speed. If thepistonis incorrectly adjusted, then the door either closes too slowly (overdamped) ortoo rapidlywitha fewbounces (underdamped). If adjusted just right (criticallydamped),thenthedoorclosesasquicklyaspossiblewithoutslammingandwith-outanyoscillation.

Fromphysics,theforceappliedtoamassduetoanattachedspringisdefinedas

= āˆ’springF kx (A.22)

x

Spring with constant k

Piston with dampingcoefficient c

Door withmass m

Door position

Figureā€‚A.6ā€‚ Exampleā€‚ofā€‚aā€‚spring-dashpotā€‚system:ā€‚automaticā€‚door-closingā€‚mechanism.

Page 368: Numerical and Analytical Methods with MATLAB for

352ā€ƒ ā—¾ā€ƒ Appendix A

wherekisthespringconstant(inunitsofnewton/meter)andxisthepositionofthedoorattachedtothespring(inmeters).

The damping force in the pneumatic piston is proportional to the velocity

=xdxdt

ofthedoor:

= āˆ’damperF cx (A.23)

wherecisthedampingcoefficientofthepiston(inunitsofnewton-seconds).Thesumoftheforcesonthedoor = +total spring damperF F F mustobeyNewtonā€™s

secondlaw =total

2

2F md xdt

,andthus

= āˆ’ āˆ’mx kx cx

+ + = 0xcmx

kmx (A.24)

Equation(A.24)hasthesameformasEquation(A.6)whereR =c,L =m,and= 1C k .Thus,wecanmodelthedoor/spring/dampersystemasaseriesRLCcir-

cuit(whichwehavealreadysolvedmathematically)wherethepistoncorrespondstotheresistor, themassof thedoorcorrespondstothe inductor,andthespringcorrespondstothecapacitor.

Reference 1. Johnson,D.E.,Hilburn,J.L.,andJohnson,J.R.,Basic Electric Circuit Analysis, 4th ed.,

PrenticeHall,1990.

Page 369: Numerical and Analytical Methods with MATLAB for

353

Appendixā€‚B:ā€‚Specialā€‚Charactersā€‚inā€‚MATLABĀ®ā€‚Plots

MATLABĀ®allowstheuseofGreekandspecialcharactersinitsplotheadingsandlabels.ThemethodfordoingthisbasedontheTeXformattinglanguage[1]andissummarizedinthisappendix.

MATLABprovidesthefunctionstitle,xlabel,ylabel,andtextforadd-inglabelstoplots.TheselabelscanincludeGreekandspecialcharactersbyapplyingthecharactersequencesasshowninTableB.1.Thesesequencesallbeginwiththebackslashcharacter(\)andcanbeembeddedinanytextstringargumenttotitle,xlabel,ylabel,andtext.Subscriptsandsuperscriptsmayalsobeappliedbyusingthe_and^operators.Forexample,thesequenceVoiswrittenasV _ o,and106iswrittenas10 6.Ifthesubscriptorsuperscriptismultiplecharacters,thenusecurlybracestodelimitthestringtobesubscripted,forexample,VoutisgeneratedwithV _ out.

Exampleā€‚B.1

The following MATLAB script shows how to use special characters in a plot.

%Example_B_1.m%Thisscriptshowsexampleusageofspecialcharactersin%MATLABplots.%Plota1MHzsinewaveovertheinterval0<t<2microsect=0:2e-8:2e-6;fo=1e6;xout=sin(2*pi*fo*t);plot(t*1e6,xout);title('Plotofsin(2\pif_ot)forf_o=10^6Hz');xlabel('time(\museconds)');ylabel('x_out(t)');text(1.5,0.3,'\omega=2\pi\timesf_o');---------------------------------------------------------------------------

TheresultingplotisshowninFigureB.1.

Page 370: Numerical and Analytical Methods with MATLAB for

354ā€ƒ ā—¾ā€ƒ Appendix B

Tableā€‚B.1ā€‚ Specialā€‚Symbolsā€‚forā€‚Useā€‚inā€‚MATLABā€‚Plots

Character Sequence Symbol

Character Sequence Symbol

CharacterSequence Symbol

\alpha Ī± \upsilon Ļ… \sim āˆ¼

\beta Ī² \phi Ļ• \leq ā‰ 

\gamma Ī³ \chi Ļ‡ \infty āˆž

\delta Ī“ \psi Ļˆ \clubsuit ā™£

\epsilon Īµ \omega Ļ‰ \diamondsuit ā™¦

\zeta Ī¶ \Gamma Ī“ \heartsuit ā™„

\eta Ī· \Delta Ī” \spadesuit ā™ 

\theta Īø \Theta Ī˜ \leftrightarrow ā†”

\vartheta Ļ‘ \Lambda Ī› \leftarrow ā†

\iota Ī¹ \Xi Īž \uparrow ā†‘

\kappa Īŗ \Pi Ī  \rightarrow ā†’

\lambda Ī» \Sigma Ī£ \downarrow ā†“

\mu Ī¼ \Upsilon Ī„ \circ Ā°

\nu Ī½ \Phi Ī¦ \pm Ā±

\xi Ī¾ \Psi ĪØ \geq ā‰„

\pi Ļ€ \Omega Ī© \propto āˆ

\rho Ļ \forall āˆ€ \partial āˆ‚

\sigma Ļƒ \exists āˆƒ \bullet ā€¢

\varsigma Ļ‚ \ni āˆ \div Ć·

\tau Ļ„ \cong ā‰… \neq ā‰ 

\equiv ā‰” \approx ā‰ˆ \aleph ā„µ

\Im ā„‘ \Re ā„œ \wp ā„˜

\otimes āŠ— \oplus āŠ• \oslash āˆ…

\cap āˆ© \cup āˆŖ \supseteq āŠ‡

\supset āŠƒ \subseteq āŠ† \subset āŠ‚

\int āˆ« \in āˆˆ \o āˆ˜

Page 371: Numerical and Analytical Methods with MATLAB for

Appendix Bā€ƒ ā—¾ā€ƒ 355

Reference 1. Knuth,D.E.,The TeXbook,AddisonWesley,Boston,1984.

0 0.5 1 1.5 2ā€“1

ā€“0.8

ā€“0.6

ā€“0.4

ā€“0.2

0

0.2

0.4

0.6

0.8

1Plot of sin(2Ļ€ fot) for fo = 106 Hz

Time (Āµseconds)

x out

(t)

Ļ‰ = 2Ļ€ Ɨ fo

Figureā€‚B.1ā€‚ Exampleā€‚usageā€‚ofā€‚Greekā€‚letters,ā€‚specialā€‚characters,ā€‚subscripts,ā€‚andā€‚superscriptsā€‚inā€‚aā€‚MATLABā€‚plot.

Tableā€‚B.1ā€‚ Specialā€‚Symbolsā€‚forā€‚Useā€‚inā€‚MATLABā€‚Plotsā€‚(Continued)

Character Sequence Symbol

Character Sequence Symbol

CharacterSequence Symbol

\rfloor āŒ‹ \lceil āŒˆ \nabla āˆ‡

\lfloor āŒŠ \cdot ā‹… \ldots ā‹Æ

\perp āŠ„ \neg Ā¬ \prime ā€²

\wedge āˆ§ \times Ɨ \0 āˆ…

\rceil āŒ‰ \surd āˆš \mid

\vee āˆØ \varpi Ļ– \copyright Ā©

\langle \rangle

Page 372: Numerical and Analytical Methods with MATLAB for
Page 373: Numerical and Analytical Methods with MATLAB for

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

William Bober ā€¢ Andrew Stevens

Bober ā€¢ Stevens

ISBN: 978-1-4398-5429-7

9 781439 854297

9 0 0 0 0

K12515

Electrical Engineering

Combining academic and practical approaches to this important topic, Numerical and Analytical Methods with MATLABĀ® for Electrical Engineersis the ideal resource for electrical and computer engineering students. Based on a previous edition that was geared toward mechanical engineering students, this book expands many of the concepts presented in that book and replaces the original projects with new ones intended specifically for electrical engineering students.

This book includes:

ā€¢ An introduction to the MATLABĀ® programming environment ā€¢ Mathematical techniques for matrix algebra, root finding,

integration, and differential equationsā€¢ More advanced topics, including transform methods, signal

processing, curve fitting, and optimization ā€¢ An introduction to the MATLABĀ® graphical design environment,

SimulinkĀ®

Exploring the numerical methods that electrical engineers use for design analysis and testing, this book comprises standalone chapters outlining a course that also introduces students to computational methods and pro-gramming skills, using MATLABĀ® as the programming environment. Helping engineering students to develop a feel for structural programmingā€”not just button-pushing with a software programā€”the illustrative examples and extensive assignments in this resource enable them to develop the necessary skills and then apply them to practical electrical engineering problems and cases.

Numerical and Analytical Methods with MATLABĀ® for Electrical Engineers

Numerical and Analytical M

ethods with M

ATLABĀ® for Electrical Engineers

K12515_Cover_mech.indd 1 7/27/12 9:01 AM