已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 数据安全与隐私保护-第33篇-洞察与解读
- 英文版安全教育课件
- 小学生用电安全知识培训课件
- 湖南省三新联盟联考2025-2026学年高一上学期11月期中考试生物试卷
- 安全疏散课件基本参数2
- 广东省小学五年级上学期数学第七单元测试卷-方阵问题
- 中职生劳务派遣合同
- 2026届江苏省苏州市常熟中学高二化学第一学期期中质量跟踪监视试题含解析
- 工会服务采购合同
- 丹阳农机水泵采购合同
- 吴《园林植物配置技术》课件
- 公路养护应急预案
- 隔膜泵真空泵工安全操作规程
- 水浒传人物吴用
- 2023年河南省安阳豫北水利勘测设计院有限公司招聘笔试题库含答案解析
- 2023 可靠性设计基础试卷
- 部编版小学道德与法治六年级下册第4课《地球-我们的家园》公开课课件
- 群落的演替课件
- GB/T 9995-1997纺织材料含水率和回潮率的测定烘箱干燥法
- GB/T 3469-1983文献类型与文献载体代码
- GB/T 27809-2011热固性粉末涂料用双酚A型环氧树脂
评论
0/150
提交评论