https://ebookmass.com/product/difference-matrices-for-odeand-pde-a-matlab-companion-john-m-neuberger/
Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
America's Scientific Treasures: A Travel Companion 2nd Edition Stephen M. Cohen
https://ebookmass.com/product/americas-scientific-treasures-a-travelcompanion-2nd-edition-stephen-m-cohen/
ebookmass.com
Destination C1 & C2 : grammar & vocabulary with answer key 18 [printing]. Edition Malcolm Mann
https://ebookmass.com/product/destination-c1-c2-grammar-vocabularywith-answer-key-18-printing-edition-malcolm-mann/
ebookmass.com
(eTextbook PDF) for Privilege, Power, and Difference 3rd Edition
https://ebookmass.com/product/etextbook-pdf-for-privilege-power-anddifference-3rd-edition/
ebookmass.com
World Criminal Justice Systems 9th Edition https://ebookmass.com/product/world-criminal-justice-systems-9thedition/
ebookmass.com
Death : Perspectives from the Philosophy of Biology 1st Edition Philippe Huneman
https://ebookmass.com/product/death-perspectives-from-the-philosophyof-biology-1st-edition-philippe-huneman/
ebookmass.com
The Constitutional Theory of the Federation and the European Union Signe Rehling Larsen
https://ebookmass.com/product/the-constitutional-theory-of-thefederation-and-the-european-union-signe-rehling-larsen/
ebookmass.com
Being Good in a World of Need Larry S. Temkin
https://ebookmass.com/product/being-good-in-a-world-of-need-larry-stemkin-2/
ebookmass.com
Entrepreneurship: The Practice and Mindset (NULL)
https://ebookmass.com/product/entrepreneurship-the-practice-andmindset-null/
ebookmass.com
Our Love Affair with Drugs: The History, the Science, the Politics 1st Edition Jerrold Winter
https://ebookmass.com/product/our-love-affair-with-drugs-the-historythe-science-the-politics-1st-edition-jerrold-winter/
ebookmass.com
India's Public Health Care Delivery: Policies for Universal Health Care 1st Edition Sanjeev Kelkar
https://ebookmass.com/product/indias-public-health-care-deliverypolicies-for-universal-health-care-1st-edition-sanjeev-kelkar/
ebookmass.com
John M. Neuberger
Difference Matrices for ODE and PDE A MATLAB® Companion DifferenceMatricesforODEandPDE JohnM.Neuberger
DifferenceMatrices forODEandPDE JohnM.Neuberger DepartmentofMathematicsandStatistics
NorthernArizonaUniversity Flagstaff,AZ,USA
ISBN978-3-031-11999-6ISBN978-3-031-12000-8(eBook) https://doi.org/10.1007/978-3-031-12000-8
MATLABisaregisteredtrademarkofTheMathWorks,Inc.,Natick,MA,USA
MathematicsSubjectClassification:65-01,35-01,34-01,65L,65M,65M06,65M20,65N,65N06, 65N25,35F,35G,35A24,35J20
© SpringerNatureSwitzerlandAG2023
Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpart ofthematerialisconcerned,specificallytherightsoftranslation,reprinting,reuseofillustrations, recitation,broadcasting,reproductiononmicrofilmsorinanyotherphysicalway,andtransmission orinformationstorageandretrieval,electronicadaptation,computersoftware,orbysimilarordissimilar methodologynowknownorhereafterdeveloped.
Theuseofgeneraldescriptivenames,registerednames,trademarks,servicemarks,etc.inthis publicationdoesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfrom therelevantprotectivelawsandregulationsandthereforefreeforgeneraluse.
Thepublisher,theauthors,andtheeditorsaresafetoassumethattheadviceandinformationinthis bookarebelievedtobetrueandaccurateatthedateofpublication.Neitherthepublishernorthe authorsortheeditorsgiveawarranty,expressedorimplied,withrespecttothematerialcontained hereinorforanyerrorsoromissionsthatmayhavebeenmade.Thepublisherremainsneutralwithregard tojurisdictionalclaimsinpublishedmapsandinstitutionalaffiliations.
ThisSpringerimprintispublishedbytheregisteredcompanySpringerNatureSwitzerlandAG Theregisteredcompanyaddressis:Gewerbestrasse11,6330Cham,Switzerland
Preface Thistextwillbeusefulforthefourdifferentaudienceslistedbelow.Itisexpected thatallreaderswillhaveknowledgeofbasiccalculus,linearalgebra,andordinary differentialequations,andthatthesuccessfulstudentwilleitheralreadyknow elementarypartialdifferentialequations,orbeconcurrentlylearningthatsubject. Thematerialisintendedtobeaccessibletothosewithout expertise inMATLAB®, althoughalittlepriorexperiencewithprogrammingisprobablyrequired.
1.Thistextservesasasupplementforthestudentinanintroductorypartialdifferentialequationscourse.Aselectionoftheincludedexercisescanbeassigned asprojectsthroughoutthesemester.Throughtheuseofthistext,thestudentwill developtheskillstorunsimulationscorrespondingtotheprimarilytheoretical coursematerialcoveredbytheinstructor.
2.Thesenotesworkwellasastandalonegraduatecoursetextinintroductory scientificcomputingforpartialdifferentialequations.Withprerequisite knowledgeofordinaryandpartialdifferentialequationsandelementary numericalanalysis,mostofthematerialcanbecoveredandmanyofthe exercisesassignedinaone-semestercourse.Someoftheharderexercisesmake substantialprojects,andrelatetotopicsfromtheothergraduatemathematics coursesgraduatestudentstypicallytake,e.g.,differentialequationsandtopicsin nonlinearfunctionalanalysis.
3.Establishedresearchersintheoreticalpartialdifferentialequationsmay find thesenotesusefulaswell,particularlyasanintroductoryguidefortheirresearch students.ThoseunfamiliarwithMATLABcanusetheincludedmaterialasa referenceinquicklydevelopingtheirownapplicationsinthatlanguage. Amathematicianwhoisnewtothepracticalimplementationofmethodsfor scientificcomputationingeneralcanwithrelativeease,byworkingthrougha selectionofexercises,learnhowtoimplementandexecutenumericalsimulationsofdifferentialequationsinMATLAB.Thesenotescanserveasapractical guideinindependentstudy,undergraduateorgraduateresearchexperiences,or forhelpsimulatingsolutionstospeci ficthesis-ordissertation-related
experiments.Theauthorhopesthattheeaseandbrevitywithwhichthenotes providesolutionstofairlysignificantproblemswillserveasinspiration.
4.Thetextcanserveasasupplementfortheinstructorteachinganycoursein differentialequations.Manyoftheexamplescanbeeasilyimplementedandthe resultingsimulationdemonstratedbytheinstructor.Ifthecoursehasa numericalcomponent,afewexercisesofsuitabledifficultycanbeassignedas studentprojects.PracticalassistanceinimplementingalgorithmsinMATLAB canbefoundinthistext.
ScientistandengineershavevalidmotivationstobecomeproficientatimplementingnumericalalgorithmsforsolvingPDE.Thetext’semphasisonenforcing boundaryconditions,eigenfunctions,andgeneralregionswillbeusefulasan introductiontotheiradvancedapplications.Forthemathematician,accomplishedor student,amorepowerfulbenefitcanbethetangible,visualrealizationoftheobjects ofcalculus,differentialequations,andlinearalgebra.Thehigh-levelprogramsare developedbythereaderfromearlierprogramsandshortfragmentsofrelatable code.Theresultingsimulationsaredemonstrationsofthepropertiesoftheunderlyingmathematicalobjects,wherevectorsrepresentfunctions,matrixoperations representdifferentiationandintegration,andcalculationssuchassolvinglinear systemsor fi ndingeigenvaluesareeasilyaccomplishedwithonelineofcode.Even withoutmuchpriorknowledgeofprogrammingorMATLAB,byworkingthrough aselectionofexercisesinthistext,thereaderwillbeabletocreateworking programsthatsimulatemanyoftheclassicproblemsfromPDE,whilegainingan understandingoftheunderlyingfundamentalmathematicalprinciples.
Theapproachofthetextisto fi rstreviewMATLABandasmallselectionof techniquesfromelementarynumericalanalysis,andthenintroducedifference matricesinthecontextofordinarydifferentialequations.Wethenapplytheseideas toPDE,includingtopicsfromtheheat,wave,andLaplaceequations,eigenvalue problems,andsemilinearboundaryvalueproblems.Weenforceboundaryconditionsonregionsincludingtheinterval,square,disk,andcube,andmoregeneral domains.Wepushthegeneralnotionthatlinearproblemscanbeexpressedasa singlelinearsystem,whilemanynonlinearproblemscanbesolvedviaNewton’s method.
Flagstaff,USAJohnM.Neuberger
Acknowledgements Iwould firstandforemostliketoacknowledgemyfatherJ.W.Neuberger.He taughtmemuchofwhatIknowaboutdifferentialequationsandthenumerical solutionofthem.Hisbeliefinmypedagogicalapproachandthepracticalusefulnessofmycoursenoteswasmymainmotivationinpublishingthem.
IalsowouldliketothankmyPh.D.advisorAlfonsoCastrowhointroducedme tononlinearfunctionalanalysis,particularlyasitpertainstosemilinearelliptic boundaryvalueproblems.Chapter 5 contentofthistextreflectsasmallsliceofmy lifetimepursuitstounderstandandcomputationallysimulatetheequationsofthat subject.
Ihavebeenextremelyluckyinhavingawonderfullysupportivefamily.Mywife Dinahasbeenthemainsourceofinspirationovermycareerasaprofessorof mathematics.MysonNickhasaninterestinmathematicsaswell,andhasbeen insistentthatIrefi nethenotessothatotherscouldusethem.
Iwouldalsoliketothankmy20-plusyearsofundergraduateandgraduate partialdifferentialequationsandnumericalanalysisstudents.Theirfeedbackwas invaluableintheprocessofdevelopingandrefiningmynotes.Themuch-improved textcontainsnumerousclari ficationsandhintsasadirectresultoftheirsuggestions, andtheexercisesaremorerobustandcomplete,thankstotheircountlesshoursof codingandgrindingoutprojectreports.IlearnedafewMATLAB® tricksfrom themtoo.AspecialthanksgoestomyformerandcurrentstudentsTylerDiggans, RyanKelly,andIanWilliams,whoeachtookaturnatproofreading,andmade somevaluableeditorialsuggestionsfromthestudentperspective.
andtheStudentExercises
1.2.3ReproducingCodesandExercises
1.2.4GuidelinestotheHomeworkExercises
forloop,eigs,andsort
2.2.1TheShootingMethodforODEBVP
2.2.2ComparisonofApproximateSolutionstoExact
2.2.3MATLAB®:Ones,Zeros,the ‘:’ Iterator,the@ SyntaxforDefi ningInlineFunctions,Subfunctions 23
2.2.4RowsVersusColumnsPartI,DiagnosingDimension andSizeErrors
2.3.1HigherOrderDifferencesandSymbolicComputation
2.3.2MATLAB®:kron,spdiags, ‘backslash’ (mldivide),tic, andtoc ....................................
2.4.1MATLAB®:if,else,while,fprintf,meshgrid,surf, reshape, fi nd,singleindexing,androwsversus columnsPartII ..............................
3.4EnforcingZeroDirichlet,ZeroNeumann,andPeriodic BoundaryConditionsUsingEitherPointorCellGrid
4.5.4TheMethodofLines
4.6.1TheMethodofLines
4.6.3BlockMatrixSystemsandD
4.8.3AccurateEigenvaluesoftheLaplacianonDisk, Annulus,andSections
4.8.4TheLaplace–BeltramiOperatoronaSpherical
5AdvancedTopicsinSemilinearEllipticBVP
5.1BranchFollowingandBifurcationDetection
5.1.1TheTangentNewtonMethodforBranchFollowing
5.1.2TheSecantMethodforBifurcationDetection
5.1.3SecondaryBifurcationsandBranchSwitching
5.2MountainPassandModi fiedMountainPassAlgorithms forSemilinearBVP
5.2.1TheMPA
5.2.2TheMMPA
5.3The
Acronyms Somefrequentlyusedacronyms.
ODEOrdinarydifferentialequation,ordinarydifferentialequations.
PDEPartialdifferentialequation,partialdifferentialequations.
BCBoundarycondition.
IVPInitialvalueproblem.
BVPBoundaryvalueproblem.
0-DBCZeroDirichletboundarycondition,i.e., u ¼ 0ontheboundary. ForODE,thisis yaðÞ¼ 0and/or ybðÞ¼ 0.
0-NBC ZeroNeumannboundarycondition,i.e., @ u @ g ¼ 0ontheboundary,forthe outwardunitnormalvector g.ForODE,thisis y0 a ðÞ¼ 0and/or y0 b ðÞ¼ 0.
MOLMethodoflines.ItreferstodiscretizingaPDEwithdifferencesinallbut onevariable,usuallytime,andthensolvingtheresultingsystemofODE byanyconvenientmeans.
RHSGeneraltermfortheRHSofanequation,mostoftenaknownfunctionor vectordefiningalinearsystem.
LHSGeneraltermfortheLHSofanequation.
RK Runge–Kutta,an OððDxÞ4 Þ methodforsolving first-orderIVP.
SOVSeparationofvariables;itreferstotwodistincttechniques:
1.ODE,equation ! f ðyðxÞÞy0 ðxÞ¼ gðxÞ,hencebothsidescanbe integratedwithrespectto x,yieldinganimplicitsolution
F ðyÞ¼ GðxÞþ c
2.PDE,forlinearequationthesubstitution uðx1 ; x2 Þ¼ pðx1 Þqðx2 Þ gives
F ðpðx1 ÞÞ¼ c ¼ Gðqðx2 ÞÞ,whenceBCcanbeusedtoconvertthe sidewithboundaryvaluestoaneigenvalueproblem,andthensolve theothersideasafamilyparameterizedbytheeigenvaluestogeta generalsolution.
HWHomework.Anecessarypartofthelearningprocess.
CCNUsuallyreferstotheminimal-energysign-changingexactly-once solutionto Du þ fuðÞ¼ 0,foravarietyofassumptionson f including superlinearity.Thelettersrefertotheauthor ’snamesinthearticle[24].
MPAMountainpassalgorithm,celebratedresultby[25].
MMPAModifi edmountainpassalgorithm.ItextendstheMPAto findtheCCN solution.
Chapter1 Introduction Summary Inthischapter,wesummarizethekeyfeaturesandcontentofthetext. WeexplainthechoiceofMATLAB® asaprogramminglanguage,andthenbriefly emphasizetheusefulnessoftheMATLABdebugger.Wediscusstheprocessof convertingcodefragmentsandhintsfromthetextintoworkingprograms,andgive somesuggestionstoinstructorsontheassignmentofthehomeworkproblemswhich requirethoseworkingprograms.Wegivemoredetailconcerningeachofthespecific includedtopics.
1.1ASummaryoftheDifferentialEquationsWeWill Consider Differentialequationsisavastsubject.Weconcentratehereprimarilyonthemost fundamentalequationsencounteredinintroductoryODEandPDEcourses.Many oftheincludedcomputationalhomeworkexercisescorrespondtotypicalanalytical homeworkexercisesfromthosecourses.
Inparticular,forODEwepresentalgorithmsforapproximatingsolutionstofirstandsecond-orderlinearandnonlinearequationsandsystemsofequations,forinitial andboundaryvalueproblems.Homeworkexercisesincludeexamplesrequiringthe separationofvariables,integratingfactors,constantcoefficientsecond-ordertheory, andotherstandardtechniquesfromanintroductorycourseinODE.Wediscussthe enforcementofDirichlet,Neumann,andperiodicboundaryconditions.Eigenvalue problemsandeigenfunctionexpansionsarefeatured.
ForPDE,weemphasizetheeigenfunctionsoftheLaplacian,Laplace’sequation, theheatandwaveequations,andnonlinearellipticproblems.Weconsidertheclassic regionsofthesquare,disk,andannulus,aswellasothermoregeneralregions,with variousIC/BC.Byavarietyofmethods,weshowhowtonumericallysimulatethe separationofvariablesolutionstotypicalhomeworkexercisesfromanintroductory PDEcourse.Forcompleteness,weincludeanexamplecodeforfirst-orderPDE andthemethodofcharacteristics.Includedareasmallselectionofmoreadvanced equations,intendedprimarilytodemonstratethewiderangeofpossibleapplications
©SpringerNatureSwitzerlandAG2023
J.M.Neuberger, DifferenceMatricesforODEandPDE, https://doi.org/10.1007/978-3-031-12000-8_1
forthetext’smethods.Inparticular,weincludesomeexperimentswithTricomi’s equation,bifurcationforsemilinearellipticBVP,andeigenvaluesofthe p -Laplacian.
1.2TheUseofMATLAB® andtheStudentExercises Thegoalofthesenotesistomakeeasilyaccessiblethegeneralabilityofthereader tousefirst-andseconddifferencematricestosetupandsolvelinearandnonlinear systemswhichapproximateordinaryandpartialdifferentialequations.Thescope ofdifferentialequationsisimmense,andsothisbriefexpositionwillonlygivethe detailsforthemostfundamentaltypesofclassicproblemslistedabove.Itisour beliefthattheeasewithwhichtheincludedproblemsaresolvedwillbeencouraging tothereaderwithmorecomplicatedapplicationsinmind,andthatthedeveloped arsenalofMATLABcommandsandtechniqueswillbeusefulintheirattemptsto followthroughwiththeirownsuccessfulinvestigations.
Thevalueofthepresentedmethodologyforsolvingthestatedtypesofproblemsisindependentofthechoiceofprogrammingplatform.Generally,wesolve lineardifferentialequationswithasinglesparsematrixlinearsystemsolve,andwe solvenonlineardifferentialequationswithNewton’smethod.TheincludedalgorithmscouldcertainlybeimplementedinlanguagesotherthanMATLAB,butwhy wouldyouwantto?ThedevelopedMATLABcodesareshort,easilyrelatedtothe underlyingequationsfrommathematics,andtheheavyliftingisgenerallydoneby built-incompiledcommands,e.g.,theindispensable‘\’,MATLAB’sbuilt-inefficientlinearsolver, eigs,itsnearlyunbeatableeigenvaluesolver,and ode45,oneof itsgenericordinarydifferentialequation(ODE)systemsolvers.Onewouldhaveto workveryhardtoimproveontheoverallspeedoranyotherfacetsofthesebuilt-in functions’implementationsinanothersetting.Thesparse-matrixcapabilityofMATLABmeansthatfairlyhugeproblemscanbeattackedwithapersonalcomputer,and thatwithnottoomuchmoresophistication(butbeyondthescopeofthisdocument), implementationsonsupercomputingclusterscouldbeeffectivelyusedtoattackthe mostseriousandcomputing-intensiveofapplications.Inallfairness,itwouldnot betoohardtoimplementthealgorithmspresentedherein Mathematica,andthe experiencedC/C++programmerwouldnotfinditdifficulttobuildalibraryoftools, forexamplefrom Netlib [21]. Mathematica isprobablyabetterchoice,infact,for intensivesymboliccomputationsthatmightbeneededforpre-andpost-processingin morecomplicatedapplications.Theintermediateprogrammerwouldprobablyfind itnottoodifficulttotranslatethecodeincludedinthistextto Sage. Python could certainlybeused,oncesomeperhapsmissinghigh-levelmathematicalfunctionality builtintoMATLABwasotherwiseaccessedviaappropriatelibrariesoffunctions. So,manylanguageswouldprovideafineplatformforwritingshort,easyprograms tosolve,byourmethods,theexampleproblemsincludedinthisdocument,butwe arguethatnoneoftheseotherchoiceseasilyyieldsignificantperformanceincreases orareeasiertounderstandorimplementthanMATLAB.Asaneducatorwhoregularlyteachessectionsofnumericalanalysisandotherappliedmathematicscourses
withacomputationalcomponenttoengineeringandsciencemajors,theauthorfinds thatthisstudentpopulationiscurrentlylikelytoalreadyknowMATLABandtobe usingitintheirothercourses,andthosethatdon’talreadyknowitseemtopickit upprettyquickly.
Chapter 2 containsseveralentireMATLABprogramswhichdemonstratesome usefulcodingtechniquesonsomefamiliarproblemsfromcalculusandordinarydifferentialequations.Theexercisesaskthereadertomodifyandtesttheseprograms. Chapter 3 startswithacompleteprogram,cutintosegmentsandpresentedinbetween mathematicaldefinitionsandexplanationsofthealgorithmandsyntax,andChaps. 4 and 5 extendtheideastoPDE.EachsubsequentsectionincludesenoughMATLABcodefragmentssuchthatitshouldbepossiblefortherelativelyinexperienced programmertoputtogetherworkingprogramsdemonstratingtherelevantmethods. Completeprogramsareonlyoccasionallypresented.Eachsectioncomeswithafew exercisesforthereadertofurthertheirskills,suggestingtoapply,generalize,orcombinepresentedideastosolverelatedproblemsorperformdifferentcomparisons.A littlefamiliaritywithintroductorynumericalanalysiswouldcertainlybehelpful,but theattempthasbeenmadetomaketheinformationfairlyself-containedinthatbrief descriptionsofsomewell-knownandimportantelementarynumericalmethodsare included.
1.2.1UsingMATLAB® ’sDebugger Itisouropinionthatthedebuggerisanessentialtoolfordevelopingandunderstandingprograms,andthatitshouldbeusedearlyandoftenbythebeginnerandexpert alike.Gettingared‘dimensionmismatch’error?Clickonthehyphentotherightof alinenumberontheleftsideoftheeditor.Ifaredbulletappears,theprogramwill stopthefirsttimeithitsthatline.Theninspectthevariablesinquestion.Placingyour cursoroverthemwillatleastrevealtheirdimension.Perhapsthematrixshouldbe transposedbeforetheoperation?Ifthedatainvolvedisnottoohuge,youcanopen avariableeditorandinspecteachelement.Right-clickingonthebreakpointisone waytoselecttheconditionaloption,e.g., i==23 willstoponthelineif i = 23.The usercandescendintoasubfunctionforinspectionofthatfunction’slocalvariables, orskipoverthefunctiontothenextlineintheparentfunction.Clearbreakpoints, setnewones,continuetothenext,checkingthedimensionandifneedbecontents ofanyvariableswhosevalueisinquestion.
YoucanusethedebuggertolearnMATLAB.Forasmall n value,runanexample program,steppingthroughthecodelinebyline.Checksomecalculationsbyhand andcompare.Whenaloopgetstedious,putabreakpointafteritoruseaconditional breakpointtoskipaheadintheaction.MATLAB’swayofgeneratinggraphicscan beconfusingtotheuninitiated.Putabreakpointonsomeplotlinesandinspect theindependentanddependentvariables.Wheneveraprogramispausedinthe debugger,thecommandlinecanbeusedtoexaminecontentsorperformsmall checkingcalculations.The‘executeselection’featurecanoftenbeusedatthattime
tomakeasmallerportionofthecoderungivenpreviouslystoredvaluesofrelevant variablesandfunctions.
Thefirsttimeoneattemptstoexecuteaprogramwithasignificantnumberof complicated,newlinesofcode,oneexpectscodingerrors.Agoodapproachisto stepthroughtheprograminthedebuggereitherlinebyline,orsectionbysection, generallyinspectingtheinputsandoutputsofeachlineorrelatedgroupoflines, e.g.,aloop,verifyingthatdimensionsandvaluesappearconsistentwiththatpredicted.Minormistakescanbecorrectedastheyareencountered,whileonemay needtopausetoconsiderthebestfixfordeepererrors.Reallearningcanoccurwhen errorsareencounteredthatforcethecodertodetermineifthestepsofthealgorithm andcorrespondingvariablesareproperlyrepresentingtheunderlyingmathematical constructs.
1.2.2LineNumberinginMATLAB® Examples Whereitmakessense,theauthorincludeslinenumberstotheleftoftheincluded linesofMATLABcode.Inparticular,whenbreakingaprogramorprogramfragment intoblocks,resumingconsecutivelinenumberingisused.Manynewexamplesonly requireminormodificationsofpreviouslydevelopedMATLABprograms.Inthat case,thelinenumberingmaystartatsomeintegerlargerthanone,indicatingthat somelinesaremissingandpresumedtobeunderstoodbasedonpriordiscussion.Of coursedifferingstyles,andaddingcomments,blanklines,options,extraloops,or moredescriptiveoutputwillinpracticechangethelinenumberingandformatofthe code.Ourapproachinthisdocumentissomewhatminimalistic,generallymakingan efforttosetupandsolvetheproblemswithafewextrabellsandwhistles.Ifcutting andpastingfromapdfofthistext,itmaybenecessarytodeletethelinenumbers wherepresent;taketheopportunitytoreflectonthepurposeofeachlineasyou removeeachlinenumber.IfyouaretypingtheexampleprogramsintotheMATLAB editorbyhand,itiswisetodosoablockofafewlinesatatime,executingorbetter yetsteppingthroughviathedebuggerandverifyingtheresultingstateofthepartial programbeforeaddinganothersmallblock.
1.2.3ReproducingCodesandExercises Ifthisdocumentisbeingusedasatextbook,theauthorhopesthatthestudentwill writetheirownMATLABprogramstorecreatetheresultsfrommanyoftheincluded examples.Theentireprogramisincludedinthetextforsomeoftheexamples,and enoughcodefragmentsandhintsareprovidedsuchthatitshouldbepossiblein subsequentsectionstoreproducetheresultswithoutexternalresources.Thereader mightthinkofitasabitofagametoseeiftheycandosowithlinenumbering thatagreeswiththatprovidedintheincludedcodefragments,i.e.,canyouinitialize
anddefinethevariousscalars,vectors,andsparsematricesinfivelinesastheauthor did?Theincludedexercisesareforthemostpartintendedtobefairlyreasonable extensionsorcombinationsofthepresentedideas,againdoable withoutoutside resources. 1 TheprogressionofexamplesandexercisesisdesignedtoteachMATLAB anddemonstratetheutilityofdifferencematrices,ateachstepmovingthereader alittleclosertowardbeingabletoindependentlyinvestigatedifferentialequations, perhapsequationsoftheirownchoosingwhicharemorecomplicatedandbeyond thescopeofthistext.
Somesectionscontainshortformallystatedexamples,typicallyinvolvingpenciland-papercalculationstoapproximateasolutionforsomereasonablediscretization orasmallnumberofiterations,andtocomputeforcomparisonthecorresponding exactsolutionbysomeknowntechnique.Someoftheun-starred(non-programming) exercisesaresimilartotheseexamples,andmaybeusefulinpreparingforin-class assessments.;-)
1.2.4GuidelinestotheHomeworkExercises Un-starredproblems,problemswhicharenotindicatedbyoneormore‘*’,generally donotrequireprogramming.Theseproblemsarenotintendedforprogramming HWassignments.Theymaybeusefulinthepreparationforin-classassessments. Typically,theseproblemsrequireasmallpencil-and-papercalculation,e.g.,forthree divisionsandoneiteration,orinvolveatheoreticalderivation.Ifworkedoutbyhand priortothewritingandsubsequentdebuggingofMATLABcode,theymayserveto aidinthesuccessfulimplementationandunderstandingoftheunderlyingalgorithms.
StarredproblemstypicallyrequirewritingMATLABcodeinordertoanswerthe questions.Problemsindicatedwithasingle‘*’aregenerallytheeasiestandhave shorterexpectedstudentsolutiontimes.Someoftheseproblemsonlyrequiresmall modificationstoprovidedlistingsofMATLABcode.Problemswhichhavebeen markedwithtwoorthree‘*’generallyhaveincreasedcomplexity,requiremore studentprogramming,andhaveacorrespondinglygreateranticipatedrequiredtime spentinsolvingthem.Theymaymakesuitableprojectsforthebeginningstudent.
TheauthorusesthefollowingsystemforassigningandassessingHW.AllHW willbesubmittedelectronicallyviathecoursemanagementsystem,e.g.,BBLearn orMoodle.EachHWwillfirstandforemostbeashortreport,statingtheproblem solved,givingabriefdescriptionofthealgorithmsandmethodsusedtosolvethe problems,containinggraphicalortabularsummariesofoutput,andwithabriefbut convincinganalysisoftheresults.Wherepossible, comparisons betweenknownand approximatesolutionsshouldbeincluded.Eachreportshouldbein .pdfformat.The uploadshouldbeaccompaniedbyoneorseveral.mMATLABfiles,capableofonly
1 Somecourseinstructorsmayconsiderthatextensivesharingofcodeorstudentdownloadingof existingcodefromtheInternetaccomplisheslittletowardcoursegoals,andinsomecasesmay considersuchactionstobeunethical.
minoreditingofgeneratingthevalidresultscontainedinthereport.Thereportshould avoidtheinclusionoflargequantitiesoftediousdata,graphics,codelistings,etc. Summarize!
Forratingthepointvalueofindividualhomeworkexercises,theauthorgenerally usesascaleof10,20,and40pointsforsingle-,double-,andtriple-starredproblems, respectively.Toallowforsomestudentchoiceandindependentinvestigationof severalaspectsofagiventopic,theauthoroftenmakesassignmentsoftheform submitxoutofypossiblepointsworthofstarredproblemsolutionsfromSectionsW andZ,e.g.,200outof340possiblepointsworthofstarredproblemsfromChap. 2, asthefirstassignment.
1.3TheOrganizationofThisText Thetextisorganizedasfollows.
Chapter 2 containsabriefintroductiontoMATLAB,withafewrelevantelementaryexamplesandafairlyextensivelistofwarm-upexercises.Inparticular,we discussRunge–KuttaforsystemsofODE,numericaldifferentiationandintegration,andNewton’smethodappliedtovectorfields.Throughoutthischapter,we distributeadiscussionoftheMATLABcommandsneededinallsubsequentmaterial,including linspace, kron, spdiags, meshgrid, reshape, eigs,and thepowerfullinearsystemsolver‘\’.Fromtheauthor’sexperienceswithstudents whiledevelopingthesenotes,weattemptinthischaptertoaddressmanyoftheir ‘frequentlyaskedquestions’concerningcommonpitfallsinprogrammingand MATLABsyntax.Asubsectiononcubicsplinesdemonstratestheusesofmostof theabovecommandsinasingleapplication,inparticularbybuildingacomplicated sparsematrixenforcingthevariousconstraintsinordertosolvethecorrespondingsystemwithasinglelinearsolvecommand.Thefinalsectioncontainsabrief overviewofsometheoriesfortheexistenceanduniquenessofsolutionstoODE, ODEsystems,convergenceofNewton’smethod,orderofapproximationofIVP solvers,anddifferenceformulas.
Chapter 3 containsODEmaterial,butwithaneyetowardeasymodificationfor thesubsequentapplicationtoPDE.Thehomeworkexercisesassumefamiliarity withintegratingfactors,separationofvariables,convertingsecond-orderproblemstofirst-ordersystems,constantcoefficientlineartheory,somebasicexistence anduniquenesstheoryforIVP,eigenvalues,andothertopicstypicallycovered inanintroductoryundergraduateODEcourse.Itisalsoassumedthatthemost elementarynumericaltopicsareunderstood,e.g.,differenceapproximationsfor derivatives,Riemannsums,Euler’sandRunge–Kutta’smethodsforIVP,Newton’s methodforafunctionofoneorseveralvariables,andTaylor’sandLagrange’spolynomialapproximationtheoremswitherrorterms.Forabriefoverviewofthese
topics,seeSect. 2.6.InthelastsectionofChap. 3,weincludeabriefpractical guidefortheconstructionoftheFourierseries,whichareusedheavilyinChap. 4.
• Section 3.1 startsoffwithanexample:howtosolveanonlinearsecond-order ordinaryellipticboundaryvalueproblem(BVP)usingNewton’smethod.We usethisexampleasaplacetointroduceandexplainseveralessentialMATLABcommandsandtechniqueswhichwillbeconstantlyreusedthroughout thedocument.Theseconddifferencematrix D2 onthepointgridisintroduced inthisfirstapplicationandthenusedinmanysubsequentapplications.This Newton’smethodapproachismoreefficientcomparedtoimplementingthe shootingmethod,analternativeODE-onlymethodbrieflydiscussedinChap. 2. InSect. 4.3,onlysmallmodificationstotheODENewton’smethodcodewill berequiredtosolveasemilinearellipticBVPonthesquare.
• Section 3.2 solvesalinearordinarysecond-orderBVP.Byourpresentedmethod, notmuchchangewillberequiredinSect. 4.4 inordertosolveLaplace’sequationonasquaredomaininasimilarfashion.
• Section 3.3 solvesaclassicODEeigenvalueproblemwithoneadditionalline ofMATLABbeyondthatalreadycodedinprevioussections.Weusethisexampletointroduceeigenfunctionexpansions.Weincludeaproofoftheexact eigenvaluesofaseconddifferencematrix,whichisusefulinunderstandingthe convergenceofalgorithmsthatusethismatrix.Onlyminormodificationstothe developed MATLAB codeswillberequiredtosolveaPDEeigenvalueproblem onthesquareinSect. 4.2
• Section 3.4 showshowtobuildthe D2 matrixforboththepointandcellgrids, forDirichlet,Neumann,mixed,andperiodicboundaryconditions(BC).
• Section 3.5 solvesafirst-orderlinearinitialvalueproblem.Wefeaturethefirst differencematrix D1 .
• Section 3.6 appliesourfirst-ordermethodtoasystemoftwofirst-orderinitial valueproblemsinordertosolveasecond-orderinitialvalueproblem.
• Section 3.7 appliesNewton’smethodtosolveanonlinearfirst-orderinitialvalue problem(IVP),similartothatinSect. 3.1 butusing D1 .
• Section 3.8 providesabriefoverviewofthetheoryandapracticalguideforthe constructionoftheFourierseries.
Chapter 4 concernsPDE.Thehomeworkexercisesassumesomefamiliaritywith (ortheconcurrentlearningof)elementaryPDEtechniquesandtheory,includingseparationofvariables,applicationsofFourierseriesinPDE,eigenfunction expansions,Laplace’s,Heat,andWaveequations,forclassicalregionssuchas theinterval,square,disk,andannulardomains,withvariousboundaryandinitial
conditions.Fortheconvenienceofthereader,thesetopicsarebrieflysummarized inSect. 4.10.Therequirednumericaltechniquesareforthemostpartexplained inthistext,withsomereviewofclassicmethods,e.g.,theexplicitandimplicit methodsfortheheatequation.
• Section 4.1 introducessparseblockmatricesforencodingtheLaplacian.In particular,wedevelopthe D2 matrixonasquaredomain,enforcingDirichlet and/orNeumannBContheindividualfoursides,usingbothpointandcellgrids.
• Section 4.2 verifiesthenumericallyapproximatedeigenvaluesandeigenvectors oftheLaplacianonthesquareanddiscusseseigenfunctionexpansions.
• Section 4.3 generalizesthemethodfromSect. 3.1 tosolveasemilinearelliptic BVPonthesquare.
• Section 4.4 appliestheideasfromSect. 3.2 toPDEinordertosolvenonhomogeneousLaplace’sequationonthesquarewithnonhomogeneousmixedBC.
• Section 4.5 containssevenmethodsforsolvingtheheatequationontheinterval andsquare.Wepresenttheclassicexplicit,implicit,andCrank–Nicolsonmethods.Weusethismaterialasaplacetointroducethe‘methodoflines’(MOL)as ageneralandpowerfulPDEtechnique.Wemakeuseoftheseparationofvariable(SOV)eigenfunctionexpansionsolutionderivation,implementingFourier expansionsinMATLABtosolvetheheatequation,wherethecoefficientsare obtainedbyeitherexactformulasornumericalintegration.Wedemonstratethat itispossibletoobtainreasonableapproximationstosolutionsoftheheatequationbysolvingonelargesparselinearsystemwithasinglelinearsystemsolver call.
• Section 4.6 containsabriefdiscussionofthewaveequation,withexampleson theintervalandsquare.Weshowhowtoimplementthemethodoflines.We providediscussionandexercisesshowingthattheobviousexplicitandimplicit methodsexperiencedifficultieswithdissipationandphasedrift,andpresenta betteralternativeexplicitmethod.Itisdemonstratedthatalinearproblemsuch asthewaveequationcanbeeffectivelysetupandsolvedwithasingleinvocationofalinearsolver.
• Section 4.7 considersTricomi’sequation.Weareabletosolvetheseboundary valueproblemsbycombiningLaplace’sequationandwaveequationsinglelinear-systemtechniques.
• InSect. 4.8,wedeveloptechniquesforthecreationof D2 matricesforother regions.Weconsiderthecube,disk,annulus,angularsectorsofdiskandannulus,andsphere.BasedonMATLAB’sbuilt-in delsq function,weprovidean
elementarycodeforthefirstconsiderationofapproximatingaLaplacianonarbitrarysubdomainsofthesquare.Thereisafairlyextensivelistofcorresponding HWexerciseswhichaskfornumericalsolutionstomanyofthePDEfromthis chapteronspacialregionsotherthanintervalsandsquares.
• InSect. 4.9,webrieflydiscussfirst-orderPDE.Differencematricesarenotused. TheclassicmethodofcharacteristicsisusedtosetupandsolvesystemsofODE toobtainnumericalsolutionstothePDE.Wedemonstratewithanexamplethat featuresashock.
• InSect. 4.10,webrieflysummarizetheseparationofvariablestechniquefor solvingPDE.Inparticular,wecomputeeigenvaluesandeigenfunctionsofthe Laplacian,andsolutionstoLaplace’sequation,heatequations,andwaveequations.Avarietyofregionsandboundaryconditionsareconsidered.
Chapter 5 extendssomeoftheideasfromChap. 4 tomoreadvancedapplications insemilinearandfullynonlinearellipticBVP.
• Section 5.1 advancesourideasoffollowingbifurcationbranchesforsemilinear ellipticBVP.Section 5.1.1 introducesthetangentgradientNewtonalgorithm forcontinuation.Inparticular,wecanfollowbifurcationbranchesofthesemilinearellipticBVPfromSect. 4.3.Section 5.1.2 introducesthesecantmethod forlocatingbifurcationpoints.Section 5.1.3 discussesalittlefurthermethods anddifficultiesinfindingnewbranchesbifurcatingfromthesebifurcationpoints.
• Section 5.2 findsseverallow-energysolutionsofasemilinearellipticBVPby ‘minimax’variationalmethods.Section 5.2.1 appliesthecelebratedMountain PassAlgorithm(MPA)ofChoiandMcKenna[25]tofindaMI = 1one-sign solutiontoasuperlinearellipticBVP.Section 5.2.2 appliestheModifiedMountainPassAlgorithm(MMPA)tofindaMI = 2sign-changingexactly-once solutiontoasuperlinearellipticBVP.
• Section 5.3 brieflyintroducesthe p -Laplacian.Wesolvefullynonlinearelliptic BVPofthetype Δ p u = f and Δ p = λ(u |u | p 2 ) ontheintervalandsquare domains.
Chapter2 ReviewofElementaryNumerical MethodsandMATLAB® Summary Inthischapter,wereviewtheuseofMATLAB® inthecontextofseveral elementaryapplicationsfromordinarydifferentialequationsandcalculus.First,we practicebasicmatrixandvectoroperationsatthecommandline.Next,wewritea shortcodetoimplementEuler’smethod,whichwetheneasilymodifytoimplement theRunge–Kuttamethodforsystems.Werecalltheshootingmethod,anODE-only techniqueforsolvingBVPviarepeatedapplicationofanIVPsolver.Wefurther demonstrateMATLABsyntaxandprogrammingtechniquesonseveralelementary numericaldifferentiationandintegrationproblems,applyNewton’smethodtononlinearsystems,andsolveacubicsplinewithasinglelinearsystemsolvestep.The includedhomeworkexercisesrequirethereadertoimplementtheexampleprograms, andintroducesomenewconcepts.Eachsectionendswithoneormoresubsections containingabriefdiscussionofthevariousaspectsofMATLABwhichoneneedsin ordertoimplementandexecutethealgorithms.Thismaterialattemptstoaddressthe manyfrequentlyaskedquestionsconcerningthenutsandboltsofgettingaprogramto produceappropriateoutput.Weintroducesomeconceptsandtechniquesforthecomparisonofapproximatesolutionstoexactsolutions,apedagogicalthemerepeated intheHWexercisesthroughoutthistextbook.Wepresentingrayboxesoverviews ofspecificMATLABcommandsandsyntaxusedintheseprogramswhichmightbe newtotheuninitiated,andwhicharereliedonheavilythroughoutthistext.
Thischapterassumesabasicfamiliaritywithcalculusandordinarydifferential equations.Standarddifferentialequationsandcalculustextssuchas[2]and[19] canbeconsultedbythereaderasneededforthemathematicaltheorybehindthe examples.Throughoutthisbook,itisusefultoknowsomelinearalgebra,suchas thatcoveredin[1, 7, 11, 15].Allthealgorithmsofthischaptercanbefoundinany standardintroductorynumericalanalysistexts,suchas[3].
Alongsidethedevelopmentofseveralprograms,weexplaintotheuninitiateda littleaboutgraphicsandafewotherelementarybutpossiblyconfusingaspectsof MATLAB.TheMATLAB help functionalityandallmannerofonlineexamplescan
©SpringerNatureSwitzerlandAG2023
J.M.Neuberger, DifferenceMatricesforODEandPDE, https://doi.org/10.1007/978-3-031-12000-8_2
andshouldbeconsultedtolearnmoreabouttherichnessofoptions,commands,data structures,fileI/O,andsoon.
ThepossibilitiesofprogrammingandapplicationsforMATLABarevast.For theconvenienceofthereader,weprovideinthischapter’sbrieftutorialexamplesof mostofthecommandswhichareusedintheimplementationofthealgorithmsinthe subsequentchapters.ThereadershouldtakeparticularnoteoftheusefulMATLAB commands linspace, meshgrid, kron, spdiags,andthepowerfulsolvers eigs and‘\’,usedtocomputeeigenvaluesandsolvelinearsystems,respectively. Allthesecommandsareusedheavilythroughoutthistext.
Wealsogivesomeguidancetowardanumberofotherissuesconcerningthe operationofMATLAB,e.g.,webrieflydiscussusingMATLABatthecommand line,basicmatrixandvectoroperations,thethreadingofsomealgebraicoperators withadot(‘.’),logicaloperations,andsoon.Weprovideashortdiscussionabout rowandcolumnvectors,thedimensionsandsizesofarrays,anddiagnosingthe relatederrorsthatoccurwhenquantitiesinacalculationarenotofcompatibleshape. Includedisadiscussionofsomeconceptsandtechniquesforthecomparisonof approximatesolutionstoexactsolutions.Thefinalsectionofthischaptercontainsa briefsummaryoftheelementarytheoryforODE,systems,orderofapproximation ofODEsolvers,Newton’smethod,anddifferenceformulaswitherrorterms.
2.1IntroductiontoBasicMATLAB® attheCommandLine OnecanuseMATLABasacalculator,withoutcreatingafile.Theworkspaceholds anynewlycreatedvariables(notlocalvariablesdeclaredinfunctions)andtheir valuesforsometime,soitispossibletoineffectwriteaprogrambysequentially executingcommandsatthecommandline.Onewillfinditinconvenienttorepeat complicatedstepsiftheyareonlysavedinyourcommandhistorybuffer,butitisoften convenienttotypeafewcommandsatthecommandlineprompttoexploreafew MATLABexpressionsofparticularinterest.Ifaprogramispausedbythedebugger ataparticularline,theworkspacewillcontainthestateofallcurrentvariablesatthat pointofthesequentialexecutionoftheprogram.
Theoperations +,, * , /,and ˆ denotetheusualoperationsforscalars,vectors, andmatrices.Forexample,if A isan m × n matrix,then A ∗ x makessenseonly if x isascalaroran n × k matrix.If k = 1then x isacolumnvector,andthisis normalmatrix-vectormultiplication.Sometimes,onewantstoperform componentwiseoperations ratherthantheusualmathematicaloperation.Forthis,oneusesa dot(.)beforetheoperationsymbol.Forexample,if A and B are m × n matricesfor somenaturalnumbers m and n (including1,i.e.,columnorrowvectors),then A.*B denotesthe m × n matrixwithentries aij bij .If c isascalar,nodotisneededforthe usualmultiplication c ∗ A ,butwecanusethedottoexponentiatecomponent-wise asin A.ˆc,whichgivesthe m × n matrixwithentries (aij )c .The sum, max,and norm commandsareusefulexamplesofthemanybuilt-inmatrix-vectoroperators.
Trythefollowingmatrixoperationstogetcomfortablewiththeexpectedresult. Repeatwithsomerowandcolumnvectors,andacoupleofnon-squarematrices.
> A=[12;3,4]; creates2 × 2matrix. Separatorspacesandcommasindicatenewcolumn. Separatorsemicolonindicatesnewrow. Terminatorsemicolonsuppressesoutputtoscreen.
> B=[12;21];c=3; Defineasecond2 × 2matrixandascalar.
> A*B
Usualmatrixproductresultdisplayedtoscreen.
> A.*B
Component-wiseproductresultdisplayedtoscreen.
> A./B
Component-wisedivisionresultdisplayedtoscreen. Theoperation A/B actuallyinvokesalinearsystemsolver!
> A+B
Noneedfordot,usualadditionisalreadycomponent-wise.
> A.ˆB
Component-wiseexponentiation.
Operation AˆB givesanerror.
> A.ˆc
Component-wiseexponentiation.
Operation Aˆc givesusualpowerofsquare n × n matrix.
Operation Aˆc giveserrorif A notasquarematrix.
> x=[1;3;-5]
Createcolumnvector.
> sum(x)
Sumcolumnvector.Try prod(x) instead.Try sum(A) also.
> norm(x)
ReturnsusualEuclideanvectornorm.
> max(abs(x))
Equivalentto norm(x,1)
Inordertoplotatypical(non-symbolic)function,itisnecessarytounderstand thewayMATLAB’svariousplottingfunctionstakeasinputanarrayofdependent, discretevalues,and,optionally, arraysofthesamesize ofindependentvalues.A convenientwaytodiscretizearangeofvalueswhichweusethroughoutthistextis viaMATLAB’s linspace command.
> n=10;x=linspace(0,1,n+1)’; createscolumnvector x (i ) = (i 1)/ n , i = 1,..., n + 1. semicolonsuppressesoutputtoscreen. singlequote transposes rowvectortocolumnvector.
> plot(sin(pi*x)); createsanew(bydefault)figurecontainingtheplot. manyfunctionslikesinthreadovervectors,thatis x , sin ( x ) ∈ Rn +1 .
> f=@(k,x)sin(k*pi*x); definesafunctionwhichcanbelaterplottedorpassedtootherfunctions
> figure(10);plot(x,f(1,x)); createssameplotasabove,butinadifferentfigureandwithindependent x -values.
> for k=1:6 startaloop.commandpromptsuppresseduntil‘end’ > holdon; multiplegraphicswillappearinsamefigure
plot(x,f(k,x)); end loopexecuted,figurewithmultiplegraphicscreated.
Wewillusethepowerful eigs commandtosolveseriousproblemsindifferential equations,butwecanimmediatelyandeasilyuseittocomputetheeigenvaluesor eigenvectorsofanysmallsquarematrix.
> A=[21;12]; eigs(A) returnsthetwoeigenvaluesof A. [V,D]=eigs(A) returnstheeigenvectorsandeigenvalues. V(:,1) extractsthefirsteigenvector. diag(D) extractstheeigenvalues. V*D*V’ reconstitutes A viaorthogonaldiagonalization.
> B=diag(1:8) (createsdiagonalmatrixwithentries1to8) eigs(B) returnsbydefaultsixlargesteigenvalues. [V,D]=eigs(B,6,'sm') returnssixsmallesteigenvalues.
> L=[Azeros(2,8);zeros(8,2)B] (creates10 × 10blockmatrix.) [V,D]=eigs(L,6, 'sm') returns6smallesteigenvalues.
Ifyouexperimentmuchwiththeaboveexercises,youwillsoonbefrustrated withretypingorrecallinglinestofixmistakesortrydifferentoptions.Foranything complicated,thecommandsaregenerallystoredpermanentlyinafile,whichisthen executedallatonceasaprogram,orsteppedthroughline-by-lineinthedebugger. AgoodtimetouseMATLABasacalculatoriswhenaprogramispausedinthe debuggerandtheworkspacecontainsallcurrentvariables.Ifthecommandhistory containsseveralgoodlines,theycanbecopiedandpastedintoanewfile,andpresto, aprogram,isborn.Inthenextsections,wepresentaseriesofshortprogramsthat introducemoreMATLABcommandsandsolveelementaryproblemsfromcalculus anddifferentialequations.
2.1.1MATLAB® :sum,prod,max,min,abs,norm,linspace, forloop,eigs,andsort
WebrieflydiscusshereafewoftheMATLABcommandsandsyntaxesusedinthis section,inparticularthosewhicharereliedonthroughoutthistext.
The sum, prod, max, min, abs,and norm commands. Givenacolumnorrowvector x ,thecommands sum, prod, max,and min allreturnascalaroftheintendedcalculatedvalue.Givenatwo-dimensional array,thesefourcommandsreturnarowvectorwhereeachentryistheresult ofthecalculationalongcolumns.The abs commandthreadsoveranyarray, e.g., abs ( A ) = (abs (aij )).The norm commandreturnsbydefaulttheusual Euclideanlengthofavector,e.g., norm(u)= u 2 i ,althoughthecommand acceptsoptionstoenforceothernorms.
The linspace command.
Thebuilt-inMATLABcommand linspace isusedthroughoutthistext asaconvenientwaytogeneratearowvectorofregularlyspacedvaluespartitioningagiveninterval.TheMATLABstatement x=linspace(a,b,n+1); generatesarowvector x oflength n +1suchthat x (i )=a +(i 1)(b a )/ n , for i = 1, ··· , n + 1.
Theauthorhasmadeamoreorlesspermanentdecisionthat nwillalwaysbethe numberofdivisionsofagiveninterval,sothat n + 1isthenumberofpoints,including