




已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 安全高空作业培训内容课件
- 设备安全生产标准化培训课件
- KV酒水购销合同3篇
- 海西路消防安全培训基地课件
- 2026届云南省昆明市石林县化学九上期末经典模拟试题含解析
- 设备安全操作与保养培训课件
- 2025年篮球常识试题及答案
- 押题宝典教师招聘之《小学教师招聘》考试题库(各地真题)附答案详解
- 2025年氢能专业考试题及答案
- 2025年教师招聘之《小学教师招聘》考试题库及答案详解(夺冠)
- 涉密文件日常管理办法
- 微信社交礼仪见面扫一扫时代25课件
- 药品批发企业《药品经营质量管理规范》
- 2025贵州黔西南州兴义市招聘事业单位教师40人备考试题及答案解析
- 2025甘肃省省直文博单位招聘事业编制工作人员26人笔试备考试题及答案解析
- 2025四川省公安厅警务辅助人员招聘(448人)笔试备考试题及答案解析
- 认识社会生活(教案)2025-2026学年统编版《道德与法治》八年级上册
- 一例跌倒护理不良事件分析
- invt英威腾CHF100A变频器说明书
- 新教师岗前培训讲座中小学教学常规PPT
- GA/T 1968-2021法医学死亡原因分类及其鉴定指南
评论
0/150
提交评论