Upload
others
View
19
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