Matlab预定义函数.ppt_第1页
Matlab预定义函数.ppt_第2页
Matlab预定义函数.ppt_第3页
Matlab预定义函数.ppt_第4页
Matlab预定义函数.ppt_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1,Matlab与科学计算,计算机学院刘咏梅Email:liuyongmei,2,第四章MATLAB编程(预定义函数),IntroductiontoMATLABMATLABBasicsofNumericalComputingMATLABProgramming(branchingandLoops)MATLABProgramming(PredefinedFunctions)MATLABGraphicandImageProcessingScientificComputingusingMATLAB,3,本章学习的目标:,IntroductiontoMatlabFunctionsbuiltinfunctionsanduserdefinedfunctionsOptionalArgumentsSharingDataUsingGlobalMemoryPreservingDataBetweenCallstoaFunctionFunctionFunctionsSubfunctions,4,Functions,FunctionsaremorecomplexthanscriptsFunctionshavetheirownlocalvariablesFunctionsreturnoutputasspecified,andcanacceptinputasspecified,5,Whyweusefunctions?,IndependentTestingofSub-Tasks:Eachtaskisanindependentunitthatcanbetestedseparately(unittesting).ReusableCode:Withinthesameprogram(thecodeisnotrepeated).Itcanbeusedinanotherprogram.Isolationfromunintendedsideeffects:Isolationoffunctionvariablesfromthemainprogramvariables.Theinputandtheoutputvariablesarespecifiedclearly.,6,SyntaxofMatlabFunctions,Userdefinedfunctionsbehavejustlikebuiltinfunctions.Allfunctionshaveasimilarsyntax,whethertheyarebuilt-infunctionsoruser-definedfunctions.NameInputOutput,A=cos(x),7,Howtocallfunctions?,Thefunctionscanbecalleddirectlyinthecommandwindow,orbyanyotherprogramorfunction.Veryimportant:iftheinputvariablesarechangedinthefunctionstheywillnotchangeinthemainprogram(PASS-BY-VALUESCHEME),8,BuiltinFunctions,Builtinfunctionsallowustoreusecomputercodeforcalculationsthatareperformedfrequently.Forexample,supposetherewerenobuiltinsinefunctioninMATLABandyouwilldoalotoftrigonometriccalculationsinvolvingthesineofanangle.WevealreadybecomefamiliarwithanumberofMATLABbuiltinfunctionslikesin(x)orplot(x,y)forexample.,9,SomeexamplesofBuiltinFunctions,Exponential(指数)exp(x)exponentialofx(ex)sqrt(x)squarerootofxLogarithmic(对数)log(x)naturallogarithm(lnx)log10(x)log2(x),10,SomeexamplesofBuiltinFunctions,Numeric(数值)fix(x)roundtonearestintegertowards0round(x)roundtonearestintegersign(x)+1,0or-1rem(x,y)Findsremainderofx/yComplex(复数)abs(x)absolutevalueangle(x)phaseangleincomplexplaneconj(x)conjugateofximag(x)imaginarypartofxreal(x)realpartofx,11,BuiltinFunctionsforvectors,max(x)returnslargestvalueinvectorxa,b=max(x)returnslargestvalueinaandindexwherefoundinbmax(x,y)xandyarraysofsamesize,returnsvectorofsamelengthwithlargervaluefromcorrespondingpositionsinxandymax(352,648)ans=658sametypeoffunctionsareavailableformin,12,BuiltinFunctionsforvectors,sort(x)sortinascendingordescendingordermean(x)averageormeanvaluemedian(x)medianvaluesum(x)sumofelementsofxprod(x)productofelementsofxcumsum(x)returnsvectorofsamesizewithcumulativesumofxi.e.x=4,2,3returns4,6,9cumprod(x)returnsvectorofsamesizewithcumulativeproductsinvectorofsamesizei.e.x=4,2,3returns4,8,24,13,Builtinfunctionsappliedtomatrices,Matrices(arrays)arestoredincolumnmajorformWhenbuiltinfunctionsforvectorsareappliedtoamatrixfunctionoperatesoncolumnsandreturnsarowvector,14,Builtinfunctionsappliedtomatrices,sum(012;345)ans=357prod(012;345)ans=0410cumsum(012;345)ans=012357,cumprod(012;345)ans=0120410sort(912;324)ans=312924,15,User-definedFunctions,YoucanuseuserdefinedfunctionsinyourprogramsjustasyouwoulduseMATLABsbuiltinfunctions.Userdefinedfunctionshelpyouwritemorecompactprogramsandwritecomplexprogramsintoshorteronesthatareeasiertodebugandgetrunning.,16,User-definedFunctions,User-definedfunctionsmuststartwithafunctiondefinitionline.ThedefinitionlinecontainsThewordfunctionAvariable(variables)thatdefinesthefunctionoutputAfunctionnameAvariable(variables)usedfortheinputargument,functionoutput=poly(x),Theabovelineofcodesdefinesafunctionnamedpoly.,17,Asimpleexampleofuser-definedfunctions,18,YoucanuseyouruserdefinedfunctionsfromtheCommandWindoworfromaM-fileprogram.,19,Whenxisavector,Considerthefollowing,A=1,2,5;%Aisa3-elementrowvectory=2*poly(A)y=1482982Inthestatementy=2*poly(A)above,theuserdefinedfunctionpolyiscalledwhichevaluatesthepolynomialateachpointintheinputrowvector.Then,eachvalueismultipliedby2,resultingintherowvectorcalledyhavingthevalues14,82,982.,20,CommentsforFunctions,Thecommentlinesimmediatelyafterthefirstlinearereturnedwhenyouquerythehelpfunction,21,22,Userdefinedfunctionsmay,Havemorethanoneinputvariable,functions=f(x,y,z).Thisfunctionhasthreeinputvariables.Havemorethanoneoutputvariable,functionout1,out2=f(x)isafunctionwithoneinputvariableandtwooutputvariables.Inputandoutputvariablescanbescalars,vectorsormatrices.Withinthebodyofthefunction,thereneedstobeoneassignmentstatementforeachoutputvariable.,23,LocalVariables,Anyvariablesusedwithinafunctionarecalledlocalvariables.ThesevariablesdonotappearintheWorkspaceWindowandarenotavailableforthemainprogramtoaccess.Theoutputvariablenamesusedinthefunctionstatementandinthebodyofthefunctionarealsolocalvariables.Theinputvariablesarelocalvariablesalso.,24,LocalVariables,VariablesdefinedinanM-filefunction,onlyhavemeaninginsidethatprogramTheonlywaytocommunicatebetweenfunctionsandtheworkspace,isthroughthefunctioninputandoutputarguments,25,x,y,a,andoutputarelocalvariablestothegfunction,Whenthegfunctionisexecuted,theonlyvariablecreatedisdeterminedinthecommandwindow(orscriptM-fileusedtoexecuteaprogram),ansistheonlyvariablecreated,26,OptionalArguments,Forexample:plotfunctionx=0:pi/100:2*pi;y1=sin(2*x);y2=2*cos(2*x);plot(x,y1,x,y2);,x=0:pi/100:2*pi;y1=sin(2*x);y2=2*cos(2*x);plot(x,y1);holdon;plot(x,y2);,27,OptionalArguments,max(x)returnslargestvalueinvectorxa,b=max(x)returnslargestvalueinaandindexwherefoundinbmax(x,y)xandyarraysofsamesize,returnsvectorofsamelengthwithlargervaluefromcorrespondingpositionsinxandysametypeoffunctionsareavailableformin,28,OptionalArguments(InputandOutput),Optionaloutput,Optionalinput,29,Determinethenumberofinputandoutputvariables,Twobuiltinfunctionsletyoudeterminethenumberofinputandoutputvariablesinanyfunction,forfunctions=f(x)nargin(f)returnsinourcase,ans=1sincefhasoneinputargument,andnargout(f)alsoreturnsans=1inourcasebecausefhasonlyoneoutputvariable.,nargin:determinesthenumberofinputargumentsnargout:determinesthenumberofoutputarguments,30,GlobalVariables,Remembervariablenamesusedwithinafunctionarelocalvariables,theydonotappearintheWorkspacewindowofthemainprogram.ItispossibletodefineaGlobalVariablethatisthencommontoboththemainprogramandthefunction.Itisrecommendednottodothis.Althoughitispossibletodefineglobalvariables,itisabadidea!,31,SharingDataUsingGlobalMemory,Globalmemoryisaspecialmemorythatcanbeaccessedfromanyworkspace.Syntax:globalvar1var2var3Remark:Eachglobalvariablemustbedeclaredtobeglobalbeforeitisusedforthefirsttimeinafunction.Bettertobethefirststatementinthefunctionaftertheinitialcomments.,32,PreservingDataBetweenCallstoaFunction,Eachtimethefunctionisfinished,dataintheworkspaceisdestroyed.Tomakesomevariablespersistentforthenextfunctioncalls,usethepersistcommand.Specialtypeofmemorythatcanbeaccessedonlyfromthesamefunction.Syntax:persistentvar1var2var3,33,PreservingDataBetweenCallstoaFunction,Exercise:runningaveragesandstandarddeviations.Usermustenterthenumberofvaluesindataset,andthenentervaluebyvalue.Eachtimeheentersavaluetheprogramcallsthefunction

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论