Upload
others
View
14
Download
1
Embed Size (px)
Citation preview
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
Numerical and Analytical Methods with MATLAB® for Electrical Engineers
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
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
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
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
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
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
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
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.
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
xi
Acknowledgments
WewishtothankJonathanPlantofCRCPressforhisconfidenceandencourage-mentinwritingthistextbook.Inaddition,wewouldliketoexpressthankstoChrisLeGoffforhelpinpreparingtheartworkandtoPatrickFarrellandMichaelRohanfortheirtechnicalexpertise.
WealsowishtoexpressourdeepgratitudetoSelmaBober,TheresaStevens,andEmmaStevensfortoleratingthemanyhourswespentonthepreparationofthemanuscript,thetimethatotherwisewouldhavebeendevotedtoourfamilies.
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.
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).
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).
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.
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
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.
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
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.)
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).
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.)
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.)
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.)
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.)
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.)
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)
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.
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
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)
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)
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.
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]
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);
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);
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);
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.)
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
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
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
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;
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;
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);------------------------------------------------------------
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).
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.)
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);--------------------------------------------------------
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
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)
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');
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
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
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.
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
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.
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.
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);
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');-------------------------------------------------------------------------
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);-----------------------------------------------------------
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,
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.
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)
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'];
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
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------------------------------------------------------------
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.
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
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)
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
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.
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.)
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.)
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.
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)
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)
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 π
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
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
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°.
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.
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.
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
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)
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.
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).
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.
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
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.
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.
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.
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.
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
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.
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:
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)
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.
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);
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.
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
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)
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
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.
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
,
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
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.
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)
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
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 .
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
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
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,
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
,
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.
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.
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
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);
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
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
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.
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.
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.
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
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.
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.
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.
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.
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)
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.
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
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)
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
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)
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.
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
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.
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.)
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)
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.
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.
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.
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.
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).
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).
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
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.
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
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.
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.
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
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
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 .
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.
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
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
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
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.
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θ.
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.
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
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.
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)
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.
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 .
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.
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.
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.
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.
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).
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.
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.
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.
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.
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 .
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.
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
.
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
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.
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.
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.
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--------------------------------------------------------------------------
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.
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;
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.
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
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.
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.
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.
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;
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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)
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));
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.
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.
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.
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.
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.
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.
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.
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)
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.
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.
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
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.
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)
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=
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 )
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)
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
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.
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.
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).
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)
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)
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=+
++
−+
++
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.
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
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= []
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
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.
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
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
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.
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.
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
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).
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)
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.
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)
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.
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.
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.
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.
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.
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.
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
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)
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
−+
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)
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 >−
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−
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
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)
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.
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)
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.
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.
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.
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.
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)');
-------------------------------------------------------------------
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.
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.
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.
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
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
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.
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].
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
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.
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).
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.
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.
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.
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.
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.
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.
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
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
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
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.
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).
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.
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.
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)
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) .
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.
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… .
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
∑ ∑∑= − −= ==
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.
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).
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)
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.)
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;
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.
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.
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
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.
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.
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.
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
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.
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.
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.
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
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 ).
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.)
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.
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.
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.
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
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;
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
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.
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.
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)
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.
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.
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
= π + π
= π
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
+ + + =
+ + + =
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.
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.
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
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=[];
-----------------------------------------------------------------------
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);
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
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
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.
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
=π
= π +
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
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
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
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
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.
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.
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).
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.)
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.
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.
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).
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.
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).
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.
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.
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.
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.
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.
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.
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)
.
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.
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.
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
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)
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.
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.
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
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.
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)
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.
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.
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.
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.
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.
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.
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.
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 ∘
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
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