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

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

An introduction to numerical methods: a MATLAB approach 4th Edition Guenther
https://textbookfull.com/product/an-introduction-to-numericalmethods-a-matlab-approach-4th-edition-guenther/

Applied Numerical Methods with MATLAB for Engineers and Scientists Fourth Edition Steven C. Chapra Dr.
https://textbookfull.com/product/applied-numerical-methods-withmatlab-for-engineers-and-scientists-fourth-edition-steven-cchapra-dr/


Numerical Methods for Engineering: An introduction using MATLAB® and computational electromagnetics examples (Electromagnetic Waves) 2nd Edition Karl F. Warnick
https://textbookfull.com/product/numerical-methods-forengineering-an-introduction-using-matlab-and-computationalelectromagnetics-examples-electromagnetic-waves-2nd-edition-karlf-warnick/
Numerical Linear Algebra A Concise Introduction with MATLAB and Julia Folkmar Bornemann
https://textbookfull.com/product/numerical-linear-algebra-aconcise-introduction-with-matlab-and-julia-folkmar-bornemann/

Numerical Methods for Engineers and Scientists Using MATLAB Second Edition Esfandiari
https://textbookfull.com/product/numerical-methods-for-engineersand-scientists-using-matlab-second-edition-esfandiari/

A Little Bit of Numerology An Introduction to Numerical Divination Novalee Wilder
https://textbookfull.com/product/a-little-bit-of-numerology-anintroduction-to-numerical-divination-novalee-wilder/

Numerical Methods for Engineers and Scientists Using MATLAB® Ramin S. Esfandiari
https://textbookfull.com/product/numerical-methods-for-engineersand-scientists-using-matlab-ramin-s-esfandiari/

Numerical Methods of Exploration Seismology With Algorithms in Matlab r Gary F. Margrave
https://textbookfull.com/product/numerical-methods-ofexploration-seismology-with-algorithms-in-matlab-r-gary-fmargrave/

Numerical Linear Algebra An Introduction 1st Edition Holger Wendland
https://textbookfull.com/product/numerical-linear-algebra-anintroduction-1st-edition-holger-wendland/

An Introduction to Numerical Methods
A MATLAB® Approach
Fourth Edition

An Introduction to Numerical Methods A MATLAB® Approach
Fourth Edition
Dr. Abdelwahab Kharab Abu Dhabi University
Professor Ronald B. Guenther Oregon State University
MATLAB • is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks does not warrant the accuracy of the text or exercises in this book. This book’s use or discussion of MATLAB • software or related products does not constitute endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular use of the MATLAB • software.
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2019 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business
No claim to original U.S. Government works
Printed on acid-free paper
Version Date: 20180612
International Standard Book Number-13: 978-1-138-09307-2 (Hardback)
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation without intent to infringe.
Library of Congress Cataloging-in-Publication Data
Names: Kharab, Abdelwahab, author. | Guenther, Ronald B., author.
Title: An introduction to numerical methods : a MATLAB approach / Abdelwahab Kharab, Ronald B. Guenther.
Other titles: Numerical methods
Description: Fourth edition. | Boca Raton, Florida : CRC Press, [2018] | Includes index.
Identifiers: LCCN 2018011079| ISBN 9781138093072 (hardback : alk. paper) | ISBN 9781315107042 (ebook)
Subjects: LCSH: Numerical analysis--Data processing. | MATLAB.
Classification: LCC QA297 .K52 2018 | DDC 518--dc23
LC record available at https://lccn.loc.gov/2018011079
Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the CRC Press Web site at http://www.crcpress.com


Preface
Thisisatextbookdesignedforanintroductorycourseinnumericalmethods.It dealswiththetheoryandapplicationofthemostcommonlyusednumericalmethodsforsolvingnumericalproblemsonmicrocomputers.Itis intendedforstudents inmathematics,science,andengineeringwhohavecompletedtheintroductorycalculussequence.Inaddition,thereaderisassumedtohavetakenastructured programmingcourse.Thethrustofthistextistoassistthestudentstobecome familiarwiththemostcommonnumericalmethodsencounteredinscienceandengineering.Thecontentmaterialofthisbookhasbeendesignedtobecompatible withanyintroductorynumericaltextbookthatexistsinthe market.Studentswill beabletoexamineandsolvemanynumericalproblems,usingMATLAB R 1 ina shortperiodoftime.
Duetotherapidadvancementofcomputertechnologyandsoftwaredevelopments, wehaveusedMATLABasthecomputingenvironmentthroughout allthechapters ofthebook.Eachnumericalmethoddiscussedinthisbookisdemonstratedthrough theuseofMATLABwhichiseasytouseandhasmanyfeaturessuchas:
1.Powerfulmatrixstructure,
2.Powerfultwo-andthree-dimensionalgraphingfacilities,
3.Avastnumberofpowerfulbuilt-infunctions,
4.MATLAB’sstructuredprogrammingstylethatresemblesFORTRANandBASIC.
Thegoalofthispresentfourtheditionisthesameasthepreviousone.Thebook introducesstudentstoawiderangeofusefulandimportantalgorithms.Computer
1MATLAB R isaregisteredtrademarkoftheMathWorks,Inc. Forproductinformation,pleasecontact: TheMathWorks,Inc. 3AppleHillDrive Natick,MA01760-2098USA
Tel:508-647-7000Fax:508-647-7001
E-mail:info@mathworks.comWeb:www.mathworks.com
resultsarepresentedwithfulldetailssothatthemainstepsofthealgorithmofeach numericalmethodarevisualizedandinterpreted.Forthisreason,asupplementary CD-ROM,attachedatthebackofthebook,hasbeendevelopedforstudents’use withMATLAB.TheCD-ROMcontainssimpleMATLABfunctionsthatgiveaclear step-by-stepexplanationofthemechanismbehindthealgorithmofeachnumerical methodcovered.Emphasisisplacedonunderstandinghowthe methodswork. Thesefunctionsguidethestudentthroughthecalculations necessarytounderstand thealgorithm(s).Themainfeatureofthisbook,besidetheuseofMATLABasits computingenvironment,isthatthestyleofthebookiseasy, direct,andsimple. Thisislikelytobooststudents’confidenceintheirability tomastertheelements ofthesubject.
Thebookisorganizedinafairlystandardmanner.Topicsthataresimpler,both theoreticallyandcomputationally,comefirst;forexample Chapter2 containsan introductiontocomputerfloatingpointarithmetic,errors,andintervalarithmetic andfindingtherootofequationsiscoveredin Chapter3 .
Bothdirectanditerativemethodsarepresentedin Chapter4 forsolvingsystems oflinearequations.
Interpolation,splinefunctions,conceptsofleastsquaresdatafitting,andnumericaloptimizationarethesubjectsof Chapters5, 6, 7,and 8. Interpolationforms thetheoreticalbasisformuchofnumericalanalysis.
Chapters9 and 10 aredevotedtonumericaldifferentiationand integration.Severalefficientintegrationtechniquesarepresented.
In Chapters11 and 12 awidevarietyofnumericaltechniquesispresentedforsolvinglinearintegralequationsandordinarydifferentialequations.Anintroductionfor solvingboundaryvalueproblemsispresentedin Chapter13. Chapter14 isdevoted tosomenumericaltechniquesforcomputingtheeigenvalues andeigenvectorsofa matrix.AnintroductiontoDynamicalsystemsandChaosispresentedin Chapter 15.Thelast Chapter16 providesabasicintroductiontonumericaltechniquesfor solvingpartialdifferentialequations.
Ineachchapterwehaveattemptedtopresentclearexamplesineverysection followedbyagoodnumberofrelatedexercisesattheendofeachsectionwith answerstosomeexercises.
Itisthepurposeofthisbooktoimplementvariousimportant numericalmethods onapersonalcomputerandtoprovidenotonlyasourceoftheoreticalinformation onthemethodscovered,butalsotoallowthestudenttoeasilyinteractwiththe computerandthealgorithmforeachmethodusingMATLAB.
Thistextshouldprovideanexcellenttoolsuitableforteachingnumericalmethod coursesatcollegesanduniversities.Itisalsosuitableforself-studypurposes.
FeaturesintheFourthEdition
Therehavebeensomeminorchangesinsomesections.Majornewfeaturesare asfollows:
• AnewchapteronDynamicalsystemsandChaos.
Acknowledgments
Wewishtothankthemanypersonswhohavehelpedusinthecreationofthis book.Theyare:
FromAbuDhabiUniversity,Dr.DeenaElsori,Dr.JamalBenbourenane,Dr. MakhtarSarr,Prof.HaydarAkcaandProf.HichemEleuch.Mr. SaadaouiMohamedfromUniversityofLaghouat.
Specialthanksareduetothosewhogavetheirtimetoeditour book,Mr.Zack PolaskiandMr.FayselKharabfromLisbonUniversity.
TheauthorsremainverygratefultoSarfrazKhanandtheeditorialandproductionstaffofChapman&Hall/CRCwhohavebeenhelpfulandavailableatall stages.
Finally,theauthorsaregratefulforthefinancialandfacilitiessupportprovided byDr.AshrafKhalilDirectorofResearchofAbuDhabiUniversity.
Suggestionsforimprovementstothebookarealwayswelcome andcanbemade bye-mailat:awkharab@yahoo.com.
AbdelwahabKharab RonaldB.Guenther

Chapter1 Introduction
TheTaylorSeriesisoneofthemostimportanttoolsinnumericalanalysis.It constitutesthefoundationofnumericalmethodsandwillbe usedinmostofthe chaptersofthistext.FromtheTaylorSeries,wecanderivetheformulasanderror estimatesofthemanynumericaltechniquesused.Thischaptercontainsareview oftheTaylorSeries,andabriefintroductiontoMATLAB R .
1.1ABOUTMATLABandMATLABGUI(GraphicalUserInterface)
MATLAB(MATrixLABoratory)isapowerfulinteractivesystemformatrixbasedcomputationdesignedforscientificandengineeringuse.Itisgoodformany formsofnumericcomputationandvisualization.MATLABlanguageisahighlevelmatrix/arraylanguagewithcontrolflowstatements,functions,datastructures, input/output,andobject-orientedprogrammingfeatures. Tofullyusethepower andcomputingcapabilitiesofthissoftwareprograminclassroomsandlaboratories byteachersandstudentsinscienceandengineering,partof thistextisintendedto introducethecomputationalpowerofMATLABtomodernnumericalmethods.
MATLABhasseveraladvantages.Therearethreemajorelementsthathave contributedtoitsimmensepopularity.First,itisextremelyeasytousesince datacanbeeasilyentered,especiallyforalgorithmsthatareadaptabletoatable format.Thisisanimportantfeaturebecauseitallowsstudentstoexperiment withmanynumericalproblemsinashortperiodoftime.Second,itincludeshighlevelcommandsfortwo-dimensionalandthree-dimensional datavisualization,and presentationgraphics.Plotsareeasilyobtainedfromwithinascriptorincommand mode.Third,themostevidentpowerofaMATLABisitsspeedof calculation. Theprogramgivesinstantaneousfeedback.Becauseoftheir popularity,MATLAB andothersoftwaresuchasMAPLEandMathematicaarenowavailableinmost universitymicrocomputerlaboratories.
Oneoftheprimaryobjectivesofthistextistogivestudents aclearstep-by-step explanationofthealgorithmcorrespondingtoeachnumericalmethodused.To accomplishthisobjective,wehavedevelopedMATLABM-functionscontainedin
asupplementaryCD-ROMatthebackofthebook.TheseM-filescanbeusedfor theapplicationorillustrationofallnumericalmethodsdiscussedinthistext.Each M-functionwillenablestudentstosolvenumericalproblemssimplybyenteringdata andexecutingtheM-functions.
Itiswellknownthatthebestwaytolearncomputerprogrammingistowrite computerprograms.Therefore,webelievethatbyunderstandingthebasictheory underlyingeachnumericalmethodandthealgorithmbehindit,studentswillhave thenecessarytoolstowritetheirownprogramsinahigh-levelcomputerlanguage suchasCorFORTRAN.
AnotherfutureofMATLABisthatitprovidestheGraphicalUserInterface (GUI).Itisapictorialinterfacetoaprogramintendedtoprovidestudentswith afamiliarenvironmentinwhichtowork.Thisenvironmentcontainspushbuttons, togglebuttons,lists,menus,textboxes,andsoforth,allofwhicharealreadyfamiliartotheuser,sothattheycanconcentrateonusingtheapplicationratherthanon themechanicsinvolvedindoingthings.Theydonothavetotypecommandsatthe commandlinetoruntheMATLABfunctions.Forthisreason,we introducedGUI inthiseditiontomakeiteasierforthestudentstoruntheM-functionsofthebook. Areadmefilenamed”SUNPackagereadmecontainedinthedirectoryNMETH” oftheCDattachedatthebackcoverofthebook,explainsindetailsthestepsto followtoruntheMATLABfunctionsusingGUI.Inaddition, AppendixD shows theuseofGUIforsolvingseveralexamples.
1.2ANINTRODUCTIONTOMATLAB
InthissectionwegivetothereaderabrieftutorialintroductiontoMATLAB. Foradditionalinformationweurgethereadertousethereferenceanduser’sguides ofMATLAB.
1.2.1Matricesandmatrixcomputation
MATLABtreatsallvariablesasmatrices.Theyareassignedtoexpressionsby usinganequalsignandtheirnamesarecase-sensitive.Forexample,
>> A=[4-25;617;-106]
A= 4 25 617 106
Newrowsmaybeindicatedbyanewlineorbyasemicolon.Acolumnvector maybegivenas
>> x=[2;8;9]orx=[289]’
x=
2 8 9
Elementsofthematrixcanbeanumberoranexpression,like
>> x=[21+212/42^3]
x= 2338
Onecandefineanarraywithaparticularstructurebyusingthecommand
x=a:step:b
Asanexample
>> y=[0:0.2:1]
y=
00.20000.40000.60000.80001.0000
>> y=[0:pi/3:pi]
y=
01 04722 09443 1416
>> y=[20:-5:2]
y= 2015105
MATLABhasanumberofspecialmatricesthatcanbegenerated bybuilt-in functions
>> ones(2)
ans= 11 11 amatrixofall1’s.
>> zeros(2,4)
ans= 0000 0000 a2 × 4matrixofzeros.
>> rand(2,4)
ans=
0.95010.60680.89130.4565
0 23110 48600 76210 0185
a2 × 4randommatrixwithuniformlydistributedrandomelements.
>> eyes(3)
ans=
100 010 001
the3 × 3identitymatrix.
The diag functioneithercreatesamatrixwithspecifiedvaluesonadiagonalor extractsthediagonalentries.Forexample,
>> v=[325];
>> D=diag(v)
D=
300 020 005
a3 × 3diagonalmatrixwith v onthemaindiagonal.
Toextractthediagonalentriesofanexistingmatrix,the diag functionisused:
>> C=[2-47;318;-156];
>> u=diag(C)
u= 2 1 6
The linspace functiongeneratesrowvectorswithequallyspacedelements.The formofthefunctionis linspace(firstValue,lastValue,numValues)
where firstValue and lastValue arethestartingandendingvaluesinthesequence ofelementsand NumValues isthenumberofelementstobecreated.Forexample,
>> evens=linspace(0,10,6) evens= 0246810
Themostusefulmatrixfunctionsare
eig eigenvaluesandeigenvectors inv inverse lu LUdecomposition
qr QRfactorization rank rank
Acomponent-by-componentadditionoftwovectorsofthesamedimensionsis indicatedas
>> x=[158]; >> y=[243]; >> x+y
ans= 3911
Multiplyingavectorormatrixbyascalarwillscaleeachelementofthevector ormatrixbythevalueofthescalar.
>> C=2*[13;42]
C= 26 84
>> v=3*[14-57]
v=
312 1521
Thecomponent-by-componentmultiplicationofthevectors xandyisindicatedas
>> x.*y
ans= 22024
Theinner,ordot,productoftwovectorsisascalerandcanbe obtainedbymultiplyingarowvectorandacolumnvector.Forexample,
>> u=[57-12]; v=[2;3;10;5]; >> u*v
ans= 31
Thetransposeofamatrixoravectorisdenotedbyaprimesymbol.Forexample
>> x’
ans=
1 5 8
Thematrixoperationsofmultiplication,power,anddivisionareindicatedas
>> B=[13;42];
>> A=[25;06];
>> A*B
ans= 2216 2412
>> A^2
ans= 440 036
>> A/B
ans= 1 60000 1000
2.4000 0.6000
>> A.*B
ans= 215 012
Notethatthethreeoperationsofmultiplication,division,andpowercanoperate elementwisebyprecedingthemwithaperiod.
1.2.2Polynomials
MATLABprovidesanumberofusefulbuilt-infunctionsthatoperatesonpolynomials.Thecoefficientsofapolynomialarespecifiedbytheentriesofavector. Forexample,thepolynomial p(x)=2x3 5x2 +8isspecifiedby[2-508].To evaluatethepolynomialatagiven x weusethe polyval function.
>> c=[2-508];
>> polyval(c,2)
ans=
4
evaluatesthepolynomials p(x)=2x3 5x2 +8at x =2.
Thefunction roots findsthe n rootsofapolynomialofdegree n.Forexample,to findtherootsofthepolynomial p(x)= x3 5x2 17x +21,enter
>> a=[1-5-1721]; >> roots(a)
ans=
7.0000 3.0000 1.0000
1.2.3Outputformat
WhileallcomputationsinMATLABareperformedindoubleprecision,theformat ofthedisplayedoutputcanbecontrolledbythefollowingcommands:
formatshortfixedpointwith4decimalplaces(thedefault) formatlongfixedpointwith14decimalplaces formatshortescientificnotationwith4decimalplaces formatlongescientificnotationwith15decimalplaces formatratapproximationbyratioofsmallintegers
Onceinvoked,thechosenformatremainsineffectuntilchanged. ItispossibletomaketheprintedoutputfromaMATLABfunctionlookgoodby usingthe disp and fprintf functions.
disp(X) displaysthearray X,withoutprintingthearrayname.If X isastring, thetextisdisplayed.Forexample,
disp(’TheinputmatrixAis’)
willdisplaythetextplacedinsinglequotes.Thefunction disp alsoallowsusto printnumericalvaluesplacedintextstrings.Forexample, disp([’Newton’smethodconvergesafter’,num2str(iter),’iterations’]) willwriteonthescreen Newton’smethodconvergesafter9iterations
Herethefunction num2str(iter) convertsanumbertoastring.
Theotherfunction fprintf ismoreflexibleandhastheform
fprintf(’filename’,’format’,list)
where
filename isoptional;ifitisomitted,outputgoestothescreen.
format isaformatcontrolstringcontainingconversionspecificationsoranyoptional text.Theconversionspecificationscontroltheoutputofarrayelements.
Commonconversionspecificationsinclude:
%P.Qeforexponential
%P.Qffixedpoint
%P.Qgtoautomaticallyselecttheshorterof%P.Qeor%P.Qf wherePandQareintegersthatsetthefieldwidthandthenumberofdecimal places,respectively.
list isalistofvariablenamesseparatedbycommas,andthespecialformat \n producesanewline.
Forexample,thestatements
>> x=pi;y=4.679;z=9; >> fprintf(’\nx=%8.7f\ny=%4.3f\nz=%1.0f\n’,x,y,z)
printsonthescreen
x=3.1415927
y=4.679
z=9
1.2.4Planarplots
PlottingfunctionsisveryeasyinMATLAB.Graphsoftwo-dimensionalfunctions canbegeneratedbyusingtheMATLABcommand plot.Youcan,forexample,plot thefunction y = x2 +1overtheinterval[ 1, 2]withthefollowingcommands:
>> x=[-1:0.02:2];
>> y=x. ˆ2+1;
>> plot(x,y)
Theplotisshownin Figure1.1.Thecommand plot(x,y,’r+:’) willresultin r=red with + forpointsanddottedline.Use helpplot formanyoptions.
Toplotafunction f 1definedbyanM-file(see Subsection1.2.7)inaninterval [a,b],weusethecommand
>> fplot(’f1’,[a,b]).
FIGURE1.1
Plotofthefunction f (x)= x2 +1 in [ 1, 2].
Otherfeaturescanbeaddedtoagivengraphusingcommandssuchas grid, xlabel, ylabel,title,etc....Forexample,thecommand gridon willcreategridlinesonthe graph.
Plotsofparametricallydefinedcurvescanalsobemade.Try, forexample,
t=[0:0.01:4*pi]; x=cos(2*t); y=sin(3*t); plot(x,y).
Multipleplotsonasinglegraphareillustratedby
>> x=[0:0.1:2*pi];
>> y1=cos(x);y2=sin(x);y3=cos(2*x); >> plot(x,y1,x,y2,x,y3)
1.2.53-Dmeshplots
Three-dimensionalor3-Dmeshsurfaceplotsaredrawnwiththefunction mesh. Thecommand mesh(z) createsathree-dimensionalperspectiveplotoftheelements ofthematrix z
Thefollowingexamplewillgeneratetheplotshownin Figure 1.2 ofthefunction z = e x2 y2 overthesquare[ 4, 4] × [ 4, 4].
>> [xy]=meshgrid(-4.0:0.2:4.0,-4.0:0.2:4.0);
>> z=exp(-x.^2-y.^2);
>> mesh(x,y,z)
FIGURE1.2
Three-dimensionalsurface.
Thefirstcommandcreatesamatrixwhoseentriesarethepointsofagridin thesquare 4 ≤ x ≤ 4, 4 ≤ y ≤ 4withgrid0.2unitswideand0.2unitstall. Thesecondcommandcreatesamatrixwhoseentriesarethevaluesofthefunction z(x,y)atthegridpoints.Thethirdcommandusesthisinformation toconstruct thegraph.
Othercommandsrelatedto3-Dgraphicsare plot3 and surf.
1.2.6Functionfiles
MATLABcontainsavastcollectionofbuilt-infunctionsfromelementaryfunctionslikesineandcosine,tomoresophisticatedfunctions likematrixinversions, matrixeigenvalues,andfastFouriertransforms. Table1.1 containsasmallselectionofelementarymathematicalMATLABfunctionsand AppendixB contains additionallistsoffunctionsgroupedbysubjectarea.
Notethatallthesefunctionnamesmustbeinlowercases.MATLABfunctions mayhavesingleormultiplearguments.Forexample,
[U,D]=eig(A)
producesamatrix U whosecolumnsaretheeigenvectorsof A andadiagonalmatrix D withtheeigenvaluesof A onitsdiagonal.
cos(x) cosineof x
sin(x) sineof x
tan(x) tangentof x
sqrt(x) squarerootof x
abs(x) absolutevalueof x exp(x) exponentialof x
log(x) logtothebase e of x
log10(x) logtothebase 10 of x
cosh(x) hyperboliccosineof x
tanh(x) hyperbolictangentof x
asin(x) inversesinefunctionof x expm(A) exponentialofmatrix A
Table1.1 ElementarymathematicalMATLABfunctions.
1.2.7Definingfunctions
MATLABallowsuserstodefinetheirownfunctionsbyconstructinganM-filein theM-fileEditor/Debugger.Thefirstlineofafunctionhastheform
functiony=function name(inputarguments)
Asanexample,letusdefinethefunction f 1(x)=2x3 3x +1asanm.file.Using theEditor/Debuggeroranytexteditorlike emacs,or vi,weenter
functiony=f1(x)
y=2*x.ˆ3-3*x+1;
OncethisfunctionissavedasanM-filenamedf1.m,wecanusetheMATLAB commandwindowtocompute,forexample,
>> f1(2)
ans= 11
Userdefinedfunctionscanthemselveshavefunctionsasinputparameters.They canbeevaluatedinternallybyusingthefunction feval.Forexample,
>> x1=fzero(’f1’,0)
x1=
0.3949
givesthezeroof f1 closestto0.
Wecanpassonefunction f1.m toanotherfunction f2.m inMATLABbyusing the@symbol:
>> f2(@f1)
Forexample,thebuilt-infunction quad(f,a,b) inMATLABapproximatelyintegratesthefunction y = f (x)from a to b.Tousethisbuilt-infunctiontoapproximatelyintegrate y =cos(πx)+2from x = 1to x =1,webeginbywritinga MATLABfunctioncalled f1.m:
functiony=f1(x) y=cos(pi*x)+2;
Ifweareinthecorrectdirectory,wetypeinMATLAB:
>> quad(@f1,-1,1)
ans=
4 00000001667477
1.2.8Relationsandloops
Likemostcomputerlanguages,MATLABoffersavarietyofflowcontrolstatementslike for,while,and if.Thestatements,thatweusetocontrolthefloware calledrelations.
The Relationaloperators inMATLABare
==equal
<=lessthanorequal
>=greaterthanorequal
˜=notequal
< lessthan
> greaterthan
Notethat“=”isusedinanassignmentstatementwhile“==”is usedinarelation.
Logicaloperators &and
| or ˜not if,for,whilestatements