Matlab入门教程 MatlabGettingstarted Matlab软件介绍 Matlabsoftwareintroduction Matlab和Mathematica、Maple并称为三大数学软件。它在数学类科技应用软件中在数值计算方面首屈一指。行矩阵运算、绘制函数和数据、实现算法、创建用户界面、连接其他编程语言的程序等。MATLAB的基本数据单位是矩阵,它的指令表达式与数学、工程中常用的形式十分相似,故用MATLAB来解算问题要比用C,FORTRAN等语言完成相同的事情简捷得多,并且MATLAB也吸收了像Maple等软件的优点,使MATLAB成为一个强大的数学软件。在新的版本中也加入了对C,FORTRAN,C,JAVA的支持。 Matlab,Mathematica,andMaplearecollectivelycalledthethreemajormathematicalsoftware。Itissecondtononeinnumericalcalculationinmathematicalscienceandtechnologyapplicationsoftware。Rowmatrixoperations,drawingfunctionsanddata,implementingalgorithms,creatinguserinterfaces,connectingprogramsinotherprogramminglanguages,etc。ThebasicdataunitofMATLABisamatrix。Itsinstructionexpressionsareverysimilartothosecommonlyusedinmathematicsandengineering。Therefore,itismuchsimplertouseMATLABtosolveproblemsthantouseC,FORTRANandotherlanguagestoaccomplishthesamething,andMATLABalsoAbsorbedtheadvantagesofsoftwarelikeMaple,makingMATLABapowerfulmathematicalsoftware。Inthenewversion,supportforC,FORTRAN,C,andJAVAhasalsobeenadded。 Matlab界面介绍 Matlabinterfaceintroduction 1。软件下载完毕后点击预设字体更改自己需要的页面设置。 2。主页中点击新建脚本。新建的脚本就是当前需要编辑的地方。 3。编辑完成之后按CtrlS进行保存。 4。清除命令行窗口内容,填写CLC即可清除工作区内容,在命令行窗口填写clearall。 1。Afterthesoftwareisdownloaded,clickPresetFonttochangethepagesettingsyouneed。 2。ClickNewScriptonthehomepage。Thenewlycreatedscriptistheplacethatneedstobeeditedcurrently。 3。Afterediting,pressCtrlStosave。 4。Toclearthecontentsofthecommandlinewindow,fillinCLC,clearthecontentsoftheworkarea,andfillinclearallinthecommandlinewindow。 Matlab数据类型 Matlabdatatype 1。字符与字符串 1。Charactersandstrings S’a’’’中间所表示的所有内容即为字符串 Abs(s)表示为每个字符都有其对应的ASCII值 Char()表示字符串 Num2str(65)表示为数字65转换成为’65’ Length(str)表示为字符串长度【其长度包括空格键】 S’a’’’indicateseverythinginthemiddleisastring Abs(s)meansthateachcharacterhasitscorrespondingASCIIvalue Char()representsastring Num2str(65)isexpressedasthenumber65convertedinto’65’ Length(str)isexpressedasthelengthofthestring〔thelengthincludesthespacebar〕 2。矩阵 Matrix 可用A〔123;452;327〕举例 AvailableA〔123;452;327〕example BA’表示矩阵行列将互相变换 BA’matrixrowsandcolumnswillbetransformedintoeachother CA:表示矩阵将竖拉一排【从第一列开始】 CA:Thematrixwillbedrawnverticallyinonerow〔startingfromthefirstcolumn〕 Dinv(A)表示矩阵求逆【非方阵无法求逆】 Ezeros(10,5,3)表示生成十行五列且为三位 的0矩阵命令行窗口中E(:,:,1)即表示一维矩阵 E(:,:,1)rand(10,5) rand生成均匀分布的伪函数,分布在(01) 之间 E(:,:,1)randn(10,5) randn生成标准正态分布的伪随机数(均值为 0,方差为1) E(:,:,1)randi(10,5) randi生成均匀分布的伪随机整数 Dinv(A)Matrixinversion〔Nonsquare matrixcannotbeinverted〕 Ezeros(10,5,3)generatestenrowsand fivecolumnswiththreedigits0E(:,:,1)inthematrixcommandwindowmeansaonedimensionalmatrix E(:,:,1)rand(10,5) randgeneratesauniformlydistributedpseudofunction,distributedin(01) between E(:,:,1)randn(10,5) randngeneratespseudorandomnumbersfromastandardnormaldistribution(themeanis0,varianceis1) E(:,:,1)randi(10,5) Randigeneratesuniformlydistributedpseudorandomintegers 3元胞数组 元胞数组是MATLAB中特有的一种数据类型,是数组的一种,其内部元素可以是属于不同的数据类型,概念理解上,可以认为它和c语言里面的结构体、c里面的对象很类似。元胞数组是matlab中的特色数据类型,它不同于其它数据类型(如字符型,字符数组或者叫字符串,以及一般的算术数据和数组)。它特有的存取数据方法决定了它的特点,它有给人一种查询信息的感觉,可以逐渐追踪一直到所有的变量全部翻译成基本的数据信息。它的class函数输出就是cell。 CellarrayisauniquedatatypeinMATLAB。Itisakindofarray。Itsinternalelementscanbelongtodifferentdatatypes。Intermsofconceptualunderstanding,itcanberegardedasverysimilartothestructureintheClanguageandtheobjectsinC。similar。Cellarrayisacharacteristicdatatypeinmatlab,whichisdifferentfromotherdatatypes(suchascharactertype,characterarrayorstring,andgeneralarithmeticdataandarray)。Itsuniquedataaccessmethoddeterminesitscharacteristics。Itgivespeopleafeelingofqueryinginformation,anditcanbetrackedgraduallyuntilallvariablesaretranslatedintobasicdatainformation。Theoutputofitsclassfunctioniscell。 设置Acell(1,6) SetAcell(1,6) A{2}eye(3)表示生成3x3的对角线数值为1的单位矩阵 A{2}eye(3)generatesa3x3identitymatrixwithadiagonalvalueof1 A{5}magic(5) A{5}magic(5) magic(n)生成一个n阶幻方,就是把1n2排成一个nxn的矩阵,使得矩阵的每行、每列,以及主、副对角线上面的n个数之和都相等(容易证明,这个和等于n(n21)2)。 magic(n)generatesamagicsquareofordern,whichistoarrange1n2intoannxnmatrix,sothatthesumofnnumbersoneachrow,eachcolumn,andthemainandsubdiagonalsofthematrixareequal(Itiseasytoprovethatthissumisequalton(n21)2)。 BA{5}即A{5}赋值给了B BA{5}ieA{5}isassignedtoB 04结构体Structure Booksstruct(’name’,{{MachineLearning’,’DataMining’}},’price’,〔3040〕) ()内的几位结构体,赋值给books Booksstruct(’name’,{{MachineLearning’,’DataMining’}},’price’,〔3040〕) Severalstructuresin(),assignedtobooks Books。name在books中选取name的属性 Books。nameselecttheattributeofnameinbooks Books。name(1) Books。name{1} Matlab矩阵操作 Matlabmatrixoperations 1。矩阵的定义与构造 设置A〔1235;8546〕 Thedefinitionandconstructionofmatrix SetA〔1235;8546〕 B1:2:9 其中1、2分别确定最大值,2为步长 B1:2:9 Amongthem,1and2respectivelydeterminethemaximumvalue,and2isthestepsize Crepmat(B,3,1)重复 Crepmat(B,3,1)repeat Dones(2,4)表示生成一个2行4列且值均为1的矩阵 Generateamatrixwith2rowsand4columnsandthevalueis1 矩阵的四则运算 Fourarithmeticofmatrix 设置A〔1234;5678〕 B〔1122;2211〕 CAB表示对应相加 DAB表示对应相减 EAB’B’表示A乘以B的转置,且需要确保A行数同B列数相同 FA。B表示对应项相乘 GAB可以理解为GBAGBpinv(B)Apinv(B)GApinv(B)即AB的逆 SetA〔1234;5678〕 B〔1122;2211〕 CABmeanscorrespondingaddition DABmeanscorrespondingsubtraction EAB’B’representsthetransposeofAmultipliedbyB,anditisnecessarytoensurethatthenumberofrowsinAisthesameasthenumberofcolumnsinB FA。Bmeansthecorrespondingitemsaremultiplied GABcanbeunderstoodasGBAGBpinv(B)Apinv(B)GApinv(B)istheinverseofAB 矩阵的下标Matrixsubscript 设置Amagic(5)SetAmagic(5) BA(2,3)表示选取第二行,第三列 BA(2,3)meanstoselectthesecondrowandthethirdcolumn CA(3,:)表示选取第三行的所有列 CA(3,:)meanstoselectallthecolumnsinthethirdrow DA(:,4)表示选取所有行的第四列 DA(:,4)meanstoselectthefourthcolumnofallrows 〔m,n〕find(A20)找大于20的序号值矩阵 〔m,n〕find(A20)Findtheserialnumbervaluematrixgreaterthan20 Matlab逻辑与流程控制循环结构 Matlablogicandprocesscontrolloopstructure 在实际问题中,经常会遇到许多有规律的重复运算,因此,在程序设计中,需要将某些语句重复执行一组,被重复执行的语句称为循环体,每循环一次都必须做出是否继续重复执行的决定,这个决定所依据的条件称为循环的终止条件。 Inactualproblems,manyregularrepeatedoperationsareoftenencountered。Therefore,inprogramdesign,certainstatementsneedtobeexecutedrepeatedlyinagroup。Thestatementsthatareexecutedrepeatedlyarecalledloopbodies。Whethertocontinuetorepeatthedecision,theconditiononwhichthisdecisionisbasediscalledtheterminationconditionoftheloop。 Matlab,提供了两种循环结构即for循环结构和while循环结构。 Matlabprovidestwoloopstructures,namelyforloopstructureandwhileloopstructure。 for循环结构 forloopstructure for循环语句允许按照给定的判断范围或给定的循环次数,重复完成一次或多次运算。它从for开始,用end结束。其格式为: for循环变量初值:步长:终值 执行语句1 。。。。 执行语句2 end 步长默认值为1,可省略;初值、步长、终值可以是正数也可以是负数,还可以是整数,也可以是小数,只要符合数字逻辑即可。 Theforloopstatementallowsoneormorecalculationstoberepeatedinaccordancewithagivenjudgmentrangeoragivennumberofloops。Itstartswithforandendswithend。Theformatis: forloopvariableinitialvalue:steplength:finalvalue Executestatement1 。。。。。。。。。。。。。 Executestatement2 end Thedefaultvalueofthesteplengthis1,theinitialvalue,steplength,andfinalvaluecanbepositiveornegative,integer,ordecimal,aslongastheyconformtothedigitallogic。 while循环结构 whileloopstructure Matlab给定此结构,根据给的条件,决定是否以不确定的循环次数来执行循环语句体,基本格式为: while条件表达式 执行语句1 。。。。。。 执行语句n end 其执行方式为若条件表达式中的条件成立,则执行循环语句,如果表达式不成立,则执行end后面的语句。 Giventhisstructure,Matlabdecideswhethertoexecutetheloopstatementbodywithanindeterminatenumberofloopsbasedonthegivenconditions。Thebasicformatis: whileconditionalexpression Executestatement1 。。。。。。。。。。。。。。。。。 Executestatementn end Theexecutionmethodisthatiftheconditionintheconditionalexpressionisestablished,theloopstatementisexecuted,andiftheexpressionisnotestablished,thestatementafterendisexecuted。 分支结构Branchstructure 1。if。。。end结构 if。。。endstructure if条件表达式 。。。 语句体 。。。 end 该结构只有一个判断语句,当条件表达式为真实,就执行与具体,如果条件表达式为假,则跳出条件题而直接执行end后面的语句 ifconditionalexpression 。。。 Sentencebody 。。。 end Thisstructurehasonlyonejudgmentstatement。Whentheconditionalexpressionistrue,itisexecutedandspecific。Iftheconditionalexpressionisfalse,theconditionalquestionisjumpedoutandthestatementafterendisexecuteddirectly 2。if。。。else。。。end结构 if。。。else。。。endstructure if表达式 语句体1 else 语句体2 end 此时如果表达式为真,则系统将执行语句体1,如果表达式为假,则系统将执行语句体2。 ifexpression Statementbody1 else Statementbody2 end Atthistime,iftheexpressionistrue,thesystemwillexecuteandspecificone,iftheexpressionisfalse,thesystemwillexecutestatementbody2 3。switch。。。case。。。end结构 switch。。。case。。。endstructure switch。。case。。。end结构是通过与某个表达式的值进行比较,根据比较的结果做不同的选择,以实现程序的分支功能,它的结构格式为: switch表达式(数值或字符串) case数值或字符串1 语句体1; case数值或字符串2 语句体2; 。。。 otherwise 语句体n; end switch后面表达式的值为数值变量或字符变量,通过这些值与case后面数值或字符串的值进行比较,与哪一个case的值相同就执行哪一个case下面的语句体,如果与所有case的值都不相同,则执行otherwise下面的语句体。otherwise语句可以省略,如果省略otherwise,所有case都不满足时跳出分支结构,另外switch必须与end配对使用。 Theswitch。。case。。。endstructureistocomparewiththevalueofacertainexpressionandmakedifferentchoicesaccordingtotheresultofthecomparisontorealizethebranchfunctionoftheprogram。Itsstructureformatis: switchexpression(numberorstring) casevalueorstring1 Sentencebody1; casevalueorstring2 Sentencebody2; 。。。 otherwise S end Thevalueoftheexpressionafterswitchisanumericvariableoracharactervariable。Bycomparingthesevalueswiththenumericvalueorstringvalueafterthecase,thestatementbodyunderwhichcaseisexecutedifthevalueofwhichcaseisthesameasthatofallcasesIfthevaluesarenotthesame,thestatementbodybelowotherwiseisexecuted。Theotherwisestatementcanbeomitted。Iftheotherwiseisomitted,thebranchstructurewillbejumpedoutwhenallthecasesarenotsatisfied。Inaddition,theswitchmustbepairedwithend。