还剩90页未读,继续阅读
本资源只提供10页预览,全部文档请下载后查看!喜欢就下载吧,查找使用更方便
文本内容:
__TLAB讲义第一章__TLAB系统概述
1.1__TLAB系统概述__TLAB(__TrixLABoratory)矩阵实验室的缩写,全部用C语言编写特点
(1)以复数矩阵作为基本编程单元,矩阵运算如同其它高级语言中的语言变量操作一样方便,而且矩阵无需定义即可采用
(2)语句书写简单
(3)语句功能强大
(4)有丰富的图形功能如plotplot3语句等
(5)提供了许多面向应用问题求解的工具箱函数目前,有20多个工具箱函数,如__处理、图像处理、控制系统、系统识别、最优化、神经网络的模糊系统等
(6)易扩充
1.2__TLAB系统组成
(1)__TLAB语言__TLAB语言是高级的矩阵、矢量语言,具有控制流向语句、函数、数据结构、输入输出等功能同时__TLAB又具有面向对象编程特色__TLAB语言包括运算符和特殊字符、编程语言结构、字符串、文件输入/输出、时间和日期、数据类型和结构等部分
(2)__环境__TLAB__环境有一系列的工具和功能体,其中大部分具有图形用户界面,包括__TLAB桌面、命令窗口、命令历史窗口、帮助游览器、工作空间、文件和搜索路径等
(3)图形处理图形处理包括二维、三维数据可视化,图像处理、模拟、图形表示等图形命令还包括低级的图形命令,供用户自由制作、控制图形特性之用
(4)数学函数库有求和、正弦、余弦等基本函数到矩阵求逆、求矩阵特征值和特征矢量等__TLAB数学函数库可分为基本矩阵和操作、基本数学函数、特殊化数学函数、线性矩阵函数、数学分析和付里叶变换、多项式和二重函数等
(5)__TLAB应用程序接口(API)__TLAB程序可以和C/C++语言及FORTRAN程序结合起来,可将以前编写的C/C++、FORTRAN语言程序移植到__TLAB中
1.3__TLAB的应用范围包括__TLAB的典型应用包括数学计算算法__建模、仿真和演算数据分析和可视化科学与工程绘图应用__(包括建立图形用户界面)以矩阵为基本对象第二章__tlab基础
2.1__TLAB快速入门
(1)搜索路径搜索路径也被看作是__TLAB的路径,其包含的文件被认为在路径上搜索路径设置存放在文件pathdef.m中,称为当前目录,当要在__TLAB中打开一个文件时,就以当前目录为开始点当输入一变量value时,__TLAB的搜索路径次序value是否为变量value是否为内部函数当前目录中是否存在value.m文件搜索路径上是否存在value.m文件path函数可以控制__TLAB的目录搜索路径,主要使用的格式path显示当前的搜索路径p=path把当前的搜索路径存到字符变量P中pathnewpath设置路径为newpathpathpathnewpath向当前路径添加一个新目录addpath函数向__TLAB的搜索目录中添加一个新目录addpath路径名pathpath’路径名’增加搜索路径rmpath函数从__TLAB的搜索路径删除一个目录rmpath路径名删除路径还可以利用菜单File-setpath(路径浏览器)what显示出搜索路径上的文件名what路径名路径名中的文件名typevalue显示变量内容edit文件名对m文件进行编辑
(2)工作空间(Workspa__)工作空间是一个重要而且比较抽象的概念,它是指运行__TLAB程序或命令所生成和存储在内存中的所有变量和__TLAB提供的常量构成的__通过使用函数、运行M文件和装载保存的工作空间,可以向工作空间增加变量s__e保存整个工作空间或一部分变量,使用方式s__eworkspa__as文件名或s__e文件名[变量名]load恢复工作空间,使用方式loadworkspa__load文件名工作空间浏览器File-ShowWorkspa__还有一组命令来管理这些变量whowhos显示出工作空间中的变量列表clear[变量名]清除变量
(3)__TLAB命令窗口输入命令和输出结果如输入help[函数名]a=
62.2矩阵、变量、运算和表达式
(1)矩阵的输入A.直接输入注意
(1)行元素间用空格或逗号(,)隔开;
(2)行与行之间用分号(;)或回车;
(3)整个元素列表用[]括起直接输入的矩阵为一全局变量,一直保存在内存中例a=[123;456]a=123456a=[123;456;789]a=[123;456;789]矩阵元素可以灵活地描述矩阵元素,矩阵元素a[ij]按列存放通过下标单独对元素赋值例a11=1a32=a11得到a=1a=100001即自动形成一个3行2列矩阵,对未赋值的元素充值0矩阵的元素可以用任意形式的表达式例算术表达式x=[-1sqrt52+7^4]x=
1.0e+003*-
0.
00100.
00226.5610大矩阵可以用小矩阵作为元素例a=[12;34]b=[aa+5;a-5zerossizea]例A=[123;456]A=123456B=[A;789]B=123456789可以从矩阵中抽取某些元素构成新矩阵C=A1:2:C=123456例a=[345;678]b=[+24*56]c=[sin
0.5*pisqrt40]d=[a;b;c]复数的表示__TLAB支持复数的运算,复数的虚部用i或j表示例a=1+2i或a=1+2j二者表示的结果一样复数可以直接运算,例a=3+4i;b=5+6ja+b输出ans=
8.0000+
10.0000i复数运算的一些常用函数
①abs返回复数的模
②angle返回复数的相角
③conj返回共轭复数
④i__g返回复数的实部
⑤real返回复数的虚部B.用语句或函数产生a=randn55产生正态分布5*5的随机矩阵C.用M-文件或外部数据文件产生M-文件是一个以.m为后缀的文本文件,文件内容为一系列__TLAB命令,在__TLAB环境下键入该文件名(不包括后缀),文件中的全部命令会依次逐个执行;M-文件名(不包括后缀)相当于一个宏命令.例如一个名为__gik.m的文件包含了如下的内容,(假设__gik.m在当前目录下)A=[
16.
03.
02.
013.
05.
010.
011.
08.
09.
06.
07.
012.
04.
015.
014.
01.0]在__tlab环境下执行如下命令__gikAA=16321351011896712415141D.用矩阵编辑器创建和修改矩阵使用File-Showworkspa__
(2)矩阵运算运算符+,-,*,/右除,\左除和^幂右除C=A/B即C满足CB=A,当B可逆时,A/B=AB-1左除C=A\B即C满足AC=B,当A可逆时,A\B=A-1B幂A^n=A*…*A;A必须是方阵例矩阵的加减法a=[1:3;4:6;7:9]b=a;c=a+b;c=a-b注矩阵相加减必须有相同的维数例矩阵的点乘运算,^运算时矩阵必须为方阵,且只能与数字运算d=a*b必须符合m*n与n*l的结构d=a.*b矩阵的点乘运算例\左除A\B=invA*B其中invA表示A逆阵,例如求解AX=BA=[100;040;009];B=[123;010;011];X=A\B/右除:A/B=A*invB例如求解XA=BX=B/A3变量与表达式__tlab的赋值语句有两种形式:其一为变量=表达式;其二为表达式,将表达式的值赋于一个自动定义的变量ans注A如果以;结尾,则不显示计算结果,否则显示计算结果B除保留字外,变量可以用字母开头,后跟19个字母或数字变量名区分大小写,变量使用时不需要先定义,也不必定义变量的类型可以用who或whos来显示已定义的变量例如whoYourvariablesare:ABCaanswhosNameSizeBytesClassA2x348doublearrayB3x372doublearrayC2x348doublearraya3x248doublearrayans1x18doublearrayGrandtotalis28elementsusing224bytes一些常用的变量pi
3.14159265//π值isqrt-1//虚数单位jsameasiepsfloating-pointrelativeprecision
2.2204e-016//容量变量realmin__allestfloating-pointnumber
2.2251e-308//最小浮点数real__xlargestfloating-pointnumber
1.7977e+308//最大浮点数infinfinity任意一个非零数除以0//正无穷大nanNot-a-number(0/0或inf-inf)//非数如r=1/0r=inf1/rans=04矩阵的其他简单运算:A’:矩阵转置invA A-1sumA得到一个行向量,其元素为A的每一列的和a=[123;456]sumasuma’diagA得到一个列向量,其元素为A的对角元sumdiaga冒号:运算符a:b:c生成一个由等差数列构成的行向量X,Xi+1-Xi=b例0:pi/4:pians=
00.
78541.
57082.
35623.1416如果省略b,则等差数列的公差为1a=0:
0.05:1x=linspa__0175a=1:4;b=1:2:7;c=[ba]等比数列logspa__0211创建起点为10,终点为102,11个元素,公比为
100.2矩阵的变换rot90:矩阵逆时针旋转n*90度fliplr:矩阵左右翻转flipud:矩阵上下翻转稀疏矩阵的存储sparseA:用于把完全矩阵压缩为稀疏矩阵A=[0,1,0,0;0,3,0,4;5,0,0,0;0,0,0,7]sparseAans=315121223244447sparseiju:函数直接造成稀疏矩阵,ij为向量分别对应行号和列号,u也为向量,存储非元素的值.i=
[12234]j=
[22414]u=
[13457]A=sparseijufull函数把稀疏矩阵还原为完全矩阵5数组及其运算数组可以看作是行向量,实质为阵列运算是元素对元素的运算,用句号(.)来区别数组和矩阵之间的区别在于运算规则不同,矩阵运算由线性代数规则来定义运算符+-和.*./.\.^A.*B A与B对应的元素相乘A.\B B的元素除以A的相应元素A./B:A的元素除以B的相应元素A.^B:A的元素为底,B的相应元素为幂的数组如a=[1:3;4:6;7:9]b=a;c=a+b;c=a-b查看下列运算的结果a*ba.*ba/ba./ba\ba.\ba^b指数和底数均为矩阵,无法求解a.^ba’a.’
2.3基本数学函数abs(绝对值或复数模)sqrt(平方根)real(复数的实部)i__g(复数的虚部)conj(复数的共轭)round(舍入为最接近的整数)//round-
0.5=-1round
0.4=0fix(向0方向舍入为整数)//fix
0.99=0fix
1.01=1floor(向负无穷大舍入为整数)//floor-
0.5=-1floor
0.5=0__il(向正无穷大舍入为整数)//__il-
0.5=0__il
0.6=1sign(符号函数)rem(xy)(取余数函数)//得到x/y的余数,rem114=3sincostanasinatan//三角函数都是面向阵列中的元素操作,角度单位均为弦度atan2yx//-pi=atan2yx=pisinh(双曲正弦)coshtanhexp(以e为底的指数)log(自然对数)log10(常用对数)bessel(贝塞尔函数)gam__(伽码函数)rat(无理数的分式有理逼近)[ND]=ratxtol要求absx-N/D=tol*absxtol的缺省值为tol=
1.e-6*normX:1其中normX:1=__xsumabsX
2.4关于矩阵的一些有用的工具产生矩阵的工具:‘[]’表示空矩阵空矩阵不包含任何元素,它的维数为0*0;空矩阵可以在运算中传递例A=[1,2,3;4,5,6;7,8,9]A(2,)=[]输出A=123789空矩阵有矩阵缩维的作用eye:单位矩阵对角线元素为1A=eye33A=100010001zeros所有的元素都是0Z=zeros24Z=00000000ones所有的元素都是1Z=5*ones33Z=555555555rand矩阵元素是用均匀分布在[
0.
01.0]内产生的随机数randn产生一个n阶(0-1)的随机矩阵Z=rand3Z=
0.
10940.
65990.
17850.
98880.
35140.
35730.___
00.
84950.5347randmn:产生一个m*n阶(0-1)的随机矩阵Z=rand16Z=
0.
59760.
46280.
76780.
59020.
39690.1927产生[-aa]之间均匀分布的随机数的公式R=a-2*a*randmnrandn矩阵元素是用期望为0方差为1的正态分布产生的随机数Z=randn3Z=-
0.
43260.
28771.1__2-
1.6656-
1.1465-
0.
03760.
12531.
19090.3273产生均值为b方差为q2的正态分布随机数的公式S=q*randnmn+b其它特殊矩阵例a=[123;456;789]1.diaga%%生成矩阵a的对角矩阵ans=1592.compan:伴随矩阵例u=[10-76]A=companuA=07-6100010eigcompanuans=-
3.
00002.
00001.0000即方程的根3.__gic:魔方矩阵(矩阵的元素由1~10组成,行、列和对角线之和相等)例__gic5ans=172418152357141646132022101219213111825294.trila%%生成矩阵a的下三角矩阵ans=1004507895.triua%%生成矩阵a的上三角矩阵ans=123056009注
1.下标引用在__tlab中,矩阵元素的引用可用两个下标来表示如矩阵A中,第i行第j列的元素用Aij引用,也可以用一个下标来表示,用单个下标表示元素并不只限于矢量对于矩阵,由于__tlab的运算基本上都是对列操作的,矩阵可以认为是按列优先排列的一个长的列矢量,从而可用单下标引用例如2*2的矩阵,A1表示第一列的第一个元素,A2表示第一列的第二个元素,A3表示第二列的第一个元素,A4表示第二列的第二个元素,当矩阵的下标超出矩阵的实际元素的下标时,将给出错误信息但是,当某个值被赋给矩阵的一个新的元素时,__tlab会自动增加矩阵的维数大小例如4*4的矩阵A,执行命令A45=17后,矩阵A将变成4*5的矩阵在下标的表达式里使用冒号表示矩阵的一部分例如矩阵A1:kj表示矩阵A的第j列的前k个元素例如suma1:44,表示计算第四列的前四个元素元素的和A:j表示矩阵A的第j列的所有元素由于有了冒号运算符,例如求矩阵A的第j列元素之和,表示式为sumA:j2.如何建立__矩阵在科学研究与工程运算中,要建立__矩阵,方法之一是扩展二维矩阵例先建立一个简单的二维矩阵a=[578;019;436]为a矩阵扩展第三维a::2=[104;356;987]方法之二,使用cat函数它将现有的矩阵按照指定的维数建立新的__矩阵B=catdimA1A
2...例:b=cat3[28;05][13;79]
2.5复杂的矩阵运算一些矩阵运算sizeA得到矩阵的阶,得到矩阵的n行m列.rankA得到矩阵的秩detA行列式eigA特征值和特征向量e=eigA得到特征值[vd]=eigA:A*v=v*dsvdA矩阵的奇异值分解[usv]=svdAuv正交阵,s对角阵,A=usv’condA得到矩阵的条件数(最大奇异值和最小奇异值的比值)luA:LU分解(A必须是一个方阵)[lu]=luA u上三角阵,l一个下三角阵和一个置换矩阵的积[lup]=luA u上三角阵,l下三角阵,p置换矩阵qrA QR分解[qr]=qrA r上三角阵,q正交阵
2.6矩阵输出格式格式命令(数字)X=[4/
31.2345e-6];for__tshort以定点数形式显示,小数后面保留4位有效数字XX=
1.
33330.0000for__tshorte以浮点数形式显示小数后面保留4位有效数字XX=
1.3333e+
0001.2345e-006for__tshortg以定点数或浮点数的最佳形式显示,小数后面保留4位有效数字XX=
1.
33331.2345e-006for__tlong以定点数形式显示,小数后面保留14位有效数字XX=
1.
333333333333330.00000123450000for__tlonge以浮点数形式显示,小数后面保留14位有效数字XX=
1.333333333333333e+
0001.234500000000000e-006for__tlongg以定点数或浮点数的最佳形式显示,小数后面保留14位有效数字XX=
1.
333333333333331.2345e-006for__tbank以货币方式显示XX=
1.
330.00for__trat用有理数近似表示XX=4/31/810045for__thex用16进制表示XX=3ff55555555555553eb4b6231abfd271for__tcompact以紧凑形式显示(for__tloose以松散形式显示)XX=3ff55555555555553eb4b6231abfd271长命令行用“…”来表示连接第三章图形在分析问题的结果的时候,图形往往是一种很有用的工具,它可以帮助我们直观地了解结果的某些性态__tlab提供了很强的图形功能,能够在根据向量或矩阵给定数据来生成图形__tlab图形有数据可视化和图形处理两大功能,在数据的可视化部分,__tlab可使用户计算所得的数据根据其不同情况转化成相应的图形用户可以选择直角坐标、极坐标等不同的坐标系;它可以表现出平面曲线、空间曲线,绘制直方图、向量图、柱状图及空间网状面图、空间表面图等图形函数有4种通用图形函数、二维图形函数、三维图形函数、特殊图形函数.建立一个图形的步骤步骤典型代码1)准备数据x=0:
0.2:12y1=bessel1x;y2=bessel2x;y3=bessel3x;2选择窗口,决定绘图位置figure1subplot2213调用基本绘图函数h=plotxy1xy2xy3;4)设置绘图线条样式和标记sethLineWidth2{LineStyle}...{--;:;-.}seth{Color}{r;g;b}5)设置坐标轴范围、刻度和栅格线axis[012-
0.51]gridon6)标记图形坐标轴、图形图例以及其它文字xlableTimeylableAmplitudelegendhFirstSecondThirdtitleBesselFunctions[yix]=miny1;textxixyFirstMin\rightarrow...HoizontalAlig__entright7)打印图形print-dps
23.1图形窗口图形窗口(FigureWindow)是所有__tlab的图形输出的专用窗口figure:用来打开一个绘图窗口,以供后续绘图命令输出图形创建图形窗口的命令figure两种格式figurefiguren图形窗口的名称是按照该窗口创建的时间顺序依次命名的FigureNo.1FigureNo.
2.....FigureNo.n命令figure将创建一个名为figureNo.n+1的新的空白图形窗口,而figuren命令则若figureNo.n窗口已存在,则成为当前窗口h=figuren可得到图形窗口的句柄两个查阅图形参数和参数值的命令getn getn将返回关于图形窗口FigureNo.n的所有图像参数的名称和当前值setn setn将返回关于图形窗口FigureNo.n的所有图像参数的名称和其可能取的值
3.2创建二维图形(Plot函数)Plot是最简单而且使用最广泛的一个线型绘图函数,是__tlab的内部函数作用可以生成线段、曲线和参数方程曲线图形几种基本命令形式1向量式plotv参数v可以是向量、实数阵和复数阵v是长度为n的数值向量,生成ivi的一条折线,坐标轴的范围由__TLAB系统根据向量的长度元素的大小自动生成,当向量的元素充分多时,即可以得到一条外观光滑的曲线例x=0:pi/20:2*pi;plotx例x=peaks;plotx2参数式plotxyxy都是长度为n的向量,它的作用是在坐标系中生成顺序连接顶点{xiyi}的折线,绘得的连线图以x为横坐标,y为纵坐标这种调用可以用来生成参数方程的图形例y=sinx;plotxy例x1=0:1:10*pi;x2=0:
0.01:10*pi;y1=sinx
1.*x1;y2=sinx
2.*x2;plotx1y1holdonplotx2y2
(3)矩阵式plotyy是一个m*n和矩阵,为矩阵的每一列画出一条线同时以矩阵的行向量为基准对x轴进行分度和标注,标准时,采用向量1:m,这里m中矩阵的行数例z=peaks;%%产生一个49*49的矩阵plotz
(4)混合式plotxy如果XY均为向量,则长度必须相等,亦即参数式;如果X是向量,而Y是一个矩阵,X的长度与矩阵Y的行数或列数相等,则它的作用是将向量X与矩阵Y的每列或每行的向量相对应作折(曲)线,当Y是方阵时,则将向量X与矩阵Y的列向量相对应作图;如果X是矩阵,Y是向量,Y的长度等于X的行数或列数,则将X的每列或每行的向量与Y相对应作图同样,当X是方阵时,则将X的各列与Y相对应作图;如果X和Y都是矩阵,且维数相同,那么按列与列的对应方式来作图例y=1:lengthpeaks;plotpeaksy
(5)复向量式plotzz为复向量,会忽略向量的虚部,相当于plotrealzi__gz例:随机矩阵特征值分布ploteigreal2020’o’’__rkersize’6
(6)综合调用plotx1y1x2y
2...矩阵中有多个矩阵调用对,其中的每一对按前四种方式之一进行调用,不同的矩阵对之间,其维数可以不同例t=0:pi/10:2*pi;y1=sint;plotty1;可以使用plot同时显示由若干个x-y对表示的图形y2=sint-
0.5;y3=sint-
0.25;plotty1ty2ty3;从图上我们可以看出,为了体现不同x-y对表示的图形,__tlab自动地使用了不同的颜色;此外我们还可以使用如下格式来设置图形的性态
3.3线型、顶点标记和颜色在调用plot函数时__TLAB自动安排作图的线型的线段的颜色,包括线段顶点的标记事实上,__TLAB的plot函数可以设置和管理曲线的线段类型、顶点标记和颜色(在__TLAB中,它们通称为线型LineStyle)__TLAB定义的线段类型、顶点标记和线段颜色如下表颜色(color)线型顶点标记style顶点标记__rker类型符号类型符号类型符号黄色y实线-实点标记.洋红色m点线:圆圈标记O蛋青色c点虚线-.乘号标记XX红色r虚线--加号标记++绿色g星号标记**蓝色b方块标记□s白色w钻石形标记◇d黑色k向下的三角形标记V向上的三角形标记^向左的三角形标记向右的三角形标记五角星标记☆p六边形标记h注
1.连接节点的线型如果空缺则表示点与点之间没有直线相连;2.如果不指定作图的颜色,自动循环使用ymcrgbw7种颜色画线plot的最典型的调用方式是三元组参数plotxy’color-style-__rker’例plottyb+ty2k-Xty3r--*例[xyz]=peaks;//多输出函数,函数可产生多个输出值,输出值之间用逗号分开contourxyz20’k’holdonpcolorxyzshadinginterp其中peaks根据Gauss分布(正态分布)得到3个49阶矩阵contour用相同的颜色画20条等高线,pcolor将xy点上的颜色设置成zshadinginterp设置渲染方式,例x=0:
0.25:5;y1=x.^
0.1;y2=x.^
0.5;y3=x.^
0.8;y4=x;y5=x.^
1.5;y6=x.^2;y7=cosx;y8=sinx;holdonplotxy1’yo’xy2’mx’xy3’c+’xy4’rs’;plotxy5’gh’xy6’bd’xy7’w’xy8’kp’;
3.4subplot函数在一个已存在图形的绘图窗口中增加一个图形在这之前讲的都是覆盖方式holdon,加到图形上,holdoff则取代当前窗口允许在同一绘图窗口中显示或在同一纸上打印多个图形subplotmnp将一个绘图窗口分割成m*n个子窗口,每一小块有自己的坐标轴,p为活动窗口,并且在p个窗口绘制当前图形,如果坐标系已存在,则subplotp设置当前坐标系例如t=0:pi/10:2*pi;[xyz]=cylinder4*cost;%%生成一个单位圆柱体,采用[0,1]之间的等距节点,每一个节点的旋转半径是4*cost相当于4*cost母线CYLINDERRNCYLINDERR此时n=20subplot221;meshx%%x=1:my=1:nz=xc=xsubplot222;meshy;subplot223;meshz;subplot224;meshxyzsubplot111是个特殊的情况,与subplot111不同,它使下一条绘图指令在窗口中执行elf和reset指令(即删除当前图形的所有子对象),然后在默认位置创建一个坐标系绘制复数图形plotzplotrealzi__gz例如t=0:pi/10:2*pi;plotexpi*t-o
3.5坐标轴控制axis函数axis函数可控制坐标轴的刻度,使两个图形在对比时,有相同的比例因子也可用于复杂图形的局部透视axis命令的格式axis[xminx__xyminy__x]设置X,Y轴的极限范围axissquare保持X,Y轴axisequal设置X,Y轴等长axisauto设置X,Y轴为自动格式axison显示X,Y轴axisoff关闭X,Y轴gridoff图形网格不显示gridon图形网格显示例复杂函数的局部透视,利用axis函数调整x轴刻度,可以比较清楚地看到某一局部区域x=0:1/3000:1;y=costanpi*x;figure1,subplot211plotxytitle复杂函数subplot212plotxyaxis[
0.
40.6-11];title复杂函数的局部透视例利用axissquare使输出图形的保持xy轴,这样在图形窗口中绘制圆或椭圆都可用圆来表示t=0:pi/20:2*pi;figure1subplot221plotsintcosttitle圆形轨迹subplot222plotsint2*costtitle椭圆形轨迹subplot223plotsintcostaxissquaretitle调节后的圆形轨迹subplot224plotsint2*costaxissquaretitle调节后的椭圆形轨迹坐标标题及图中的文本使用函数xlabel、ylabel、zlabel、text、title说明
(1)xlabel、ylabel、zlabel为xyz轴的标记
(2)text在当前坐标系中建立文本对象格式textxy’string’在图形的xy点上放置指定的字符串text...’PropertyName’’PropertyValue’...为标题文本指定特性特征为∧表示为上标、_为表示下标、\leftarrow表示为←\rightarrow表示为→\it{斜体文字}arrow表示箭头bottom表示上下箭头textxyz’string’在三维图形上放置文字textxy’string’’color’’k’放置文字的同时设置颜色例t=-pi:pi/100:pi;y=sint;plottyaxis[-pipi-11]xlabel-\pi\leq\itt\leq\piylabelsinttitleGraphofthesinefunctiontext1-1/3\it{Notetheoddsymmetry}colorr
(3)gtext与text的不同是可利用鼠标放置文本例t=-pi:pi/20:pi;y1=sint;y2=2*cost;plotyyty1ty2gridontitle双Y轴正弦曲线gtextsinttextpi/20\leftarrow2cost
(4)plotyy双Y轴的图形,同一张图上表示两条曲线时,可拥有各自的Y轴
(5)title给当前坐标系加上标题例在同一张图上绘制出双y轴的y1=sinx和y2=2cosx函数x=-pi:pi/20:pi;y1=sinx;y2=2*cosx;plotyyxy1xy2;gridontitle双y轴正余弦曲线text00\leftarrowsinttextpi/20\leftarrow2cost
3.6专门用于绘制一元函数曲线的命令fplot在plot命令中,系统是将从外部输入或间接确认的数值矩阵转化为连线图的而在实际应用中绘制函数的二维曲线时,一般并不清楚函数的具体情况,因而在确定自变量x的取值间隔时,往往一律用平均间隔,这样往往不大准确取好了,可以表现出函数图像的大概情况,取差了,则会因某处x元素的间隔太大而根本错绘了曲线,不能反映出函数的变化情况从而使绘图失败fplot不是直接从外部接收数据,而是通过其内部自适应算法而产生的即在函数值变化比较平稳处,它所取的数值点就会自动相对稀疏一些,在函数值变化剧烈处,所取有数值点就会自动密集一些所以对于曲线起伏剧烈的函数,用fplot命令将比用一般等间距取点的plot命令绘得的曲线光滑准确一些fplot命令的具体使用格式为fplot‘function_name’limitstol’linespec’p1p
2...[xy]=fplot‘function_name’limitstol’linespec’p1p
2...其中‘function_name’待绘制函数曲线的函数名称limits limits=[xminx__x]为x的取值空间tol为fplot命令在进行运算中的相对误差tol越小,所绘得的曲线就越接近实际曲线的情况,但系统要为此占用很大的资源linepsec:线型设置p1p
2...:函数传递的参数xy输出数据点坐标例fplot与plot命令的比较functiony=funfplotxy=sin
1./tanpi.*x;%%建立一个函数funfplot[XY]=fplot‘funfplot’[-
0.
10.1]2e-4;n=sizeX;x=-
0.1:
0.2/n1+1:
0.1;y=funfplotx;plotxyholdonplotXY
3.7专门用于绘制一元符号函数曲线的命令ezplot如果符号函数中只含有一个变量,那么__tlab将其视为一个普通函数,画出其在某个区域内的图像用ezplot命令格式ezplotsym_functionlimits其中sym_function符号函数或代表它的符号变量limitslimits=[x1x2]为x的取值空间其默认值为[-2pi2pi]ezplotf%%f=fx-2πx2πezplotf[min__x]%%minx__xezplotf[xminx__xyminy__x]%%xminxx__xyminyy__xezplotxyezplotxy[tmint__x]ezplot...figure例
1.ezplot‘x^2-y^4’
2.ezplot‘x^2^sinx^2’
3.8二维特殊图形__TLAB
5.3提供了很多绘制二维图形的指令,如下图函数名称功能area填充的函数折(曲)线图bar直方图barh垂直的直方图bar3三维直方图bar3h垂直的三维直方图comet慧星轨迹状的图形errorbar误差棒图feather沿X轴分布的复数向量图fill平面多边形填色hist向量的统计直方图pareto带有标准的直方图pie饼图pie3三维饼图plot__trix矩阵折(曲)线图ribbon带状图scatter点图(与plot的绘制结果相似,但是只有数据点)stem火柴杆图stairs阶梯图例1用area函数绘制__图area函数将矢量数据或矩阵列矢量数据显示为曲线,并且将曲线与x轴之间的区间填充指定颜色用__图描述某公司1990-1994年销售与利润情况sales=[
51.
682.
490.
859.
147.0];x=90:94;profits=[
19.
334.
61.
450.
529.40];areaxsalesFa__Color[.
5.
9.6]EdgeColorbLinewidth2holdonareaxprofitsfa__color[.
9.
85.7]edgecolorylinewidth2holdoffset__aXtick[90:94];set__aLayertop;gtext\leftarrowsales;gtextprofitsgtextexpensesxlabelyearsfontsize10ylabelSalesin1000sfontsize10__图例Y=[153;327;153;261];areaY gridoncolor__psummerset__aLayertoptitleStackedAreaPlot例2用bar函数绘制向量y的直方图x=0:pi/10:2*pi;y=cosx;bary;%%取Y元素的下标作为X坐标值holdonbarxy’r’;将bar换成barh成垂直的直方图、bar3成三维直方图、bar3h成垂直的三维直方图例3用随机函数rand产生一个矩阵,从而得到复杂的条形图y=roundrand53*10;figure1subplot221bary’group’title‘Group’subplot222bary’stack’title‘Stack’subplot223barhy’stask’title‘Stack’subplot224bary
1.5title‘width=
1.5’例4用errorbarxye绘制误差棒图x=1:10;y=sinx;e=stdy*onessizex;errorbarxye注xye必须是同维;该指令常用于数理统计离散数据有理化例5hist函数可在二维平面上绘制出柱状图,用来表示数据值的分布情况其常用格式histyx并且可以绘制笛卡尔坐标系和极坐标系两种方式分布统计直方图x=-
2.9:
0.1:
2.9;y=randn200001;figure1histyxtitle‘柱状图表示数据分布’用rose绘制12小时的风向图wdir=
[45909045380335360270335270335335];wdir=wdir*pi/180;rosewdir例6pie函数可绘制出饼图,其常用格式为piex,可按向量x中的值的大小绘制出饼图piexexplode可利用explode指定分离出的切片x=[
1.
12.
80.
52.52];explode=
[01000];figure1color__phsvpiexexplodetitle‘饼图’注当x各元素和大于1时,函数对数据进行归一化处理;当各元素和小于1时,函数不对矢量进行归一处理,而只是绘制部分饼图如pie[
0.
10.
20.6]例7对于离散数据,采用stem函数alpha=
0.02;beta=
0.5;t=0:4:200;y=exp-alpha*t.*sinbeta*t;stemtyxlabelTimein\musecs;ylabel__gnitudestem3函数在三维空间描述离散序列th=0:127/128*2*pi;x=costh;y=sinth;f=absfftones101128;stem3xyfdfillview[-6530];stairs函数描述离散序列alpha=
0.01;beta=
0.5;t=0:10;f=exp-alpha*t.*sinbeta*t;stairstf;holdonplottf--*;holdoff
3.9网格和曲面__TLAB具有强大的三维图形处理功能,包括三维数据显示、空间、曲面、分块、填充以及曲面光顺着色、视点变换、旋转、隐藏等功能和操作
(1)plot3xyzLinespecplot3是一个可用来画单变量的三维函数,函数格式除了包括第三维的信息之外,其它与二维函数plot相同例绘制一个三维螺旋线t=0:pi/50:8*pi;figure1plot3sintcosttgridoffaxissquaretitle三维螺旋线例增加维数的plot3命令可以使多个二维图形沿一个轴排列起来,而不是直接将二维图形叠加到另一个的上面下例就是二维图形在三维空间的排列x=linspa__03*pi;z1=sinx;z2=sin2*x;z3=sin3*x;y1=zerossizex;y3=zerossizex;y2=y3/2;plot3xy1z1xy2z2xy3z3;gridxlabel‘x-axis’ylabel‘y-axis’zlabel‘z-axis’title‘sinxsin2xsin3x’2平面网格点的生成在数学上,函数z=fxy的图形是三维空间的曲面,在__TLAB中,总是假设函数z=fxy是定义在一个矩形的区域D=[x0xm]*[y0yn]上的为了绘制在区域D上的三维曲面,__TLAB的方法是首先将[x0xm]在x方向上分成m份,将[y0yn]在y方向分成n份,由各分划点分别作平行于坐标轴的直线,将区域D分成m*n个小矩阵块,计算出在网格点的函数值对于每个小矩形,在空间中决定出4个顶点xiyifxiyi,连接4个顶点得到一个空间中的四边形片所有这些四边形片一起构成函数z=fxy定义在区域D上的空间网格曲面为方便起见,__TLAB中用meshgrid函数产生xy轴向的网格数据,meshgrid函数的一般格式为[XY]=meshgridxy其中,xy分别指向x轴向和y轴向的数据点,当x为n维向量,y为m维向量时,X,Y均为m*n矩阵,Xij和Yij共同指向平面上的一点,当xy轴取同一向量时,可简写成[XY]=meshgridx例数学函数,定义在区域[-88]*[-88]上在生成网格点后,计算网格点上的函数值x=-8:
0.5:8;y=x;[XY]=meshgridxy;R=sqrtX.^2+Y.^2+eps;Z=sinR./R
(3)网格曲面mesh函数mesh函数绘制三维空间上的网格曲面,如上例最后加上meshZ,生成一曲面mesh函数的其它格式为meshXYZ:XYZ为同维数的矩阵meshXYZC C称为颜色矩阵网格曲面的顶点对应于空间的顶点XijYijZij而网格曲面的网格线的颜色由C值根据当前的色谱来着色这种调用形式还可以用来生成参数曲面片meshxyZC:其中,x和y是向量,Z和C是同维数的矩阵,且向量x的长度等于矩阵Z的列数,而向量y的长度等于矩阵Z的行数在这种情况下,网格曲面的曲格顶点是xjyiZij,网格线的长度由矩阵C决定meshZC Z和C都是m*n矩阵,该形式与meshxyZC等价与mesh相关的另外两个函数是meshc和meshz,它们的调用形式与mesh相同meshc函数可同时绘制出轮廓图(即等高线图)meshz的作用除了生成与mesh相同的网和曲面之外,还在曲面下面加上一个长方体的台柱,使图形更加美观例曲面图[xy]=meshgrid-3:.125:3;z=peaksxy;c=onessizez;figure1meshxyzcgridontitle多峰函数的网格曲线例:[xy]=meshgrid-8:
0.5:8;r=sqrtx.^2+y.^2+eps;/*加eps是为了防止出现0/0的情形*/z=sinr./r;meshxyz;例曲面与等高线x=-8:
0.5:8;y=x;[XY]=meshgridxy;R=sqrtX.^2+Y.^2+eps;Z=sinR./Rsubplot221;meshcZsubplot222;meshzZ
3.10实曲面的绘制实曲面就是对网格曲面的网格块(四边形片)区域进行着色的结果__TLAB的函数surf函数可提供这种功能它的调用方式与mesh相同,但mesh仅对网格线着色,网格线用黑色标出(可以修改)而surf是对网格片着色,绘制的是二维曲面例用surf函数表现三维数据k=4;n=2^k-1;theta=pi*-n:2:n/n;phi=pi/2*-n:2:n/n;X=cosphi*costheta;Y=cosphi*sintheta;Z=sinphi*onessizetheta;color__p[000;111];C=hada__rd2^k;surfXYZC;axissquare可以用shading函数来改变着色方式如shadingfa__ted默认的着色方式,网格线为黑色;shadingflat网格线分块着色;shadinginterp光顺性着色网格块的内部像素的颜色由该片的四个顶点的颜色做双线性插值得出例[xy]=meshgrid-3:.125:3;z=peaksxy;c=onessizez;figure1shadingfa__ted%%shadingflat/interpsurfxyzcgridontitle多峰函数的网格曲面surfc函数绘制二维曲面同时还绘制出轮廓图(即等高线图)surfl函数能生成具有光照效应的表面,使图形更加美观同时还可以指定三维坐标系的光源点坐标[x1y1z1],或光源方向的球面坐标值,即经度和纬度(仰角)向量[azimuthelevation]例用surfl指令创建一个图形,其中光源的方向为经度=-10度,纬度=50度surflpeaks200[-1050];color__pgray;shadingflat还有两个与meshc和meshz对应的函数surfc和surfz,这里不再详述
3.11等高线图形__TLAB支持二维和三维等高线图形函数contour和contour3被用来实现这种功能它们将输入的矩阵变量M看作是定义在[1m]*[1n]上的函数,生成若干条常数值的等高线段用户也可以指定等高线的条数、坐标系的比例以及某值上的等高线等高线的线型、顶点标记、颜色类型类似于plot函数定义contour3适用于三维等高线的生成,调用方式与contour相同例二维和三维等高线的生成contourpeaks30%生成二维等高线%contour3peaks20%生成三维等高线
3.12改变视角view函数view改变所有类型的二维和三维图形的图形视角与z=0平面所成的方向角叫仰角,与x=0平面的夹角叫做方位角,默认的三维视角方向仰角为30度,方位角-
37.5为度而默认的二维视角仰角为90度,方位角为0度函数viewazel和view[azel]将视角改变到所指定的方位角az和仰角rl例仰角和方位角的改变x=linspa__03*pi.’z=[sinxsin2*xsin2*x];y=[zerossizexonessizex/2onessizex];%生成矩阵zysubplot221plot3xyzgridonxlabel“X-axis”ylabel“Y-axis”zlabel“z-axis”title‘默认视角方位角=
37.5,仰角=30’view-
37.530%将视角改变到所指定的方位角-
37.5和仰角30subplot222plot3xyzgridonxlabel“X-axis”ylabel“Y-axis”zlabel“z-axis”title‘方位角旋转至
52.5度’view-
37.5+9030%将视角改变到所指定的方位角
52.5和仰角30subplot223plot3xyzgridonxlabel“X-axis”ylabel“Y-axis”zlabel“z-axis”title‘仰角变为60度’view-
37.560%将视角改变到所指定的方位角-
37.5和仰角60subplot224plot3xyzgridonxlabel“X-axis”ylabel“Y-axis”zlabel“z-axis”title‘方位角为0度,仰角为90度’view090%将视角改变到所指定的方位角0和仰角
903.13透视效应hidden__TLAB在绘制图形时,在默认方式下,前面的图形会挡住后面的图形,即消去后面的隐藏线,可用命令hidden改变这种模式命令格式hiddenoffhiddenon例透视图形.subplot121meshpeaks20+7;hiddenonsubplot122meshpeaks20+7;hiddenoff
3.15曲面的裁剪方法因为曲面图不能做成透明,但在一些情况下可以很方便地移走一部分表面以便看到表面下面的部分在__TLAB中,可以将要观察部分的数据置为特定的NaN来实现,由于NaN没有任何值,所有的作图函数都忽略NaN的数据点即将曲面裁剪掉一部分例利用NaN进行曲面裁剪[xyz]=peaks30;x1=x1:;y1=y:1;i=findy
10.8y
11.2;j=findx1-.6x
1.5;zij=nan*zij;surfxyz
3.16四维表现和切片图sli__对于一般的定义在xyz坐标系上的四维可视化,可以用指令sli__来实现为了实现三元函数r=fxyz的可视化表现,__TLAB提供了一个绘制三维物体切片图指令及与之配合的三维网格坐标生成指令[XYZ]=meshgridxyz%三维网格坐标的生成sli__XYZVxiyizin%绘制三维物体切片图其中xyz:决定“网格”的位置,分别是1*n、1*m和1*p向量XYZ:三维网格坐标,它们都是n*m*p维数组V:在网线节点上的三元函数值数组,维数也为n*m*pxiizi:分别决定垂直于xyz轴切面的位置向量它们的维数可以不同当取0维空阵时,表示没有切面存在切片上的函数值的大小可以用色轴上对应的颜色表示V数组中的最大有限值和最小有限值定义了色轴的范围又由于切片的位置可以任意设置,因此sli__通过三维坐标点上的色彩变化把图形的表现能力扩展到四维例函数R=xe-x^2+y^2+z^2的四维表现图.x=-2:
0.1:2;y=-2:
0.25:2;z=-2:
0.25:2;n=lengthx;[XYZ]=meshgridxyz;V=X.*exp-X.^2-Y.^2-Z.^2;xi=[-
0.
70.7];yi=
0.5;zi=-
0.5;sli__XYZVxiyizi;xlabel‘x’;ylabel‘y’;zlabel‘z’;holdoncolorbar‘horiz’%表明颜色与数组的关系view
[3045]
3.17颜色板
(1)数字图象是指将一幅二维的图象表示成一个数值矩阵,矩阵的元素解释为像素的颜色值为了显示由矩阵表示的数字图像将矩阵的每个元素对应到当前色谱的某个行标号,并取该行的颜色值作为图像相应点的颜色
(2)颜色板__p是一个m*3的矩阵,其每行的值在
0.0-
1.0之间,分别表示红、绿、蓝三种颜色,颜色板的每一行定义了一种颜色对应于RGB三元色
(3)两维数组可以用i__ge的形式显示出来,数组中的每一个元素(ij)的值表示该点的颜色或亮度,i__ge用来显求图象包括装入调色板,生成二维图象i__geX表示求生成矩阵X所表求的图像
(4)color__p__p将颜色板设置成__pcolor__p颜色板矩阵简单颜色常用函数查找表函数红绿兰颜色函数名称说明000黑bone蓝色调灰色111白cool青和品红浓淡色100红copper线性变化纯铜色调010绿flag红白蓝黑交错色011青兰gray线性灰度hot黑红黄白色hsv带饱和值的颜色查找表jet颜色查找表的一种变体pink淡粉红色pri__光谱色color__p‘default’将颜色板设置成缺省值.Colorbar在当前的图形上显求一个水平的或的直的颜色标尺.c__p=color__p得到当前使用的颜色板矩阵.color__phsv128产生128种颜色的hsv颜色板hsv的颜色从红、黄、绿、青、兰、洋红再回到红,循环变化在__YLAB中,图像由一个数据矩阵和一个颜色查找表矩阵组成,根据矩阵数据与像素颜色关系的不同,可以将图像分为三种,索引图像、亮度图像和真彩图像索引图像是将数据矩阵的元素视为颜色查找表的索引;亮度图像的数据矩阵的元素为一个亮度值,该值线性对应于颜色查找表的索引;真彩图像的数据矩阵是一个m*n*3的三维矩阵,第三维表示每一个像素点的RGB三色,而不用颜色查找表demo目录中有一个名为durer.__t的文件,其中包含了两个矩阵X__p例人体脊骨的图像loadspinei__geXcolor__pbone;title‘人体脊骨图’例(ex23)%colorflagc__p=color__p;l=lengthc__p;x=[1:l];y=x*onessizex;barx1:2y1:2:color__psummer例hot8从黑色到暗红、洋红、黄色、白色平滑过渡
3.18图形打印和读写print[–devi__][-option]filename打印当前绘图窗口中的图形其中option表示操作方式操作方式-dps单色postscript格式的文件-dpsc彩色postscript格式的文件__TLAB能够读写多种格式的图形文件,包括TIFF、JPEG、BMP、PCX、XWD和HDF格式函数imread能够读取其中任意一种格式的图像文件例RGB=imreadn__6543a.jpg;figureposition[100100sizeRGB2sizeRGB1];i__geRGB;set__aposition
[0011];例loadclownimwriteX__pclown.bmp;
3.19动画制作用__TLAB产生动画序列有二种方法第一种方法是先保存多幅不同的__,然后连续回播;第二种方法是连续不断地擦除并重画屏幕对象,在重画时屏幕对象不断变化,实现动画效果这二种方法各有优缺点前者适于来不及快速重画的场合,它只是回放预先准备的画面后者用到了画、擦、重画技术,适于表现精度不高能够快速重画的场合例1使用moviein函数建立动画图形axisequalm=moviein8;set__anextplotrepla__childrenforj=1:8plotffteyej+8m:j=getframe;endset__anextplotrepla__childrenmoviem10例2:h=uicontrolstylesliderposition...
[105020300]Min1__x16Value1fork=1:16plotffteyek+16axisequalsethValuekMk=getframe__f;end例使用擦除模式绘制动画图形a=[-8/300;0-1010;028-1];y=[35-10-7];h=
0.01;p=plot3y1y2y
3.erasemodenone__rkersize5;axis[050-2525-2525];holdonfori=1:4000a13=y2;a31=-y2;ydot=a*y;y=y+h*ydot;setpXdatay1Ydatay2Zdatay3drawnowi=i+1;end第四章控制流
4.1关系运算__TLIB有六种关系运算符====~=结果1表示true0表示false其中==只用于操作数的实部比较,==~=用于比较实部和虚部A.当两个变量是标量时,a和b的关系成立,结果为1,否则结果为0B.当比较a和b是两个维数相同的数组时,按相同位置比较,结果是一个维数和a相同的数组,其元素由1和0组成C.当比较的一个是数组a,一个是标量b时,则把标量b和数组a的每一个元素按标量关系逐个比较,结果是一个维数和a相同的数组,其元素由1和0组成如a=rand5;b=ac=a==b;c=abc=a1;c=a0;c=a
0.5x=1:10;t=x
54.2逻辑运算|(或)(与)~(非)和逻辑函数or、and、not、xor及any、all、find__TLAB提供三个逻辑操作符、|、~,同时又存在三个相应的M文件all、or、not,这二组的作用是相同的,只是使用格式稍有差异xor是第四个逻辑运算函数,完成异或操作在逻辑操作中,所有输入元素的非零值都当作1处理逻辑运算的优先级最低例x=[25–5;
00.001]~xans=0010y=[10;10]z1=xy;z2=andxy;z3=xorxy;z1=1000z2=1000z3=0111__TLAB还提供了许多测试用的逻辑函数,巧妙地使用这些函数,可得到意想不到的结果any:若作用于一向量x,则当x中至少有一个非零元素时返回1,否则返回0,若x是矩阵,则对每一列执行any返回一个元素为0或1的向量主要作用测试矩阵中是否有非零元素如a=rand15anya=11111all:测试向量,若向量的所有元素非零,返回1,否则返回0,若对矩阵则对每一列执行all操作主要作用测定矩阵中是否有零元素allat=~x5例ex
24.mx=linspa__05100//产生0~5之间均匀分布的100个数据y=cosxz=y
0.*y//将cos函数的负数置为0z=z+
0.3*y0//将cos函数的正数值增加30%z=x=
4.*z//将超过4时的z值置为0plotxzfind:找出矩阵中非零元素及其下标例a=zeros520;a37=
0.5;a415=-
0.4;[ijv]=findai=34j=715v=
0.5000-
0.4000运算符的优先级在一个表达式内可能有几个运算符__TLAB为确定运算的次序设定了运算符的优先级在同一优先级时,程序先左后右执行,在优先级不同时,先高级后低级执行最高()~(取反)..^+-.*./.\*/\+-:==++~=-最低|
4.3ifelseelseifend语句if语句的格式if逻辑表达式语句集elseif逻辑表达式语句集else语句集end仅由if和end组成的语句,可根据逻辑表达式的值选择是否执行例ifrema2=0disp’aiseven’b=a/2end例ifxdisp‘矩阵x全为0’elsedisp‘矩阵x不全为0’end例ifanda==1b
5......endif是__TLAB中最常用的条件执行语句,它与end语句一起构成各种格式,
4.4.for-end循环for循环指定次数的重复循环执行语句格式for循环参数=初态:步长:终态循环体end当步长=1时,步长可以省略例n=4;fori=1:nforj=1:nifi==jaij=2;elseifmin[ij]==1aij=1;elseaij=0;endendenddisp‘The__trixAis’;dispa执行时The__trixAis2111120010201002例(test
1.m)fori=1:mforj=1:naij=1/i+j-1;endend例fori=
9.8:3:-9iend执行时i=
9.800i=
6.
8003.800i=
0.800i=-
2.200i=-
5.200i=-
8.200例s=’abcdefghijk’fori=siend%i分别等于s中和每一个字符例c={‘aaa’’bbb’’ccc’}fori=ciendi=’aaa’i=’bbb’i=’ccc’例:在循环中可以改变循环变量的值但它不会改变循环的次数.r=1fork=1:19k=k+1;r=r*k;end例可利用数组阵列任意指定循环变是的值.ex
25.mvarx=
[73105];vary=zerossizev;k=0;forx=varxk=k+1varyk=x.^2;enddisp[vw]例(ex
31.m)求100-200之间的素数form=101:2:200k=fixsqrtm;fori=2:k+1ifremmi==0break;endendifi=k+1dispmendend
4.5while-end循环不定次数重复的循环执行语句格式while逻辑表达式循环体end例求1000以下的菲波纳契数ex
26.mf=
[11];i=1;whilefi+fi+11000fi+2=fi+fi+1;i=i+1;end例a=150;whilea
0.1a=a/2;end
4.6switch-end语句情况切换语句,case语句中可以采用多个值语句格式switch变量或表达式casev1语句casev2语句.......otherwise语句end例switchremn4==0+remn2==0case
0......case
1......case
2......otherwiseerrorThisisimpossibleend例switchvar2case{-2-1}disp‘var2isnegativeoneortwo’case{123}......otherwisedisp‘var2isothervalue’end
4.7break语句一个跳出循环的命令导致最内层的whileforif语句终止例(test
3.m)a=0;fa=-inf;b=3;fb=inf;whileb-aeps*bx=a+b/2;fx=x^3-2*x-5;iffx==0breakelseifsignfx==signfaa=x;fa=fx;elseb=x;fb=fx;endendx
4.8try..catch语句用于捕获程序运行中出现的错误,语法如下try语句...语句catch语句...语句end在正常情况下,程序只执行try和catch之间的语句,在执行上述语句发生错误时,程序将执行catch和end之间的语句,在这里可以利用lasterr获得错误信息进行处理,如再发生错误,除非嵌套了另一个try...catch,否则程序将中断执行
4.9return语句return语句终止当前的命令序列,把控制返回到调用函数或键盘
4.10输入/输出语句获得用户输入input显示一段信息,并读取用户输入语法x=input提示信息输入类型,缺省为double型例a=input‘Pleaseinputamember’a=input‘Pleaseinputachar’’s’暂停执行,等待用户按键pause:程序暂停执行语法pausenpause其中n为暂停的秒数建立完整的图形界面菜单输入函数menu例(ex
27.m)s=menucolorselectionredgreedblueyellowblackswitchscase1scolor=red;case2scolor=green;case3scolor=blue;case4scolor=yellow;case5scolor=blue;otherwisedisperror;endscolor运行结果输出函数printprintopt
4.11自定义函数用M函数自定义函数,函数M文件必须以函数的名称来作为文件名,M文件的格式如下因变量=函数名自变量自变量和因变量都可以是矩阵或几个矩阵M文件的第一行包括function该文件就是函数文件,函数和命令文件的区别是命令文件的变量用完后保存在内存,而函数文件文件__义的量仅在函数文件内部起作用函数文件有多个输出变量时,用[]括起,有多个输出变量时,用()括起例quroot.mfunctionx=qurootaifabsa1epsd=a2^2-4*a1*a3;ifd=0e=sqrtd;f=2*a1;x1=-a2+e/f;x2=-a2-e/f;endelseifabsa2epsx=-a3/a2;elseerrorcoefficienterror!end函数调用为a=
[121]x=qurootax=-1-1/*子函数调用*/function[meanstdev]=statxn=lengthx;mean=__gxn;stdev=sqrtsumx-__gxn.^2/n;functionmean=__gxnmean=sumx/n;在函数文件中可以包含多个函数,其中第一个函数称为主函数,其函数名与文件名相同,它可以由其它文件引用,其它函数称为子函数,它只能由函数中的主函数和其它子函数引用函数中有两个永久变量narginnargout表示引用函数时给出的输入变量数和输出变量数functionc=testrg1abifnargin==1c=a.^2;elsenargin==2c=a*b;end输入一个变量时,计算这一变量的平方数输入二个变量时,计算这两个变量的积函数的递归调用在调用一个函数的过程中又出现直接或间接地调用该函数本身例求n!(ex
33.m)functiony=ex33n%%求n!ifn0errornis__allerthem0returnendifn==0|n==1y=1elsey=n*ex33n-1;end
4.12全局变量局部变量和全局变量函数工作空间中,变量有三类
(1)由调用函数传递输入和输出数据的变量;
(2)在函数内部临时产生的变量(局部变量);
(3)由调用函数空间,基本工作空间或其它函数工作空间提供的全局变量global让不同的函数访问同一个变量只要在函数中global变量名;%%该变量为全局变量functionh=fallingtglobalGR__ITYh=1/2*GR__ITY*t.^2;例(ex
28.m)对于函数z=αx-12+βy+12编写相应的函数文件,其中α和β采用全局变量进行参数传递globalalphabetax=[0:
0.02:2];y=[-2:
0.02:0];[XY]=meshgridxy;subplot221;alpha=1;beta=1;z=fun1XY;meshz;subplot222;alpha=2;beta=1;z=fun1XY;meshzsubplot223;alpha=1;beta=2;z=fun1XY;meshzsubplot224;alpha=
0.8;beta=
0.5;z=fun1XY;meshzfunctionz=fun1xyglobalalphabetaz=alpha*X-
1.^2+beta*Y+
1.^
24.13命令/函数的双重性在使用__tlab命令时,我们一般使用如下的格式命令参数例如loadAugust
17.dathelpmesh有时我们也可以使用如下的方式load‘August
17.dat’help‘mesh’这就是__tlab中的命令/函数双重性,即命令参数也可以写成函数形式命令(’参数’)从下面的例子里我们可以看出这种写法的好处例有一批数据文件,文件名分别为August
1.datAugust
2.dat......august
31.dat.希望分别对这些文件做相应的处理fori=1:31s=[‘August’int2stri‘.dat’]loads%pro__ssthecontentsoftheithfileend注int2str为把数值变换为字符串
4.14执行字符串命令eval函数eval是一个非常有用的函数,相当于一个命令解释器,能够解释一个字符串表达式,即计算以字符串表示__tlab表达式形式为
1.eval‘表达式’计算出表达式的值
2.[a1a
2....an]=eval‘表达式’当表达式可产生多个结果时,分别存入a1a
2....an等变量中
3.eval字符串,选择字符串例a=’4*5-3’evalaans=17例生成12个随机矩阵,M1-M12阶数从1-12forn=1:12eval[Mnum2strn=randn]endfeval函数可以把用户的输入和函数结合起来执行基本语法如下feval函数名称,数值或变量列表;[y1y
2...]=fevalfunctionx
1...xn如果函数名称存在则将用给定的参数执行函数例a=__gic4[vd]=fevaleigafeval函数可以用于使一个函数接收设定为要调用的函数名的字符串变量,执行灵活的功能例为多种函数画出输入输出图functionplotffunxy=fevalfunx;plotxy
4.15时间和日期__TLAB提供的时间和日期函数有四类函数简解返回当前时间的函数now返回当前日期与时间的数字序列date返回当前日期字符串clock返回当前日期与矢量时间时间数据转换函数:datenum将字符串日期转换成数字序列日期datestr将数字序列日期转换成字符串形式datevec将数字序列日期转换成矢量形式计时函数:cputime返回__TLAB使用的CPU时间(秒)tic、toc计时秒表etime计算时间间隔其它常用函数:calendar日历weekday查询某日为星期几eomday月的最后一天时间日期格式字符串日期02-0ct-1996数字序列日期729300矢量日期(系统内部格式)1996102000格式转换函数datenum日期格式变数字,datestr(日期格式变字符串)datevec(日期格式变矢量)
4.12向量化__TLAB的实际使用中,有些循环可直接转换成向量操作,这样可大大提高程序执行速度,这种技术称为循环的向量化,在编写程序时,应尽量避免采用循环,将它转变为向量进行处理以便最大限度地提高用__tlab编写的程序的效率如何将循环变量变换成向量操作是一个比较复杂的问题简单问题很容易转换为向量操作,但复杂的问题不易直观转换,视实际问题而定例比较如下两个算法
(1)(t
1.m)tstart=clock;x=
0.01;fork=1:1000yk=log10x;x=x+
0.01;endtend=clock;interval=tend–tstart(t
2.m)tstart=clock;x=
0.01:
0.01:10;y=log10x;tend=clock;interval=tend–tstartt
2.m的执行速度远远低于t
1.m的执行速度例产生一个由A矩阵重复产生的矩阵BfunctionB=rep__t1AMNifnagin2reeor‘Requiresatleast2inputs.’elseifnagin==2N=Mend[mn]=sizeA;mind1:m’;mindmind;ones1:M;nindnind:ones1N;dispminddispnindB=Amindnind;函数输入为A[123;456];b=rep__t1a
324.13字符数组和字符串操作1.__TLAB的字符数组在__TLAB中,字符串都被视作字符数组字符串的建立s=’字符串’,即用’’将输入的字符串括起来注意不是”“这点与其它高级语言不同而要建立一个字符串矩阵,则可以这样建立sa=[‘string1’’string2’......]与数组不同,字符串矩阵的每一行字符元素的个数可以不同,但是每一行的所有字符串中的字符的总个数必须相同,如果不满足这个条件,即使每行中字符串的个数相同,也会出错事实上,__TLAB将一个行内的所有字符串都合并起来,构成一个字符串,单个字符串之间不加空格,这正是每行中输入的字符串的个数可以不同的原因char函数自动将最短的字符串添加空格,使各行长度相等例:a=[aaabbb;ccdd]系统报错必须为a=[aaabbb;ccdddd]利用这个特点,可以用[]将任意字符串连接起来例sa=[‘aa‘bb‘cc’;’dd’‘ee’‘f’‘k’]sa=aabbccddeefk例[sa1:sa2:]sa=aabbccddeefk注字符串的每个字符(包括空格)都是矩阵的一个元素处理字符矩阵时当作数据矩阵来处理2.字符串的比较函数strcmpstr1str2比较两个字符串是否相同,若相等则返回1值,若不相等则返回0值函数strncmpstr1str2n:比较两个字符串的前n个字符是否相同,若相等则返回1值,若不相等则返回0值3.字符串的归类函数isletterS:判断串中元素是否为字母函数isspa__S:判断串中元素是否为空格这二个函数的返回结果为与字符串长度相等的矢量,1表示结果为真,0表示结果为假4.字符串的查找与替换函数findstr‘str1’’str2’在字符串str1中查找子串str2,返回str2在str1中的起始位置函数strrep‘str1’’str2’’str3’字符串替换5.字符串运算字符串及字符串矩阵可以进行加、减、乘、除四则运算和其它数字运算(利用ASCII码)例’e’+’f’=
2036.一般通用字符串操作通用字符串操作包括字符串与ABCII间的转换、字符与数据间的相互转换,字符串大小写间的转换、字符串中空格的删除等函数名函数功能stringA将一个整数数组转换成字符串矩阵absS将字符串转换成ASCII码doubleS将字符串转换成相应的ASCII码(双精度)isstrS确认是否为字符串deblankC删除字符串结尾处的空格dispn输入n个空格str2__ts1s2s
3...将字符串变为字符串矩阵upperS将字符串进行大写转换lowerS将字符串进行小写转换a=eval‘’将字符串作为命令执行str__tch‘substr’S匹配字符串操作strtok‘string’d得到指定的子串int2strA将整数转换为字符串num2strA将浮点数转换为字符串str2numS将字符串转换为浮点数dec2hexA把十进制整数转换为十六进制字符串hex2decS把十六进制字符串转换为十进制整数hex2numS把十六进制字符串转换为浮点数dec2binA把十进制数转换为二进制字符串例打印出ASCII码从32-126之间所有可显示的字符char32:126char48:
1264.14类与对象由于引进了类和对象,__TLAB允许用户增加新的数据类型和操作,变量的类型描述变量的数据结构,指示数据的操作对象是类的实现__TLAB内建5种数据类数据类说明double双精度浮点数数组或矩阵sparse二维实数(复数)稀疏矩阵char字符数组struct结构数组__ll单元数组要定义一个__TLAB类,需经过下面几方面工作1.建立类路径类路径下包含描述类的所有方法的M文件类路径的名称由字符“@”加类名称构成例如,定义类ploynom的M文件都放置在一个名为@polynom的路径下面我们用此类来描述多项式,通过调用函数构造函数,由多项式的系数来确定多项式如p=polynom[10-2-5]表示多项式px=x3-2x-
52.定义数据结构所有对象均存储在__TLAB结构中,结构的每一个字段以及字段的详细操作仅对操作类的方法是可见的如上例,将各次幂的系数以降幂的顺序作为一个行矢量来描述多项式类polynom的对象p就成了一个仅有一个字段p.c的结构而这个字段仅有@polynom路径下的函数可以使用3.定义构造函数类的方法路径下必须包含构造函数,构造函数的名称与类名称相同,构造函数的主要作用是为对象初始化数据结构,并指定类标记下面是类polynom的构造函数@polynom/polynom.m:functionp=polynomaifnargin==0p.c=[];p=classppolynom;elseifisaapolynomp=a;elsep.c=a:;p.classppolynom;end
4.定义类型转换函数转换函数的调用形式为b=class_namea这里a是一个非class_name类的对象在__TLAB中最为重要的两个转换函数是double和char这里,我们为polynom类建立这样两个转换函数建立M文件@polynom/double.m,实现从polynom类到double类的转换格式如下functionc=doublepc=p.c要实现类polynom到类char的转换,相对来说要麻烦得多functions=charpc=p.c;ifallc==0s=0;elsed=lengthp.c-1;s=[];fora=c;ifa~=0;if~isemptysifa0s=[s+];elses=[s-];a=-a;endendifa~=1|d==0s=[snum2stra];ifd0s=[s*];endendendifd=2s=[sx^int2strd];elseifd==1s=[sx];endd=d-1;endend此时,调用charp将的如下结果charpans=x^3-2*x-
55.定义显示输出定义显示输出的文件名为display很多类的显示输出定义非常简单,仅仅是输出变量名,并将变量的值转换为字符(调用函数char)输出现为类polynom定义一个简单的显示输出文件@polynom/display.m.functiondisplaypdisp;disp[inputname1=];disp;disp[charp]disp;
4.15重载与继承重载包括三个方面的内容算法的重载,操作符的重载和函数的重载重载,实际是建立一系列特定的M文件,以指定__TLAB在操作自定义类对象时的具体操作如polynom对象加法的重载例子有polynom对象pq,当遇到p+q时,将自动在@polynom路径下寻找plus.m文件,如果文件存在,执行文件要重载这个文件,实质就是建立这个文件functionr=pluspqp=polynomp;q=polynomq;k=lengthqc-lengthp.c;r=polynom[zeros1kp.c]+[zeros1-kq.c];第五章__TLAB基本应用领域
5.1线性代数主要进行线性方程的求解、矩阵求逆、LU分解、QR分解、矩阵求幂、矩阵指数函数、求特征值及奇异值分解
1.__TLIB中的矩阵矩阵定义为二维实或复阵列矩阵的加、减、乘、除、转置运算是最基本的运算,它们应符合维数一致的限制
2.线性代数方程求解一般线性方程可表示成AX=BXA=B当矩阵A为方阵时,它的解为X=A\B(X=invAB)或X=B/A当矩阵A为非奇异时,线性方程的解唯一;当矩阵A为奇异时,线性方程的解要么不存在,要么不唯一a=[1-2-3-4;21-11;-10-12;3-34-5];b=
[1111]x=a\b当矩阵A为m*n维矩阵,且mn时,方程AX=B中,方程个数多于变量个数,因此应采用最小二乘法来求解例ex
32.m对一组测量数据t=[
00.
30.
81.
11.
62.3]’y=[
0.
820.
720.
630.
60.
550.5]’拟用延迟指数函数来拟合这组数据yt≈c1+c2e-t得6个方程,而未知数仅有c
1、c2两个应采用最小二乘法来求解A=[onessizetexp-t]c=A\yT=[0:.1:
2.5]’;Y=[onessizeTexp-T]*c;plotTY’-‘ty’o’
3.矩阵求逆detA:函数可求矩阵A的行列式值invA:函数可求矩阵A的逆矩阵值pinvA:用于计算非方阵的伪逆
4.LU、QR分解通过高斯对消或LU分解法,可将任意方阵表示成一个下三角阵与一个上三角阵的乘积A=LUa=[1:3;4:6;426][lu]=lua得到deta=detl*detuinva=invu*invl
5.矩阵求幂和矩阵指数矩阵求幂如A2B3可以用A^2B^3sqrtmA计算A的开方expmA计算矩阵A的指数eA
6.特征值与特征向量矩阵A的特征值λ和特征矢量ν,满足Aν=λνeigA求矩阵A的特征值λ
7.一元多项式的运算1一元多项式的表示和创建任意一个多项式都可以用一个行向量来表示它的系数是按降序排列例:x^3-6*x^2+11*x-6表示为p=[1–611–6]poly2symp’x’则ans=x^3-6*x^2+11*x-6poly2symp’x’函数多项式的符号表示poly函数若A是n*n矩阵,则p=polyA,p为A的特征多项式,是n+1维向量第一个元素的值一定是1而特征多项式的根就是A的特征值u=[r1r2r
3......rm]polyu=x-r1x-r
2.....x-rm例A=[6–116;100;010];p=polyA;p=[
1.0–
6.
011.0–
6.0]rootsp%%求多项式的根与eigA相同例求1,2,-3为根的多项式u=[12–3]p=polyupoly2symp%%x^3-7*x+6b多项式的基本运算多项式的加减运算__TLIB中没有多项式加减的函数,可以自编函数例(__.m)functionyy=__xynx=lengthx;%x=reshapex1nxny=lengthy;%y=reshapey1ny;n=__xnxnycc=zeros1n;ifnxnycc1nx-ny+1:nx=y;yy=x+cc;elseifnxnycc1ny-nx+1:ny=x;yy=y+cc;elseyy=x+y;end函数的调用为p1=
[346]p2=[52–47]则求多项式的和为p3=__p1p2求多项式的差为p3=__p1-p2多项式的乘法运算w=convuv即求多项式u和v的乘积,即求向量u和v的卷积,公式如下若m=lengthu;n=lengthv;则w的长度为m+n+1且wk=u1vk+u2vk+1+....ukv2k-1如:p1=
[346];p2=[52–47];p3=convp1p2;poly2symp3’x’%显示多项式15*x^5+26*x^4+26*x^3+17*x^2+4*x+42两个以上的多项式的乘法需要重复使用conv.多项式的除法运算[qr]=deconvvu表示多项式v除以多项式u得到的商q和余数r,qr均为多项式,进行解卷积的运算公式如下例[qr]=deconvp3p1;poly2symq’x’%%q=5*x^3+2*x^2-4*x+7[qr]=deconvp3p2;poly2symq’x’%%q=3*x^2+4*x+6求多项式的根rootsc返回多项式的根组成的向量,也是多项式的友元阵的特征值向量,系数为实数的多项式的根,若根为复数,则复数是成对出现的如rootsp;求p=x^3-6x^2+15x-4的根p=[1–615–4]x=rootspx=
2.8494+
2.2726i
2.8494-
2.2726i
0.3011多项式的数组运算按数组运算规则计算多项式的值polyvaly=polyvalpx计算多项式在x处的值,x可以是矩阵或向量x=[1:3;4:6];p=
[1234];polyvalpxC.多项式的因式分解n阶多项式有n个根r1r
2...rn,分解因式为x-r1x-r
2...x-rn有可能有复根,复根则合并,因此在实数范围内的分解后的因式的最高次数不会超过2,分解因式后返回n*3的矩阵,其中n为分解后的因子个数,每一行就代表一个因子例多项式的因式分解的自编函数expuly.mfunctiony=expulyps=p1;r=rootsp;y=[];while~isemptyrc=r1;r1=[];ifi__gcepscc=conv[1-c][1-conjc];y=[y;cc];rfindabsr-conjceps=[];elsecc=realc;cc=[01-c];y=[y;cc];endendifabss-1epscc=[00s];y=[y;cc];endD.最大公约式和最小公倍式最大公约式和最小公倍式是整系数多项式的两个比较重要的概念,__TLAB本身并没有提供来求多项式的最大公因式和最小公倍式的函数自编函数__d.m,利用循环相除法求最大公约式最小公倍式利用两个多项式的乘积除以二者的最大公因式即可以得到最小公约式例最大公约式和最小公倍式的自编函数(__d.m)functiony=__dfgwhile~isemptyfifabsf12*epsf1=[];elsebreak;endendwhile~isemptygifabsg12*epsg1=[];elsebreak;endendifisemptyf|isemptygerrorArgumentsshouldnotbenull;return;endf=f/f1;g=g/g1;while1[qr]=deconvfg;while~isemptyrifabsr12*epsr1=[];elsebreak;endendifisemptyry=g/g1;returnelsef=g;g=r;endiflengthr==1y=1;return;endendE.其它▲poly函数可以把向量转化为多项式,向量的元素为多项式的根u=[r1r2r
3...rm]polyu为多项式x-r1x-r
2....x-rm例求12–3为根的多项式则u=[12–3];p=polyup=[10–76]▲residue函数[rlk]=residue用于多项式的部分分式展开其中p,q分别为分子分母多项式r为留数l为极点,k为余项例num=10*
[14567];%分子多项式den=poly[-2;-1;-
0.5];%分子多项式[respoleski]=residuenumdenres=-
6.6667-
60.
000064.1667poles=-
2.0000-
1.0000-
0.5000ki=105上面的结果说明了这个问题10s4+4s3+5s2+6s+7)=-
6.6667+-
60.0000+
64.16667+10s+5s+2s+1s+
0.5s+2s+1s+
0.5▲polyfitxyn函数,用于n次多项式来拟合该函数,n的次数越高,拟合就越好例用三次多项式来拟合指数函数x=0:
0.1:5;y=expx;n=3;p=polyfitxyn;f=polyvalpx;plotxy’b’xf’r—‘例x=1:5;y=[
5.
543.
1128290.
7498.4]p=polyfitxy3x1=1:
0.1:5;y1=polyvalpx1plotxy’o’x1y1;gridon▲多项式函数函数名称功能简介convab乘法[qr]=deconvab除法polyr用根构造多项式polydera对多项式或有理多项式求导polyfitxyn多项式数据拟合polyvalpx计算x点处多项式值[rpk]=residueab部分分式展开式[ab]=residuerpk部分分式组合rootsa求多项式的根
5.2泛函分析--非线性数值方法函数__TLAB提供了一些有关积分、常微分方程求解等方面的许多泛函(可对函数进行操作的函数),如找出函数在区间上的极小值、求函数的零值点、计算函数积分等优化与求根fzero单变量函数的零点(即方程之根)fmin单变量函数的最小化fmins多变量函数的最小化数值积分和微分limit求极限quadquad8计算积分dblquad计算双重积分diff计算微分常微分方程求解odefile为ODE求解器定义微分方程问题ode45ode23ode113ode15s求微分方程ode23sode23tode23tb
1.函数在__TLAB中的表示例(humps.m)函数fx=1+1-6x-
0.32+
0.01x-
0.92+
0.04表示functiony=humpsxy=1/x-
0.
3.^2+
0.01+1/x-
0.
9.^2+
0.04-
62.数学函数的绘图fplot函数可绘制出指定函数的图形,它可以指定函数自变量和函数值的范围,还可以在同一张图上绘制出多个图形fplot‘f’区间可以指定函数自变量和函数值的范围fplot‘humps’[-55]fplot‘humps’[-55025]fplot‘[5*sinxhumpsx]’[-11]
3.函数极小值点和零值点fmin函数用于求出指定单变量函数在特定区间上的极小点,格式为fmin函数名,始值,终值例x=fmin‘humps’
0.31;humpsx;例计算函数fx=x3-2x-5在(0,2)区间上的最小值点.funtiony=fun1xy=x^3-2*x-5x=fmin’fun1’02x=
0.8165函数在这一点的极小值为y=fun1xy=-
6.0887fmins函数用于求出多变量函数的极小值点格式x=fmins‘fun’x0%可在x0附近得到函数fun的局部最小点;x=fmins‘fun’x0options%可采用指定的选项;x=fmins‘fun’x0option[]p1p
2...%可将参数p1p2,...传递给函数fun;[xoptions]=fmins...%可在options10中得到采用的计算步骤例求函数fx=100x2-x1^22+1-x12的最小值,起始点在(-1,
2.1)functionf=bananaxf=100*x2-x1^2^2+1-x1^2;[xout]=fmins‘banana’[-
12.1]x=
1.
00001.0000out10ans=165最小值f=bananaxf=0fzero函数求指定函数在特定区间上零值点如果函数不存在零点,则返回NaN格式z=fzero‘fun’x%求指定函数在特定区间上零值点fun为单变量实函数的文件名z=fzero‘fun’xtol子%指定了容许的误差z=fzero‘fun’xtoltra__%显示出每次的迭代情况z=fzero‘fun’xtoltra__p1p
2...%给函数fun提供附加的变量例a=fzero‘humps’[-10];humpsa例计算sinx从x=3开始的零点y=fzero‘sin’3例在
[12]之间求解cosx=0y=fzero‘cos’
[12]y=
1.
57084.数值积分极限limit函数格式limit表达式,变量作用对变量趋于0时求极限运算若对变量趋于a时求极限运算,则格式为limit表述式变量a例symsxath;limitsinx/x%returns1limitx-2/x^2-42%returns1/4limit1+2*t/x^3*xxinf%returnsexp6*tlimit1/xx0right%returnsinflimit1/xx0left%returns-inflimitsinx+h-sinx/hh0%returnscosxv=[1+a/x^xexp-x];limitvxinfleft%returns[expa0]导数和微分导数:fxy.....在某一点x0y
0....的增长率,即为此函数在该点的导数f’x=linfx+△x-fx/△x当△x-0可以用limit函数来求diff函数差分和导数逼近如果diff的表达式或可变参数是数值,__TLAB就计算数组中元素间的差分;如果参数是符号字符串或变量,__TLAB就对其表达式进行微分例数值向量和差分x=0:
0.1:1;y=[-.
4471.
9783.
286.
167.
087.
347.
669.
569.
489.
3011.2];%试验数据p=polyfitxy2%多项式的二阶拟合pd=polyderp%多项式求导pd=-
19.
621720.1293说明y=-
9.8108x^2+
20.1293x-
0.0317的微分是dy/dx=-
19.6217x+
20.1293例符号表达式的微分f=’logx’f函数的导数为difffans=expx例求fx=x+exsinx1/2的导数函数表示为f=’x+expx*sinx^1/2’%符号表达式difff结果为ans=1/2/x+expx*sinx^1/2*1+expx*sinx+expx*cosx例difffn求函数的n阶导数,阶数太高时,可能导致死机求y=e-2xcos3x1/2的4阶导数函数表示为y=’exp-2*x*cos3*x^1/2’diffy4prettyans多元函数的求导在diff函数中加入对所求变量的说明即可格式diff‘f’’变量’n例f=’x*sinexpy^1/2/z’;difff’y’;prettyans;对抽象函数的求导与其它函数求导的步骤一样,先说明函数的自变量,再说明函数的形式,最后用diff函数求导积分求一条曲线,一个空间曲面及空间曲体在一定坐标系下对应的__或体积主要使用int函数不定积分只要写出待积分的函数,用int就可以求出函数的积分格式intf或intf变量例有函数f=’sinx*y+z’;intf%结果-cosx*y+z/y对Z求积分intf’z’%结果-cosx*y+z定积分及广义积分在int中加入积分限,就可以求得函数在积分上下限间的积分值,格式intfunctionvar积分上限,积分下限ansa=int‘cosx’0pi/6%变量省略即对x求积an__=int‘x^y’’y’0pi/6%对变量y求积当积分限由某一具体数值变为正负无穷大时,定积分便转变为广义积分例fx=1/xgx=1/1+x2在1到正无穷大的积分函数表示为f=’1/x’;g=’1/1+x^2’intf=intf1inf;intg=intg1inf例fx=1/x2+2x+3gx=1/x2+2x-3在负无穷大到正无穷大的积分函数表示为f=’1/x^2+2*x+3’;g=’1/x^2+2*x-3’intf=intf-infinffx在整个数轴上可积intg=intg-infinfgx在整个数轴上不可积求定积分的另一函数quad和quad8用Simpson方法在指定区间内求一个函数的定积分语法quad‘fun’ab%函数fun在区间[ab]上的数值积分quad‘fun’abtol%tol为相对误差quad‘fun’abtoltra__;%以图形方式显示出积分的进度quad‘fun’abtoltra__p1p
2...%带有参数quad
8...%采用高阶方法实现积分的计算例a=quad‘sin’0pi;a=
2.0000dblquad函数:双重数值积分在一个面上积分是双重积分的本质,只要能明确地将积分面表达出来并恰当转化成int命令中所需要的积分限的形式,双重积分的结果就得到了也可以用函数dblquad注用函数时必须画出积分的面的外形dblquad函数的使用格式result=dblquad‘fun’i__inin__xoutminout__xtolfun=funinneroutter例求下列函数的双重积分functionf=f1xyf=y*sinx+x*cosy然后s=dblquad‘f1’pi2*pi0pis=-
9.
86985.3常微分方程数值解ode23和ode45__tlab中用ode23和ode45分别用中等精度和高精度龙格-库塔方法求解常微分方程(组),初值问题的函数ode23求解一般的常微分方程,采用
二、三阶的龙格-库塔法,ode45采用
四、五阶的龙格-库塔法求解过程为
(1)将微分方程变换成一阶微分方程组yn=ftyy
1....yn-1若令y1=yy2=y
1.....yn=yn-1则得一阶微分方程组相应地可确定初值y1=
(0)y2=
(0).....yn=
(0)其中y和f均为向量
(2)将一阶微分方程组编写成fty的函数M文件functiondy=funftydy=[y2;y3;......fty1y
2....yn-1]
(3)用__TLAB中提供的函数求解微分方程即用如下的格式调用ode23和ode25[ty]=ode23‘Mfilename’[t0tfinal]y0;[ty]=ode45‘Mfilename’[t0tfinal]y0其中,t0初始时间,tfinal计算时间的终值,y0为初值例1解常微分方程y’’+y2-1y’+y=01)将方程变成一个方程组y1=yy2=y’得2)建立一个名为rhf.m的函数M文件,内容为functionfyy=rhftyfyy=[(y2*1-y1^2-y1;y1];3)给定初始条件y0=
0.25y’0=0用ode23在
[015]中求解上述方程组t0=0;tfinal=15;y0=[
00.25];[ty]=ode23‘rhf’[t0tfinal]y0;例列车以20m/s的速度行驶,当制动列车时可获得-
0.4m/s2的加速度,求使列车仃下的制动期间列车的滑行路径s’’=
0.4生成的微分方程为s’=vv’=-
0.4s0=0v0=20ex
29.mfunctiondy=ex29tydy=[y2;-
0.4];ex29f.mx1=[0;20];tspan=[0:4849:
0.01:51];[TX]=ode45ex29tspanx1;subplot211plotTX:1rtitle列车滑动路径gridonsubplot212plotTX:2ktitle列车运行速度gridonN=findX:2=0;t=TN1s=XN11v=XN12例3.设有一微分方程组ex
30.m.ex30f.m
5.4解方程时的精度控制我们可以使用odeset来控制求解时的精度例options=odeset‘RelTol’1e-4‘AbsTol’[1e-41e-41e-5];[ty1y2y3]=ode45‘rigidode’
[012]
[011]options;求解方程y’=rigidodety;在求解过程中,相对误差小于1e-4y1y2y3的绝对误差分别小于1e-41e-41e-5也就是说,我们可以使用如下的格式来建立一个用来控制求解精度的结构options=odeset‘Name1’Value1‘Name2’Value2….其中Namen用来定义误差类型RelTol:相对误差,默认值=1e-3AbsTol:绝对误差,默认值=1e-
65.5函数计算器用于考察两个一元函数各自性质及其相关关系的可视化命令funtool.输入funtool,显示三个窗口,FigureNo1是一元函数fx=x;自变量的定义域x是[-2*pi,2*pi],FigureNo2是一元函数gx=1常量a的值为1/2,此处不再显示FigureNo3如下窗口3是运算及帮助部分第一行为:fx求导fx积分fx化简fx分子表达式fx分母表示式1/fxfx的反函数第二行为:fx+afx-afx*afx/afx^afx+afx*a第三行为:fx+gxfx-gxfx*gxfx/gxfgxgx=fx交换fx和gx第四行中Insert将当前函数fx送入系统内含的典型函数演示表中Cyclr在图1窗口中顺序显示典型函数演示表中的函数曲线Delete删除fxReset调整至初始状态即fx=xgx=1x=[-pipi]a=1/2Help:系统帮助Demo自动演示计算功能Close关闭窗口第六章文件处理
6.1path:得到或设置__tlab的搜索路径p=path;得到当前的搜索路径pathp1p2;用p1p2替代当前的搜索路径pathpathp1;在搜索路径中增加一个目录例pathpath‘c:\temp’;
6.2fopen语法fid=fopenfilename方式;按照指定的“许可方式”打开一个文件;方式包含如下几种不同的方式rreadwwritecreateifne__ssaryaappendcreateifne__ssaryr+readandwritedonotcreatew+truncateorcreateforreadandwritea+readandappendcreateifne__ssary在默认情况下,以上几种方式打开的是二进制文件,如果要打开文本文件,需要在字符串中增加’t’,例如‘rt’‘wt’等以读方式打开一个文件时,如果在当前目录下找不到指定的文件时,fopen会自动在搜索路径中查找这个文件;如果成功地打开了一个文件,则得到文件句柄(一个整型数),否则返回-1fid=1的文件是标准输出(standardoutput),fid=2的文件是标准出错(standarderror)[fidmessage]=fopenfilename打开文件失败时,将出错信息返回message中其中permission是打开文件操作结果的有关信息,函数返回一个非负的整数,作为打开文件的标识值,称为文件的句柄值,对于该文件的任何操作,都通过这个句柄值来传递的
6.3fclose st=fclosefid关闭fid对应的文件,成功返回0,否则返回-
16.4fread格式[acount]=freadfidsizeprecision从文件fid中读入指定长度、指定类型的数据(二进制文件),存放在a中,并且将实际读入的数据的个数存放在count中,其中countsizeprecision是可选的,在缺省情况下,size=inf(读入整个文件)precision=uchar以下是有效的size和precision关于size:N:读入N个元素到一个列向量中inf:[MN]:将M*N个元素按列读入到一个M*N矩阵中,其中N可以为inf而M不可以关于precision(数据精度)__TLABCorFortranDescriptioncharchar*1character8bitsucharunsignedcharunsignedcharacterbitsscharsignedcharsignedcharacter8bitsint8integer*1integer8bitsint16integer*2integer16bitsint32integer*4integer32bitsint64integer*8integer64bitsuint8integer*1unsignedinteger8bitsuint16integer*2unsignedinteger16bitsuint32integer*4unsignedinteger32bitsuint64integer*8unsignedinteger64bitsfloat32real*4floatingpoint32bitsfloat64real*8floatingpoint64bits例fid=fopenfread.mr;F=freadfid;s=setstrF
6.5fwrite count=fwritefidaprecision将矩阵a中的元素转换成指定的类型,按列写出到一个指定的文件中例fid=fopen__gic
5.binwfwritefid__gic5integer*4生成100字节长度的二进制文件,包含5*5个数据,即5阶方矩阵的数据,每个数据占用4个字节的存储单位,数据类型为整型
6.6fscanf从文件中读入格式化后的数据[acount]=fscanffidfor__tsize其中size是可选的,其含义同fread中的sizefor__t同c语言中的格式字符串,有%s%d%f等等
6.7fprintf格式输出,为数据转换成字符串count=fprintffidfor__ta…count=实际输出到文件的字节数for__t为输出格式%e指数表示%f固定小数位置格式%g自动选择较短的例x=0:.1:1;y=[x;expx];fid=fopenexp.___w;fprintffid%
6.2f%
12.8f\ny;
6.8input:R=INPUTHow__nyapples:读入一个数字R=INPUTWhatisyourname:s读入一个字符串
6.9feof:判断是否到达文件尾,feoffid=1文件尾=
06.10fseek重新定位文件指针STATUS=FSEEKFIDOFFSETORIGINOFFSETvaluesareinterpretedasfollows:0Movetowardtheendofthefile.=0Donotchangeposition.0Movetowardthebeginningofthefile.ORIGINvaluesareinterpretedasfollows:bofor-1Beginningoffile文件头cofor0Currentpositioninfile(当前位置)eofor1Endoffile(文件结尾)STATUSis0onsuc__ssand-1onfailure
6.11f____报告文件指针的当前位置,-1=不成功
6.12frewind返回到文件头第七章工具箱简介__TLAB包含主包和各种工具箱(TOOLBOX),迄今所有的30多个工具箱大致可分为二类功能型工具箱和领域型工具箱功能型工具箱主要用来扩充__TLIB的符号计算功能、图形建模仿真功能、文字处理功能以及与硬件实时交互功能、能用于多种学科而领域工具箱是专业性很强的,如控制工具箱、__处理工具箱等__TLAB工具箱内所包含的主要内容
(1)通讯工具箱
(2)控制系统工具箱
(3)财政金融工具箱
(4)频率域系统辩识工具箱
(5)模糊逻辑工具箱
(6)高阶谱分析工具箱
(7)图像处理工具箱
(8)线性矩阵不等式控制工具箱
(9)模型预测控制工具箱
(10)μ分析与综合工具箱
(11)神经网络工具箱
(12)优化工具箱
(13)偏微分方程工具箱
(14)鲁棒控制工具箱
(15)__处理工具箱
(16)样条工具箱
(17)统计工具箱
(18)符号数学工具箱
(19)系统辩识工具箱
(20)小波工具箱网址http://___.__thworks.com
7.1优化工具箱OptimizationToolbox1.简介优化工具箱包含了以下部分内容线性规划和二次规划求函数的最大值和最小值多目标优化约束条件下的优化非线性方程求解最小二乘问题和数据拟合问题的求解2.函数极值
7.2无约束函数极值(无限定条件的极值问题)我们可以使用fminufmins来求解这个问题,求x0附近的函数局部最小值语法如下x=fminu‘fun’x0:x=fminu‘fun’x0x=fminu‘fun’x0options‘grad’x=fminu‘fun’x0options‘grad’p1p2…[xoptions]=fminu‘fun’x
0...[...]=fmins‘fun’x
0...注options是允许误差和算法的选择例即求合适的__[x1x2]使函数成立求解过程如下Step1定义一个M文件,fun.mfunctionf=funxf=expx1*4*x1^2+2*x2^2+4*x1*x2+2*x2+1;Step2将fun.m提交给优化函数x0=[-11];%设置初始值x=fminu‘fun’x0经过36次迭代,我们得到了使得funx在x0=[-11]时的极小值
1.3031e-010x=
0.5000-
1.0000即x1=
0.5000x2=-
1.
0000.如果给定的函数有多个极值,则我们需要通过修改初始值x0来得到不同的极值点极小值为funx=
1.3031e-010例求函数fx=100x2-x122+1-x12在[-1,
2.1]处的最小值functionf=fun1xf=100*x2-x1^2^2+1-x1^2x0=[-
12.1]x=fminu‘fun1’x0x=
1.
00000.9999fun1x=
2.5132e-009函数参数options是一个包含18个元素的向量,用来描述终止精度和使用的算法,其中options1=控制优化函数在迭代过程中的输出的个数,若options1=1,则产生一个表格描述算法执行过程中函数的值和收敛信息;options2=控制x的精度;options3=控制fx的精度;2和3共同构成了终止准则当2和3同时满足时,迭代终止;grad:一个字符串,用来计算函数funx梯度的自定义函数的函数名p1p
2..:函数funx参数,形如f=funxp1p
2..df=gradxp1p
2..的函数需要这些参数注1.fmin是求单变量函数的最小值x=fmin‘fun’x1x2或x=fmin‘fun’x1x2optionsp1p2其中option只能使用18个参数中的3个option
(1)如果为非零,则显示求解的中间结果option
(2)终止运算的误差为
1.e-4option
(14)计算的最大步数为5002.fmin是在标量的情况下求函数的无约束极度小化fminu利用梯度搜索的函数的无约束极度小化fmins利用单纯形搜索的函数的无约束极度小化fmins的算法描述在默认情况下,fminu使用拟牛顿(Qusi-NewtonMethod)方法options6=1,fminu只能得到局部极小值,并且要求函数是连续的;并且fminu不能用来求解形如:的极值问题(leastsq)fmins使用一种单纯形搜索法(______xSearchMethod),当问题的阶数大于2时,它的效率比fminu低,但是如果问题的连续性很差,则fmins更加稳定;(不是用函数的梯度)语法为x=fmins‘fun’x0其余类同上述
7.3有约束的极值问题例1无边界的有约束极值问题Step2:定义描述目标函数和约束的M文件function[fg]=conFun1xf=expx1*4*x1^2+2*x2^2+4*x1*x2+2*x2+1;g1=
1.5+x1*x2-x1-x2;%Constraintsg2=-x1*x2-10;Step3:提交给优化函数x=constrconFun1x0x=-
9.
54741.0474[fg]=conFun1xf=
0.0236%%数值点的函数值options8g=
1.0e-015*%%极值点的条件值,即x1x2代入g1,g2所得之值-
0.88820%%options10=29即迭代29次例2有边界的有约束极值问题即有下界与上界条件的情况,可以使用constr函数上例中,如果a=x=b,即x被限定在某一个矩形之内时,我们可以用如下的方法来求解在前面的条件上加上x1=0x2=0具体地说x0=[-11];options=[];%%使用默任的选项vlb=
[00];%%指定下限,x1=0x2=0vub=[];%%没有上限x=constrconFun1x0optionsvlbvubx=
01.5000%%经过7次迭代求得问题的解[fg]=conFun1xf=
8.5000%%极值范围的f函数值.g=0–10%%g限定条件的值例3.考虑梯度的有约束极值问题一般地,优化函数用有限差分法计算目标函数和约束的梯度,我们也可以使用自定义函数来描述目标函数和约束的梯度,这样做有助于提高求解的精度,问题的定义如例1Step1:改写约束成如下形式x1x2-x1-x2+
1.5≤0-x1x2-10≤0Step2:定义描述目标函数和约束的M文件function[fg]=conFun1xf=expx1*4*x1^2+2*x2^2+4*x1*x2+2*x2+1;g1=
1.5+x1*x2-x1-x2;%Constraintsg2=-x1*x2-10;%%同前Step3:定义描述目标函数和约束的梯度的M文件function[dfdg]=conGrad1x%定义目标函数的梯度函数t=expx1*4*x1^2+2*x2^2+4*x1*x2+2*x2+1;df=[t+expx1*8*x1+4*x2expx1*4*x1+4*x2+2];%对x1和x2的偏导%定义限定函数的梯度dg=[x2-1-x2;x1-1-x1];Step4:提交给优化函数x0=[-11];%初始值options=[];%使用默认的选项vlb=[];%自变量无下限vub=[];%自变量无上限x=constrconFun1x0optionsvlbvubconGrad1x=-
9.
54741.0474[fg]=conFun1xf=
0.0236g=
1.0e-014*-
0.1776%%在进行同样计算的条件下,使用梯度计算时的计算量比不使用梯度的情况小得多例4具有等式约束的有约束极值问题(等式限定条件)对于那些具有若干个等式约束的问题,在约束函数组中,我们应该首先定义等式约束,并且将options13初始化乘等式约束的个数options13为等式限定条件,即等式限定条件的数目,默认值为0,等式限定条件必须放置在变量g的前几个元素中问题的定义如例1,并且在例1的基础上加上一个等式约束x1+x2=1Step1改写约束形式x1+x2-1=0Step2定义一个M文件function[fg]=conFun2xf=expx1*4*x1^2+2*x2^2+4*x1*x2+2*x2+1;g1=x1+x2-1;%等式限定条件必须在前面g2=
1.5+x1*x2-x1-x2;%不等式限定条件g3=-x1*x2-10;Step3提交给优化函数x0=[-11];options13=1;%等式条件的个数x=constrconFun2x0optionsx=-
2.
70163.7016[fg]=conFun2xf=
1.6775g=
0.0000-
9.
50000.0000求解有约束极值问题的的方法语法x=constr‘fun’x0x=constr‘fun’x0optionsx=constr‘fun’x0optionsvlbvub‘grad’x=constr‘fun’x0optionsvlbvub‘grad’p1p2…[xoptions]=constr‘fun’x0…%%返回求解过程中使用的参数[xoptionslamda]=constr‘fun’x0…%%返回使用Lagrange乘子法达到最优解时的乘子系数向量Lamda[xoptionslamdahess]=constr‘fun’x0…%%返回最后一次迭代时的Hessian矩阵不足之处目标函数和约束必须连续可微,并且只能求解局部最优解注
1.fminuconstr都是执行目标函数fx的极小值的函数,若要求解极大值,可对-fx进行求极小值的运算,所得的结果即为fx的极大值
2.优化工具箱只使用形如gix=0的限定条件,对于大于0的限定条件用=0的限定条件乘以–1来处理,若gix=0,则等价于-gix=
07.4求函数在某一区间上的极小值语法x=fmin‘fun’a1a2x=fmin‘fun’a1a2optionsx=fmin‘fun’a1a2optionsp1p2…[xoptions]=fmin‘fun’a1a2…例子x0∈05fx=x-32-1求解过程如下Step1定义一个M文件functionf=scalarFunxf=x-
3.^2-1;Step2提交给一个优化函数x=fminscalarFun05x=3y=scalarFunxy=-1不足之处只能得到局部极小值图例x=2:
0.1:4y=x-3^2-1;plotxy;axis[24–21]即可看到局部的极小值
7.5线性规划即矩阵问题的极小化语法x=lpcAbx=lpcAbvlbx=lpcAbvlbvubx=lpcAbvlbvubx0x=lpcAbvlbvubx0neqcstr%%neqcstr指出前neqcstr个约束时等式约束x=lpcAbvlbvubx0neqcstrdisplay%%控制警告信息的显示display=-1阻止警告信息显示[xlamdahow]=lpcAb..%%返回Langrange乘子法的系数和一个描述求解过程中的错误情况,how=’infeasible’,表示问题是不可解的,how=’unbounded’表示问题又一个__的解,how=’dependent’表示存在线性相关的等式约束,并且扇除了相关的约束,how=’ok’表示问题被正确求解其中c是求解函数A是约束等式矩阵b是系数矩阵vlb是下限矩阵vub是上限矩阵x0例子求极小值问题Step1输入系数c=[-5-4-6];%%函数f的表示a=[1-11;324;320];%%约束等式矩阵b=[20;42;30];%%系数矩阵Step2提交给优化函数[xlamda]=lpcabzeros31%%下限均大于0x=0%%x1=
015.0000%%x2=
153.0000%%x3=3极小值=-5*0-4*15-6*3=-78lamda=
01.
50000.
50001.000000算法描述:采用单纯形法.
7.6二次规划语法x=qpHcAbx=qpHcAbvlbx=qpHcAbvlbvubx=qpHcAbvlbvubx0x=qpHcAbvlbvubx0neqcstrx=qpHcAbvlbvubx0display[xlamda]=qpHcAb…[xlamdahow]=qpHcAb…例子求极小值问题step将函数写成形如的形式问题问题的形式改写为Step2输入系数矩阵/向量H=[1-1;-12];c=[-2;-6];%%一价变量的系数A=[11;-12;21];b=[2;2;3];vlb=zeros21;%%条件均大于0Step3提交给二次规划函数[xlamda]=qpHcAbvlbx=
0.
66671.3333lamda=
3.
11110.4444000算法描述:拟牛顿法.
2.6mini__x问题(最大值中的最小值)语法x=mini__x‘fun’x0x=mini__x‘fun’x0optionsx=mini__x‘fun’x0optionsvlbvub‘grad’x=mini__x‘fun’x0optionsvlbvub‘grad’p1p2…[xoptions]=mini__x‘fun’x0…例子Step1定义一个M文件function[fg]=mini__xFunxf1=2*x1^2+x2^2-48*x1-40*x2+304;%O__ectivesf2=-x1^2-3*x2;f3=x1+3*x2-18;f4=-x1-x2;f5=x1+x2-8;g=[];%%NoconstraintsStep2提交给优化函数x0=[
0.
10.1];x=mini__xmini__xFunx0x=
4.
00004.0000mini__xFunxans=
0.0000-
28.0000-
2.0000-
8.
00000.
00007.7求解非线性方程
1.单个自变量的非线性方程的求解x=fzero‘fun’x0x=fzero‘fun’x0toltra__p1p2…只能得到函数曲线与X轴的交点,而不能得到切点
2.非线性方程组语法x=fsolve‘fun’x0x=fsolve‘fun’x0optionsx=fsolve‘fun’x0options‘grad’x=fsolve‘fun’x0options‘grad’p1p2…[xoptions]=fsolve‘fun’x0…例1Step2定义一个M文件functionf=solvFunxf=[2*x1-x2-exp-x1;-x1+2*x2-exp-x2];Step3提交给求解方程的函数x0=-5*ones21;%初始值options=foptions;%得到默认选项options1=1;%显示输出的内容x=fsolvesolvFunx0optionsf-COUNTRESIDSTEP-SIZEGRAD/SD
347071.21-
9.41e+
0048966.8281-
1.81e+
003151.
994653.
855.
6200.
0006320510.__5-
0.
0867251.39647e-
0150.998-
1.__e-009OptimizationTerminatedSuc__ssfully%%f-COUNTisthenumberoffunctionevaluations%%RESIDistheresidualsum-of-squaresofthefunction%%STEP-SIZEisthestepsizeinthesearchdirection%%GRAD/SDisthegra___ntofthefunctionalongthesearchdirectionx=
0.
56710.5671f=solvFunxf=
1.0e-007*
0.26422642例2求一个矩阵X,使得X*X*X={12;34},初始值为[11;11]Step1定义一个M文件functionf=solvFun1xf=x*x*x-[12;34];Step2提交给求解方程的函数x0=ones22;x=fsolvesolvFun1x0x=-
0.
12910.
86021.
29031.1612F=solvFun1xF=
1.0e-005*
0.
02480.
10920.0331-
0.2034sumsumF*Fans=3814e-012算法描述使用最小二乘法特点即使方程组没有零点,也会返回一个点,这一点上的函数值的绝对值较小;如果Jacobian矩阵是奇异的,将返回一个不正确的值
3.Option的默认值No.FunctionDefaultDescription1Display0Controlsamountofoutputduringtheoptimizationcycle.0displaysnooutput;1displaystabularresults;-1suppresseswarningmessages2Terminationforx1e-4Terminationcriterionthatisameasureoftheworstcaseprecisionrequiredoftheindependentvariablesx.Theoptimizationdoesnotterminateuntilallterminationcriteriah__ebeenmet.3Terminationforf1e-4Terminationcriterionthatismeasureoftheprecisionrequiredoftheo__ectivefunctionfatthesolution.4Terminationforg1e-7Terminationcriterionusedbyattgoalconstrmini__xandseminfthatisameasureoftheworstcaseconstraintviolationthatisac__ptable.5__inAlgorithm0__inoptimizationalgorithmselection.6SDAlgorithm0Searchdirectionalgorithmselection7SearchAlgorithm0Linesearchalgorithmselection.8FunctionN/AValueofthefunctionatthelastevaluatedpoint.Forattgoalandmini__xitcontainsanattai__entfactor.9Gra___ntCheck0Whensetto1the____yticallysuppliedgra___ntsarecomparedwiththoseobtainedfromafinitedifferen__callationduringthefirstfewiterations.Thegra___ntfunctionmustexistwhenthiselementissetto110FunctionCountN/AFunctionevaluationcounter.11Gra___ntCountN/ANumberoffunctiongra___ntevaluationsorfinitdifferen__gra___ntcalculations.12ConstraintCountN/ATotalnumberofconstraintgra___ntcalculationsorfinitedifferen__gra___ntcalculations.13EqualityConstraints`0Numberofequalityconstraints.Equalityconstraintsarepla__dinthefirstelementsofthevariableg.14__ximumFunctionEvaluations100n__ximumnumberoffunctionevaluations.Thisvalueissetto100timesnwherenosthenumberofindependentvariables.Infminsthedefaultis200timesn.Infminthedefaultis500timesn.15O__ectivesUsed0Numberofo__ectivestobeasnearaspossibletothegoals.Usedbyattogoal.16MinimumPerturbation1e-8Minimumchangeinvariablesforfinitedifferen__gra___ntcalculation.Theactualperturbationusedisadaptivetoincreaseaccuracyofthegra___ntcalculation.itvariesbetweentheminimumand__ximumperturbation.17__ximumPerturbation
0.1__ximumchageinvariablesforfinitedifferen__gra___ntcalculation18Step-sizeN/AStep-sizeparameter.Generallyonthefirstiterationthisissetconservativelytoavalueof1orlessdependingontheder__atives.
7.8最小二乘和数据拟合最小二乘法是逼近一组离散点的一种重要方法,它不必知道原函数的具体形式,只要知道采样函数的每个节点的值即可
1.线性最小二乘
2.带非负约束的线性最小二乘x=nnlsAb用于在最小二乘意义下解向量x元素非负的前提下,求解系统方程Ax=b.用线性方程组也可以求解,但在某些出现负数的情况下是没有意义的特别是在方程个数多于变量个数时,应采用最小二乘法来求解语法nnlsAbnnlsAbtol%%tol的默认值=__xsizeA*normA1*epstol为误差容积[xw]=nnlsAb%%w=Langrange乘子法系数的对偶向量,w和x的关系如下wi=0i|xi=0wi=0i|xi0[xw]=nnlsAbtol例ex
41.mA=[
3.4336-
0.
52380.6710-
0.1527-
0.
52383.2833-
0.7302-
0.26__
0.6710-
0.
73024.0261-
2.0000-
0.1527-
0.26__
0.
01842.7507]b=[-
1.
00001.
50002.5000-
2.0000][xw]=nnlsAba=A\by=A*a-by1=A*x-b其中a是用方程组求的解,x是用最小二乘法求的解,可以看到方程组的解更精确,但有负数解,而最小二乘法的解更有用
3.有约束的线性最小二乘语法x=conlsAbCdx=conlsAbCdvlbx=conlsAbCdvlbvubx=conlsAbCdvlb.vubx0%%从x0初开始搜索x=conlsAbCdvlb.vubx0neqcstrx=conlsAbCdvlb.vubx0neqcstrdisplay[xlamdahow]=conlsAbCd...
4.非线性最小二乘语法x=leastsq‘fun’x0x=leastsq‘fun’x0optionsx=leastsq‘fun’x0options‘grad’x=leastsq‘fun’x0options‘grad’p1p
2...[xoptions]=leastsq‘fun’x
0...[xoptionsfunval]=leastsq‘fun’x
0...%%在解x处的函数的值[xoptionsfunvaljacob]=leastsq‘fun’x
0...%%在解x处Jacobian矩阵例,初始值x=[
0.3;
0.4]Step1定义一个M文件functionf=lesqFun1xk=[1:10];f=2+2*k-expk*x1-expk*x2;Step2提交给优化函数x0=[
0.
30.4];x=leastsqlesqFun1x0x=
0.
25780.
25785.非线性曲线拟合x是函数的系数,给定一个型值点数组,求函数Fx在型值点上的平方误差和最小语法x=curvefit‘fun’x0xdataydatax=curvefit‘fun’x0xdataydataoptionsx=curvefit‘fun’x0xdataydataoptions‘grad’x=curvefit‘fun’x0xdataydataoptions‘grad’p1p
2...[xoptions]=curvefit‘fun’x0xdataydata...[xoptionsfunval]=curvefit‘fun’x0xdataydata...[xoptionsfunvalJacob]=curvefit‘fun’x0xdataydata...第八章数据处理在实际的试验和工程测量中,通过不同的方式测得一些离散数据点,称作采样点对这些数据进行利用之前,还要对其进行分析和处理这里主要介绍曲线拟合在实际工程应用和实验中,要得到一条光滑的数据曲线或直线,而实际上却只能测得一些分散的数据点,因而在许多情况下,都需要利用这些不连续的数据点,运用最小二乘法等算法,利用多项式或其他的已知函数生成一个新的多项式或已知函数来对这些已知的数据点进行逼近,利用__TLAB强大的绘图功能,可以将拟合而成的曲线绘制成图实际中最常用的曲线拟合是多项式曲线拟合
8.1最小二乘法直线拟合直线拟合从本质上说是曲线拟合,因而完全可以利用多项式拟合的方法进行计算下面给出一个利用一组数据[x1x2x
3....xn]和[y1y2y
3....yn]用最小二乘法计算直线拟合系数的函数pline.m,其中x和y的数据个数必须相同,否则多余的数据将被忽略,并给出警告信息functionyy=plinexynx=lengthx;ny=lengthy;ifnx~=nywarningthelengthsofxandyshouldbeequalendn=minnxny;ifn2errorthenumberorthedatashouldbegreaterthan1;return;endx=x1:n;y=y1:n;x=reshapexn1;y=reshapeyn1;A=[xonesn1];b=y;B=A*A;b=A*b;yy=B\b;yy=yy例
1.某实验中测得一组数据其值如下:u
21.mx12345y
1.
31.
82.
22.
93.5已知x和y成线性关系即y=kx+b求系数k和b.x=
[12345]y=[
1.
30001.
80002.
20002.
90003.5000]p=plinexy可见k=
0.55b=
0.69直线与数据点的关系用图来表示.y1=polyvalpx;plotxy1holdon;plotxyb*;例2另一实验中测得一组数据其值如下x=1234567y=
0.
31010.
49000.
64000.
80000.
92001.
05001.2000而已知x和y满足关系式y=kxn求参数k和n.将方程两边取对数得:logy=logk+nlogx可见logx和logy成线性关系.将上面的数据放入变量x和y中然后输入:p=plinelogxlogy%p=
0.6909–
1.1851p1=expp2%p1=
0.3057可知n的值为
0.6909,而k的值为
0.3057即y=p1*x^p2y=
0.3057*x^
0.6909源程序u
22.mx=
[1234567]y=[
0.
31010.
49000.
64000.
80000.
92001.
05001.2000]p=plinelogxlogy%p=
0.6909-
1.1851p1=expp2%p1=
0.3057y1=p1*x.^p1;plotxy1holdon;plotxyb*;
8.2多项式曲线拟合有最小二乘法、牛顿法、拉格朗日法、牛顿-格雷高里法等多种方法其中最小二乘法是最普遍的多项式拟合方法
1.最小二乘法在__TLAB中,用函数polyfit对一组数据进行定阶数的多项式拟合,其基本用法如下:p=polyfitxyn用最小二乘法对输入的数据x和y用n阶多项式进行逼近,函数返回多项式的系数为一个长度为n+1的向量,包括多项式的系数[ps]=polyfitxyn函数不仅返回多项式的系数向量p还返回用函数polyval获得的误差分析报告保存在结构体变量s中.在多项式拟合中如果n的值为1就相当于用最小二乘法进行直线拟合.例3.如例1中,用polyfit可以求得:[ps]=polyfitxy1p=
0.
55000.6900s=R:[2X2double]df:3normr:
0.1643polyval为求函数的值,例例求px=5x2-6x+1多项式在x=-2025处的值p=[5–51]y=polyvalp[-2025]y=
[331996]例fx=3exx=[-1–
0.
500.51]y=[
1.
10361.
81963.
0004.
94628.1548]p=polyfitxy4y1=polyvalpxy2=3*expxplotxy1’bo’xy2’r-‘在用高阶多项式对某一函数进行曲线拟合时并不是拟合出来的多项式与被拟合函数在整个区间上都能符合polyfit只能保证在输入数据x所能达到的区间上及其附近.求得的多项式可以最大限度在逼近原函数而在其它的区间上多项式并不一定能够很好地表示原函数极有可能与原函数相差甚远的情况.用阶多项式来逼近正弦函数.在下例中,用8阶多项式来逼近正弦函数例用
[03]区间上的数据来生成多项式而在
[06]区间上画图看看在哪些区间多项式能与函数很好地符合.u
23.mx=0:
0.1:3;y=sinx;p=polyfitxy8x1=0:
0.1:6y1=sinx1y2=polyvalpx1;plotx1y2’k*’x1y1’k-‘由图可知,多项式在区间[0,3]上与函数sinx符合得相当好,即使在区间以外的4处,也没问题,但是,在离拟合区间比较远的地方如5以后,差别就明显了,因而在拟合区间以外,用拟合所得的多项式来求某处的函数值不一定得到正确的结果例多项式拟合及其有效区间x=0:
0.1:
2.5;y=erfx;p=polyfitxy6x=0:
0.1:5;y=erfx;f=polyvalpx;plotxy’bo’xf’r-‘;axis
[0502]
2.拉格朗日法拉格朗日法多项式拟合要求生成的多项式要过所有的数据点如果有n+1个数据点则拟合生成的多项式为n阶多项式用拉格朗日法生成逼近多项式也是较常用的一种方法它的计算有规律简单易于编程但生成的多项式与用来插值的数据关系很大如果数据有所改变函数就要重新计算如果数据很多计算量则很大因而在一定情况下很不方便.__TLAB中没有给出用拉格朗日法进行多项式拟合的函数设有一个函数fx已知fx的n+1个值fx0fx
1....fxn则lagrange插值多项式为Lx=fx0l0x+fx1l1x+.....+fxnlnxfunction[yyc]=lagrangexyznx=lengthx;ny=lengthy;ifnx~=nywarning‘thelengthsofxangyshouldbeequal’;endn=minnxny;ifn2error‘thenumberofthedatashouldbegreaterthan1’;returnendyy=0;fori=1:np=
1.0;forj=1:nifi~=jifabsxi-xjepserror‘thedataiserror’;return;endll=[10-xj]/xi-xj;p=convpll;endendyy=plusyyp*yi;endifnargout==2c=polyvalyyz;end函数中,x和y为拟合所用的数据,也是用来插值的原始数据,yy为返回的拟合多项式,如果参数z存在,则c应该为z中的元素用拉格朗日插值法进行插值的结果x和y中的数的个数应该相同,否则会给出警告信息,但程序仍进行,多余的数据将被忽略利用拉格朗日法拟合下列数据u
24.mx=
[12345];y=[
1.
30001.
80002.
20002.
90003.5000]p=lagrangexy;polyvalpx%ans=
1.
30001.
80002.
20002.
90003.5000x1=1:
0.01:7y1=polyvalpx1plotxyk*x1y1k-axis[17-24]
3.牛顿法函数中x和y为拟合所用的原始数据yy为返回的拟合多项式如果参数z存在则c应该为z中的元素用拉格朗日插值法进行插值的结果x和y中的数的个数应该相同.否则会给出警告信息但程序仍进行多余的数据将被忽略牛顿法与拉格朗日法拟合所得的结果非常接近关于牛顿法拟合有原理在此不作介绍.function[yyc]=newtonxyznx=lengthx;ny=lengthy;ifnx~=nywarning‘thelengthsofxangyshouldbeequal’;endn=minnxny;ifn2error‘thenumberofthedatashouldbegreaterthan1’;returnendyy=0;d=y;fori=1:n-1forj=n:-1:i+1ifabsxi-xj10*epserror‘thedatainputerror’;return;enddj=dj-1-dj/xj-i-xj;endendyy=dn;fori=n-1:-1:1ym=convyy[1-xi];yy=plusdiym;endifnargout==2c=polyvalyyz;end例x=
[12345];y=[
1.
30001.
80002.
20002.
90003.5000]p=newtonxypolyvalpx例用牛顿法在区间[1,3]上逼近正弦函数u
26.mx=1:
0.3:3;y=sinx;p=newtonxyx1=0:
0.1:6;y1=sinx1;y2=polyvalpx1;plotx1y2’ko’x1y1’k-‘
4.牛顿-格雷高里法如果有n个数据点那么拟合产生的多项式的阶数也是n-1阶所不同的是用牛顿-格雷高里法拟合所用数据的第1坐标必须是等间距的而上面的拉格朗日法和牛顿法并不要求虽然所举的例子中的数据的第1坐标都是等间隔的但所有方法中数据的每1坐标都应按顺序排列.function[yyc]=newtonforyhx0xxn=lengthy;ifn2error‘thenumberofthedatashouldbegreaterthan1’;returnendd=y;l=1;forj=2:nfori=n:-1:jdi=di-di-1endendifabshepserror‘histoo__all’;return;ends=[1–x0]/h;yy=0;forj=0:n-1f=1;fori=0:j-1k=ppluss-i/j-i;f=convkf;endyy=plusyydj+1*f;endifnargout==3c=polyvalyyxx;end例p=newtonfory11可见,在用上面的3种方法对数据x和y进行多项式拟合时,所产生的多项式都是一样的,事实上,用polyfit进行拟合也可以得到同样的结果u
27.mpolyfitxy4x=
0.2:
0.02:
0.4;y=humpsx;p=newtonfory
0.
020.2x1=
0.15:
0.02:
0.4;y1=humpsx1;y2=polyvalpx1;plotx1y2’ko’x1y1’k-‘;
5.埃尔密特法在实验所测得的数据中既知道数据的第1坐标和函数值也知道各点的一阶导数值如果此时要用多项式进行曲线拟合使参加拟合的各原始点的函数值和坐标要满足拟合所得的多项式而且要使一阶导数和第1坐标也要满足拟合多项式的微分多项式则这些条件是非常必要的.function[yyc]=aimetx0y0y1xxn=minlengthx0minlengthy0lengthy1;ifn~=lengthx0|n~=lengthy0|n~=lengthy1warning‘thelengthsoftheargumentsarenotequals!’;endifn2error‘notenoughdatapleasecheckagain.’;return;endyy=0;fori=1:nh=1;a=0;forj=1:nifj~=iifabsx0i-x0jepserror‘datainputerror’;return;endk=[1–x0j]/x0i-x0j;kk=convkk;h=convhkk;a=1/x0i-x0j+a;endendk=[-1x0i]*2*a*y0i-y1i;kk=pplusky0i;kkk=convhkk;yy=plusyykkk;endifnargout==4c=polyvalyyxx;end例已知在某实验中测得的某质点的位移和速度随时间的变化如下,求质点的速度和位移随时间的变化曲线u
28.mt=[
00.
50001.
00001.
50002.
0002.
50003.0000]y=[
00.
47940.
84150.
99750.
90930.
59850.1411]y1=[
1.
00001.
50002.
00002.
50003.
00003.5000]p=aimettyy1pp=polyderppolyvalpptx=0:
0.1:3;y0=polyvalpx;yy=polyvalppx;plotxy0’k-‘xyy’k—‘;text1-40’虚线为速度曲线’;text1-60’实线为位移曲线’;holdonplotty’k*’ty1’ko’;xlabel‘时间T(秒)’ylabel‘速度(米/秒)和位移’
8.3数值插值在工程测量和实验中,所得到的数据通常都是一些不连续的点在流动、传热及燃烧等问题中运用数值计算进行求解时通常也是得到的一些不连续的点如果要得到这些分散点以外的其他地方的数值,就必须运用这些已知的点进行插值插值可以分为一维插值、二维插值和__插值,按插值的方法可以分为线性插值、最近插值、最佳均方逼近插值等不同的插值形式下面逐一介绍
1.一维数值插值与查表对于一维数据可以通过插值与查表来求得离散点之间的数据量对于一维插值,按方法可以分为最近插值、线性插值、三次样条插值、三次插值,关于不同插值方法的插值可参阅有关方面的书籍1.interpl函数插值yi=interplxYxi函数返回的向量yi是向量xi根据数据x和Y的插值,求插值与查表类似interpl对于xi中的元素,根据它们的位置,可以由Y的元素插值得到如果Y是一个矩阵,那么插值对Y的每一列进行,函数返回一个lengthxi*lengthx的矩阵yi如果xi中的元素不在x的范围内,则插值结果为NaNyi=interplxYximethod函数用method所指定的方法进行插值,method的取值及插值方法如下‘nearest’最近插值‘linear’线性插值‘spline’三次样条插值‘cubic’三次插值对于上述所有的插值方法,都要求x的元素单调排列,如果x的元素为等间隔的,可以使用快速插值法,method相应的取值为*nearest、’*linear、’*spline、’*cubic函数默认的插值方法为线性插值例:在某实验中要测某短时光束的发光强度随时间的变化,已知在实验中测得一组数据如下,t为测数据的时间,y为反映光束强度的指标,求t=
2.25秒处的光的强度指标t=[
00.
50001.
00001.
50002.
00002.
50003.0000]y=[
00.
47940.
84150.
99750.
90930.
59850.1411]用三次样条插值来求解interp1ty
2.25ans=
0.7539通过绘图,可以看到插值后的函数与原始插值数据之间的位置关系x1=0:
0.5:3;y1=interp1tyx1’spline’;plotx1y1’k-’ty’kO’holdonplot
2.25interp1ty
2.25’spline’’k*’如果求
3.5秒处的强度,则会出现下面的情况interp1ty
3.5ans=NaN2.三次样条插值yi=splinexyxi用三次样条插值法利用数据x和y在xi处进行插值,函数返回插值的结果,x为原始数据的第1坐标,y为函数值xi可以为向量或矩阵函数等同于interplxyxisplinepp=splinexy得到用三次样条插值的分段多项式,可以用函数ppvalPPx来计算多项式在x处的值例:splinety
2.25;ans=
0.7777interp1ty
2.25’spline’ans=
0.7777pp=splinety;ppvalpp
2.25ans=
0.77773.一维表的查找y=table1tabx,从表tab中得到有若干线性插值列的表,tab的第1列相当于数据的第1坐标x,第1列数据必须单调,tab的其余列为插值的函数值,按列进行插值,x可以是向量,返回的变量y的列数是表tab的列数减1,而y的行数是向量x的长度x中元素的值必须在tab的第1列的范围内,否则会出错例:tab=[
001.
00000.
50000.
47941.
00001.
00000.
84151.
00001.
50000.
99751.
00002.
00000.
90931.
00002.
50000.
59851.
00003.
00000.
14111.0000]yy=table1tab[
2.
251.
23.5]Errorusing==tablelx0largerthanallvaluesinfirstcolumnyy=table1tab[
2.
251.2]yy=
0.
75391.
00000.
90391.
00008.4二维数值插值与查表对于二维数据,也有插值与查表两种方法,在实际中,一些较复杂的问题通常都是二维问题,因此二维数据的插值应用既广泛又重要如通过测量一个物理平面上一些离散点的温度,再通过二维插值就可以求得整个物理平面上的温度分布,并且可以利用__tLab强大的绘图功能将温度分布以图形方式输出1.interp2二维插值interp2是__tLab自带的插值函数,有许多种形式ZI=interp2X,Y,Z,XIYI,X和Y为原始数据的第一和第二维坐标,Z为函数值函数返回在XI和YI所指定的位置插值所得的函数值X和Y必须为单调的向量或用单调的向量以meshgrid格式形成的网格格式,建议用函数meshgrid来生成比较方便矩阵X和Y指定了数据Z中的元素的位置如果XI和YI指定的插值点的位置超出了X和Y所指定的范围,则在相应的点上返回NaN值XI和YI可以为矩阵,且维数必须相同,返回值ZI为与XI和YI有相同大小的矩阵,Zij就是函数在点Xij,Yij的插值结果XI和YI可以用向量xi和yi来代替,此时,__tLab认为在点meshgridxi,yi处进行插值,即相当于依次执行以下两步[XlY1]=meshgridxiyi,interp2X,Y,Z,XIY1ZI=interp2ZXIY1相当于依次执行下面的命令;[m,n]=sizeZ;x=l:n;y=1:m;[X,Y]=meshgridxy;interp2X,Y,Z,XI,YI;interp2Zntimes在Z的各点之间插入数据点以扩展Z,依次执行nfimes次默认为1次.ZI=interp2XYZXIYImethod指定插值方法,method的取值及相应的插值方法为;‘nearest’最近插值‘linear’双线性插值‘cubic’三次插值如果X和Y是等间距的,则可以使用快速插值法,其method的相应取值为’*linear,’*cubicnearest例z=[12;34]z1=interp2zz1=
1.
00001.
50002.
00002.
00002.
50003.
00003.
00003.
50004.0000z2=interp2z1z2=
1.
00001.
25001.
50001.
75002.
00001.
50001.
75002.
00002.
25002.
50002.
00002.
25002.
50002.
75003.
00002.
50002.
75003.
00003.
25003.
50003.
00003.
25003.
50003.
75004.0000interp2z2[
1.
251.88][
2.23]%此处作为向量处理ans=
1.
67751.8350interp2z2[
1.
251.88][
2.
232.7]%此处作为矩阵处理而不是向量ans=
1.
67752.0700下面利用二维插值函数对peak函数进行插值,所得图形如图所示下面部分的图形为插值的结果,上面部分为原函数的图形[XY]=meshgrid-3:
0.25:3;Z=peaksXY;[X1Y1]=meshgrid-3:
0.125:3;Z1=interp2XYZX1Y1;meshXYZ;holdon;meshX1Y1Z1+15;
2.二维表的查找Z=TABLE2TABX0Y0从表TAB中得到一个线性插值交点,在表TAB的第1列中找X0,在第1行中找Y0,即矩阵TAB的第1列元素为原始数据的第1坐标,而第1行为其第2坐标,TABij为点TABi,1TAB1j处的值,TAB11会被忽略TAB的第1行元素和第1列元素都应该是单调的例:z=[NaN
1.
00002.
00003.
00004.
00005.
00001.
00001.
00001.
25001.
50001.
75002.
00002.
00001.
50001.
75002.
00002.
25002.
50003.
00002.
00002.
25002.
50002.
75003.
00004.
00002.
50002.
75003.
00003.
25003.
50005.
00003.
00003.
25003.
50003.
75004.0000]table2z[
2.23][
1.
251.88]ans=
1.
67751.8350table2z[
2.
232.7][
1.
251.88]ans=
1.
67751.
83501.
91252.
07003.三维数值插值在__tLab中,用函数interp3来计算三维函数的插值,其基本用法为VI=interp3XYZVXIYIZIVI=interp3VXIYIZIVI=interp3VntimesVI=interp3…methodXYZ分别为每一第二第三维坐标V函数值XIYIZI为插值点的坐标它们可以为向量或矩阵.设函数的基本用法与一维或二维插值函数基本相同.
4.最佳均方逼近在实际的实验研究中测出的数据非常多用上面的多项式插值方法进行插值时多项式次数太高并不理想利用样条插值虽然可以使函数光滑且经过所有的数据点,但表达式较复杂,如果数据太多,则会占用大量的系统资源对于实验数据本身而言,让插值的函数经过所有的数据点并无必要,因各个数据都存在着误差,而最佳均方逼近则较好地克服了以上不足之处最佳均方逼近就是利用一系列已知函数来逼近未知的函数,只要知道参加所有的逼近的已知函数的参数即可下面给出最佳均方逼近的函数的原代码函数evalffx中x是输入参数,用来执行以字符串f表示的函数,其中f为字符串,表示函数名,x是数,返回函数的结果functiony=evalffxf=deblankf;ff=[f‘‘num2strx‘’];y=evalff;例:evalf‘sin’13ans=
0.4202主函数mini_product用来产生最佳均方逼近的系数和插值的函数值各参数的意义如下f为参加逼近的所有函数名组成的字符串矩阵,每个函数名占一行,注意每行的字符个数要相同,不同用空格补齐;向量x和y是参加逼近的原始数据的第1坐标和函数值,它们的长度必须相同,否则会出错;xx是要进行插值的点的第1坐标组成的向量返回参数中,a为参加逼近的各函数的系数组成的向量,其长度与矩阵f的列的长度相同,即各行对应e为均方误差;yy为与xx对应的插值点的函数值function[aeyy]=mini_productfxyxxm=sizef;m=m1;n=lengthx;b=zerosmm;c=zerosm1;ifn~=lengthyerrorXandYshouldbesamesize.endforj=1:mfork=1:mbjk=0;fori=1:nbjk=bjk+evalffj:xi*evalffk:xi;endendcj=0;fori=1:ncj=cj+evalffj:xi*yi;endenda=b\c;%产生系数向量ae=0;fori=1:n%计算均方误差eff=0;forj=1:mff=ff+aj*evalffj:xi;ende=e+yi-ff*yi-ff;endifnargin==3return;endyy=[];fori=1:m%计算xx的各元素对各逼近函数的函数值l=[];forj=1:lengthxxl=[1evalffi:xxi];endyy=[yy1];endyy=yy*a;%计算各插值点的函数值a=a例:对于下面的一组数据,用函数y=-x和函数y=1进行逼近x=
[12345];y=[
1.
30001.
80002.
20002.
90003.5000];构造函数如下functiony=ff0xy=1;functiony=ff1xy=x;在工作空间中输入命令:f=[‘ff1’‘ff0’]mini_productfxyans=
0.
55000.6900可见上面的系数正是用最小二乘法进行直线拟合时所得到的直线的系数,即逼近的结果为y=
0.55x+
0.69t=[
00.
50001.
00001.
50002.
00002.
50003.0000]y=[
00.
47940.
84150.
99750.
90930.
59850.1411]用下列函数逼近上面的数据sinx,cosx,tanx,x^3,x^2,x,1f1=[‘sin‘;‘cos‘;’tan’;’x^3’]xx=0:
0.1:3;[peyy]=mini_productf1tyxx;p=
1.
00000.
00560.0000-
0.
00080.0039-
0.0005-
0.0056plotty’k*’xxyy’k-‘图形如下图所示第九章图形用户界面GUI传统的用户界面定义为用户与计算机之间交互通信__的平台但在最近几年内,这种概念发生了巨大的变化,出现了多种形式的人机交互方式,从命令行的交互方式转变至以图形界面为主的交互形式现在,图形界面已在人机交互方式中占主导地位,这主要是由于它给用户带来了操作和控制的方便与灵活性图形用户界面GUl是包含图形对象如窗口、图标、菜单和文本的用户界面以某种方式选择或激活这些对象,通常引起动作或发生变化最常见的激活方法是用鼠标或其他单击设备去控制屏幕上的鼠标指针的运动按下鼠标按键,标志着对象的选择或其他动作__TLAB也提供了在__TLAB应用程序中加入GUI的功能本章的目的是阐述__TLAB的图形用户界面特性,并说明如何在应用程序中加入一些必要的图形用户界面单元,以方便用户使用本章中阐述__TLAB的GUI特性是__TLAB图形句柄系统的子系统__TLAB的GUI的基本图形对象分为两类——用户界面控件对象和用户界面菜单对象,简称为控件和菜单对象设计一个高效的用户界面包含以下的工作选择恰当的图形对象,并将它们有逻辑地__起来,使得用户界面容易操作和使用本章将说明图形句柄uicontrol和uimenu对象的使用,把图形界面加到__TLAB的函数和M文件uicontrol对象能建立如按钮、滚动条、弹出式菜单以及文本框等对象,uimenu对象能在图形窗口中产生下拉式菜单和子菜单
9.1控件对象及属性
1.控件对象类型控件对象类型是这样一类图形界面对象用户用鼠标在控件对象上进行操作,单击鼠标时,将会使应用程序作出响应并执行某些预定的功能子程序Callback控件的操作结果是可见的,有时可以改变应用程序的初始状态__TLAB支持10种控件对象,它们的添加方式有2种基于命令行的和基于GUI界面的,这将在下面的章节中介绍下面详细介绍它们自身,包括每种控件的目的1坐标轴Axes坐标轴对象这里不再详述2静态文本框text静态文本框是仅仅显示一个文本字符串的uicontrol该字符串是由String属性所确定的静态文本框的Style属性值是text静态文本框一般用于显示标志、用户信息及当前值静态文本框之所以称为“静态”,是因为用户不能动态地修改所显示的文本文本只能通过改变String属性来更改3可编辑文本框Edit可编辑文本框,像静态文本框一样,在屏幕上显示字符但与静态文本框不同,可编辑文本框允许用户动态地编辑或重新安排文本串,就像使用文本编辑器或文字处理器一样在String属性中有该信息可编辑文本框uicontrol的Style属性值是edit可编辑文本框一般用在让用户输入文本串或特定值可编辑文本框可包含一行或多行文本单行可编辑文本框只接受一行输入,而多行可编辑文本框可接受两行以上的输入单行可编辑文本框的输入以Enter键结尾多行可编辑文本框的输入以用Com__nd-Return键4弹出式菜单PopupMenu弹出式菜单一般用于向用户提出互斥的一系列选项清单,让用户可以选择弹出式菜单不受菜单条的限制,可位于图形窗口内的任何位置弹出式菜单的Style属性值是popupmenu.当关闭时,弹出式菜单以矩形或按钮的形式出现,按钮上含有当前选择的标志,在标志右侧有一个向下的箭头或凸起的小方块来表明uicontrol对象是一个弹出式菜单当指针处在弹出式uicontrol之上并按下鼠标左键时,出现其他选项__指针到不同的选项,松开鼠标左键就关闭弹出式菜单,显示新的选项MS-Windows和某些XWindows系统平台允许用户单击弹出式菜单,打开它,而后单击另一个选项来进行选择5滑标Slider滑标,或称滚动条,包括3个__的部分,分别是滚动槽或长方条区域,代表有效对象值范围;滚动槽内的指示器代表滑标当前值;以及槽的两端的箭头滑标uicontrol的Style属性值是Slider滑标一般用于从几个值域范围中选定一个滑标值有3种方式设定方法1鼠标指针指向指示器,__指示器拖动鼠标时要按住鼠标按键,当指示器位于期望位置后再松开鼠标按键方法2当指针处于槽中但在指示器的一侧时,单击鼠标按键,指示器按该侧方向__距离约等于整个值域范围的10%方法3在滑标不论哪端单击箭头,指示器沿着箭头的方向__大约为滑标范围的1%滑标通常与所用文本uicontrol对象一起显示标志、当前滑标值及值域范围6框架Frame框架uicontrol对象仅是带色彩的矩形区域框架提供了视觉的分隔性这点框架与uimenu的Separator属性相似框架一般用于组成单选按钮或其他uicontrol对象在其他对象放入框架之前应事先定义框架,否则框架可能覆盖控制框使它们不可见7命令按钮PushButton命令按钮,又称按钮键或按钮,是小的长方形屏幕对象,常常在对象本身标有文本将鼠标指针__至对象来选择命令按钮uicontrol,单击按钮,执行由回调字符串所定义的动作命令按钮的Style属性值是pushbutton命令按钮一般用于执行一个动作而不是改变状态或设定属性,它与Windows系统的命令按钮的作用相同8单选按钮RadioButton单选按钮,又称选择按钮或切换按钮,它由一个标志并和标志文本左端的一个小圆圈或小菱形所形成当选择时,圆圈或菱形被填充,且Value属性值设为1;若未被选择,指示符被清除,Value属性值设为0单选按钮的Style的属性值是radiobutton单选按钮一般用于在一组互斥的选项中选择一项为了确保互斥性,各单选按钮uicontrol的回调字符串必须不选组中其他项,将它们各项的Value属性值设为0然而,这只是一个约定,如果需要,单选按钮可与复选框交换使用9复选框CheckBox复选框,又称切换按钮,它由具有标志并在标志左边的一个小方框所组成激活时,uicontrol在检查和清除状态之间切换在检查状态时,根据平台的不同,方框被填充或在框内含,Value属性值设为1若为清除状态,则方框变空,Value属性值设为0复选框一般用于表明选项的状态或属性通常复选框是__的对象,如果需要,复选框可与单选按钮交换使用10列表框ListBox这是__TLAB
5.x新增加的一个控件对象列表框列出字符串表,用户可以在这个列表中选取单个列表项或多个列表项对应于选择,__TLAB执行相应的功能或操作
2.控件对象的创建有2种方式创建控件对象,下面分别介绍1基于命令行的方式创建控件对象的基本方法是使用__TLAB的函数uicontro1该函数的调用形式为h=uicontrolhfig’属性名’’属性值’...设计程序时,可根据需要向函数uicontrol提供必要的属性名和属性值参数对__TLAB系统不区别属性字符串中的大小写字母例如,Style和style都表示是属性Style的名字由于控件对象都是图形窗口对象的子对象,所以函数uicontrol调用中,第一个参数hfig应该是某个图形窗口句柄值所创建的控件对象将是该图形窗口的子对象,并出现在该图形窗口中如果省略这个句柄值参数,则生成的图形对象将是当前的图形窗口的子对象如果此时无图形窗口存在,__TLAB系统将自动创建一个图形窗口,并在其中创建相应的控件对象h是所创建控件对象的句柄值,__TLAB通过这个句柄值来管理该控件对象,如同__TLAB任何类型的图形对象一样在__TLAB图形句柄系统中,控件对象也是一种图形对象,因此对于图形对象的操作方法都能用于控件对象例如,可以用get函数取得控件对象的某些属性的当前值,用set函数可以改变和重新设置控件对象的某些当前的属性值[例1]控件对象的创建[xy]=meshgrid[-2:4:2];Z=x.*exp-x.^2-y.^2;Fh=figurePosition
[350275400300]Colorb;ah=axesColor[
0.
80.
80.8]Xtick[-2-1012]Ytick[-2-1012];Sh=su_____XdataxYdatayZdataZ...Fa__ColorgetahColor+
0.
1...EdgeColork__rkero...__rke_____Color[.
51.85];结果如图所示说明;这里只是对于uicontrol函数一个简单介绍,在后面的章节中,将会结合具体属性进行详细介绍与控件对象相关联的功能操作是通过控件对象的Callback属性来定义的,具体使用方式见后面的介绍
2.基于GUI的方式从__TLAB的命令窗口中选择File菜单下的ShowGUILayoutTool命令,或是在__TLAB命令窗口中输入guide命令,出现如图9.3所示的窗口Guide控制板是Guide工具的集成环境,它使得图形对象的生成和管理变得简单、直接例如,可以很方便地访问图形对象的属性;可以方便地控制图形对象的位置、创建任一种图形对象要创建一个图形对象,先单击AddFigure按钮,或是从列表中选择一个图形窗口然后在图形对象创建工具栏Guide控制板最下面的部分中单击想要添加的图形对象,在图形窗口中“画出”所需的位置和大小就可以了对于该控制板中的其他工具,将在后面介绍
3.控件对象的属性在__TLAB的图形句柄系统中,可使用属性对对象的外型和特性进行描述,用户可以在创建控件对象时设定这些属性的属性值,对未指定的属性值,__TLAB将使用系统提供的默认属性值可以用设置图形对象默认属性值的方法设置控件对象的默认属性__TLAB的控件对象使用相同的属性类型,但是这些属性对于不同类型的控件对象,其含义不尽相同控件对象的属性分为两大类,第一类是所有的控件对象都具有的公共属性,第二类是把控件对象作为图形对象所具有的公共属性下面分别予以介绍1公共属性●Children属性Children属性的取值为空矩阵,因为控件对象自己没有子对象●Parent属性Parent属性的取值是某个图形窗口对象的句柄值,因为控件对象总是图形窗口的子对象,该句柄值标明了控件对象所在的图形窗口如果用set函数将Parent属性设置为另一个图形窗口的句柄值,则相当于将控件对象移到另一个图形窗口中●Tag属性Tag属性的取值是字符串它定义了该控件的一个标识值定义了Tag属性后,在任何程序中都可以通过这个标识值找出该控件对象●Type属性Type属性的取值总是uicontrol,这个属性值表明图形对象的类型对于控件对象,其类型就是uicontro1,用户不能改写这个属性●UserData属性UserData属性的取值是一个矩阵,默认值为空矩阵用户可以在这个属性中保存与该控件对象相关的重要数据或信息,借此可以达到传递数据或信息的目的可以用set和get函数访问该属性●Visible属性Visible属性的取值是on默认值或off如果该属性值为off那么控件对象在图形窗口中是不可见的但是该控件对象仍存在,可以用set和get函数访问它的各个属性2基本控制属性●BackgroundColor属性BackgroundColor属性的取值是某些颜色的预定义字符或颜色RGB数值它定义控件对象区域的背景色它的默认值是系统定义的浅灰色●Callback属性Callback属性的取值是字符串,可以是某个M文件名或一小段__TLAB语句当用户激活控件对象例如,在控件对象图标上单击鼠标左键或__滑动槽标尺时,应用程序就运行Callback属性定义的子程序callback调用,但是框架静态文本框控件对象不定义Callback属性●Enable属性Enable属性的取值是on默认值、inactive和off当它的取值是on时,无论何时激活控件对象,__TLAB都执行Callback属性定义的callback子程序但如果鼠标是在控件对象图标区域外的5个像素宽的边界范围内按下时,就执行由ButtonDownFcn属性定义的callback子程序;若Enable属性的取值是inactive,那么当用户在控件对象图标及5个像素边界的范围内单击鼠标时,__TLAB执行ButtonDownFcn定义callback子程序;当Enable属性的取值是off时,控件对象的标题字是有阴影的,它的callback执行功能与inactive情形相同,即运行ButtonDownFcn定义的callback子程序这样定义是有好处的,例如可以通过定义ButtonDownFcn的callback子程序来__控制对象●Extent属性Extent属性的取值是4元素向量[0Owidthheight],记录控件对象标题字符的位置大小,其度量单位由Units属性定义只能读取该属性值,不能改写●ForegroundColor属性ForegroundColor属性的取值是某些颜色的预定义字符或颜色RGB数值,这个属性定义控件对象标题字符的颜色标题字符的默认颜色是黑色●__x、Min属性__x和Mia属性的取值都是数值,其默认值分别是1和0这两个属性值对于不同的控件对象类型意义是不同的以下分别予以介绍◆当单选按钮控件对象被选中时,它的Value属性值为__x属性定义的值当控件对象处于未选中状态时,它的Value属性定义为Min属性定义的值◆当复选框控件对象被选中时,它的Vahe属性值为__x属性定义的值;当控件对象处于未选中状态时,它的Value属性定义为Mia属性定义的值◆对于滑标控件对象,__x属性值必须比Min属性值大,__x定义滑动条最大值,Mia定义滑动条的最小值◆对于可编辑文本框控件对象,如果__x-Min1,那么对应的文本框接受多行字符输入;如果__x-Min1,那么文本框仅接受单行字符输入◆对于列表框控件对象,如果__x-Min1,那么在列表框中允许多行选择,如果__x-Mia1,那么在列表框中只允许单项选择另外,框架、弹出式菜单和静态文本框控件对象不使用__x和Min属性●String属性String属性的取值是字符串矩阵或单元数组,它定义控件的标题或选项内容,特别是对于弹出式菜单和列表框这样的多选择的控件对象,它的String属性可接受多种形式的输入,如字符串单元数组、字符串矩阵和用“|”分隔的字符串向量对于EditBoxes和Statictext这样的多行文字控件对象,String矩阵的每行、单元数组的每块及字符串中的“\n”字符定义的文字行分隔符,即从该处分行对于EditableText和String属性值可以由键盘输入●Style属性Style属性的取值可以是pushbutton按钮,默认值、RadioButton单选按钮、CheckBoxes复选框、edit文本框、text静态文本框、slider滚动条、frame框架、listbox列表框和popupmenu弹出式菜单这个属性值定义控件对象的类型,由相应的值决定●Units属性Units属性的取值可以是pixel像素,默认值、nor__lized相对单位、inches英寸、__ntimeters厘米、points磅除了nor__lized相对单位以外,其他都是绝对单位这个属性值作为解释Extefid和Position属性值的度量单位所有单位的度量都是从图形窗口的左下角处开始在相对单位下,图形窗口的左下角对应0,0,而右上角对应
1.
01.0●Value属性Value属性的取值可以是向量值,也可以是数值它的含义以及解释依赖于控件对象的类型对应于单选按钮和复选框对象,当它们处于选中状态时,Value属性值由__x属性值定义,反之由Min属性值定义对于滑动条对象,Value属性值处于Min和__x属性值之间,由滑动条标尺位置对应的值定义对于弹出式菜单对象,Value属性值是被选项的序号,例如1对应第一项所以由Value值,可知弹出式菜单的选项同样,对于列表框对象,Value属性值定义了列表框中高亮度选项的序号其他的控件对象不使用这个属性值3修饰控制属性●FontAngle属性FontAngle属性的取值是nor__l默认值、italic和oblique,这个属性值定义控件对象标题等的字体其值为nor__l时,选用系统默认的正字体;其值为italic或oblique时,使用方头斜字体●FontName属性FontName属性的取值是控件对象标题等使用字体的字库名,必须是系统支持的各字库默认字库是系统的默认字库●FontSize属性FontSize属性的取值是数值,它定义控件对象标题等字体的字号字号单位由FontUnits属性值定义,默认值与系统有关●FontUnits属性FontUnits属性的取值是points磅,默认值、nor__lized相对单位、inches英寸、__ntimeters厘米或pixels像素,该属性定义字号单位相对单位将FontSize属性值解释控件对象图标高度百分比,其他单位都是绝对单位●FontWeight属性FontWeight属性的取值是nor__l默认值、Light、demi或bold,它定义字符字体的粗细●HorizontalAlig__ent属性HorizontalAlig__ent属性的取值是left、__nter默认值或right,它定义控件对象标题等的调整方向,即标题在控件对象图标上居左left、居中__nter或居右right4辅助属性●ListboxTop属性ListboxTop属性的取值是数量值,这个属性只用于Listbox控件对象,它定义了位于列表框中的最上方的字符串在String属性中的序号非整数值被截断为大于该值的最小整数值●SliderStep属性SliderStep属性的取值是二元素向量[minstep,__xstep],这个属性只对Sliders控件对象有定义__xstep定义了在滑动槽内单击鼠标左键时,滑动槽标尺应该__的距离相对于滑槽长度的百分比;minstep定义了在滑动槽两端箭头上单击鼠标左键时,滑动槽标尺应该__距离相对于滑动槽长度的百分比它的默认值是[
0.
010.10]●Selected属性Selected属性的取值是on或off默认值当Selected属性值是on时,如果SelectionHighligh属性值也是on,那么__TLAB就显示一个对象被选中的标记.如果将ButtonDownFcn定义为设置这个属性为on,那么当选中控件对象时,控件对象就会有一个被选中的方框●SelectionHighligh属性SelectionHighligh属性的取值是on默认值或off该属性决定控件对象被选中时,是否显示被选中的状态这个属性必须与Selected属性配合使用,共同控制控件对象被选中时的状态5callback管理属性●BusyAction属性BusyAction属性的取值是can__l或queue默认值,该属性决定__TLAB采取的控制中断执行控件对象的Callback调用的方式在__TLAB环境中,如果有一个Callback调用在运行,那么随后的Callback调用总是试图中断正在运行的Callback调用如果此时Intermptible属性值为on,那么__TLAB在处理__队列时,会中断正在运行的Callback调用;如果Interruptible的属性值为off那么BusyAction属性就决定__TLAB处理__的方式此时,如果它的值是can__l,就从__队列中取消企图运行第二个Callback调用的__如果它的值是queue,就将企图运行第二个Callback调用的__加入__队列,直至当前的Callback调用完成为止●ButtonDownFcn属性ButtonDownFcn的取值是字符串,·一般是某个M文件名或一小段__TLAB语句当用户在围绕控件对象的5个像素宽的边界内按下鼠标左键时,程序执行该属性定义的Callback调用控件一般是矩形区域如果控件对象的Enable属性值是inactive或off则当在该区域以及5个像素宽的边界内按下鼠标左键时,就执行ButtonDownFcn属性定义的Callback如果这个Callback定义为表达式,那么计算结果就属于__TLAB工作区●CreateFcn属性CreateFcn属性的取值是字符串,一般是某个M文件名或一小段__TLAB语句,即当__TLAB生成控件对象时,__TLAB事先应该执行的程序段这个属性只能按设置默认值的方式定义,例如Set0,’DefaultUicontrolCreateFcn’’set__f,”IntegerHandle””off”’从根对象层设置控件对象的默认值对于已经存在的控件对象,改变该属性值,对该对象无任何影响__TLAB在生成控件对象并完成所有默认属性值的设置后,再执行由CreateFcn定义的Callback如果一个控件对象CreateFcn属性定义的Callback正在运行,那么该控件对象的句柄值不可访问,必须用函数__bo取得●DeleteFcn属性DeleteFcn属性的取值是字符串,一般是某个M文件名或一小段__TLAB语句当删除控件对象时,__TLAB在清除该对象属性之前,要执行由DeleteFcn属性定义的Callback如果一个控件对象DeleteFcn属性定义的Callback正在运行,那么该控件对象的句柄值不可访问,必须用函数__bo取得●HandleVisibility属性HandleVisibility属性的取值为on默认值、off或callback,这个属性定义控件对象句柄的可访问权限,决定其句柄值是否在父对象的Childen属性中出现如果HandleVisibility属性值是on,那么它的句柄值总是可见的如果属性值为callback,那么该句柄值只在该对象的Callback调用以及Callback调用的函数内是可见的,但是命令行内调用的函数不能访问这样的控件句柄也就是说,这样的句柄对于控件对象自己的Callback调用是私有的这对于保护交互式的程序十分有用如果HandleVisibility属性值被设置为off那么控件对象的句柄在任何时候都是不可见的如果句柄是不可见的,那么任何查询句柄的函数都不能返回它的值,这些函数包括get、findo__、__f、__a、__o、newplot、cla、clf和close等当HandleVisibility属性值是callback或off时,这样的控件对象不会出现在图形窗口对象的Children和CurrentObiect属性中,也不会出现在根对象CallbackO__ect属性中但是可以将根对象的ShowHiddenHandles属性设置为on,临时使所有的句柄都是可见的,而不管其HandleVisibility属性值是什么被隐藏的句柄仍然是有效的,只要知道这样的句柄值,一切关于句柄的操作都是合法的●Interruptible属性Interruptible属性的取值是on或off默认值,这个属性决定控件对象的Callback是否可以被随后的Callback调用中断只有由ButtonDownFcn和Callback属性定义的Callback受Intermptible属性值的影响在运行程序时,只有遇到drawnow、figure、getframe和pause等命令,__TLAB系统才检查可以中断程序运行的Callback调用__
4.控件对象属性的修改控件对象属性的创建和修改有两种方式—传统的基于命令行的方式和使用GUI界面的方式两种方式的本质是相同的,都是调用set函数对句柄进行操作但是,在编制程序界面时,GUI界面显得比较简单好用;而在程序运行中,如果要创建新的对象、改变已有的对象属性,就只能使用uicontrol和set语句了因而这两种方法都很重要,而set函数的使用则是基础本小节将通过例子进行具体介绍1使用命令行处理对象的属性使用这种方法,控件对象的属性可以在程序开始时设置,也可以在程序运行中设置在程序开始时,系统对于控件对象的属性给出默认值,但是往往不能满足要求,因而需要用户进行自定义对此,可以使用函数uicontrol,它的语法是H=uicontrol‘PropertyNamel’valuel’PropertyName2’value
2...H是该函数的返回值,为所创建对象的句柄uicontrol函数的具体用法前面已经介绍过,这里就不再详述了要创建某种控件对象,只要如前所述,将它的Style设为所需的值就可以了为了方便查阅,列出表9.1Style属性取值表属性取值所创建的对象pushbutton命令按钮togglebutton切换按钮radiobutton单选按钮checkbox复选框edit可编辑文本框text静态文本框slider滑动条frame框架listbox列表框popupmenu弹出式菜单在__TLAB命令窗口中输入下面命令可以创建一个按钮对象Hbutton=uicontrol‘Style’,’pushbutton’;说明;●uicontrol函数使用系统的默认值FactorValue作为默认值,但是系统默认值是可以修改的因此在需要创建大量对象时,可以考虑修改默认值方法见后,进而创建出大量符合自己要求的对象●可以通过返回的句柄值,对图形对象进行操作下面是一些的例子,通过它们,用户可以了解和熟悉uicontrol的用法[例2l创建一个按钮,响应滑标条的输入值假设滑标条的句柄是sli8pbgetval=uicontrol__f,’Style’,’pushbutton’,...‘Position’,
[101010025],...‘String’’GetSliderValue’,...‘Callback’’dispgetsli8,”Value”’;说明●Position属性指明所创建的按钮对象在当前的图形窗口中的位置和大小;String属性为按钮对象上的说明文字Callback属性定义了当用户单击按钮对象时,应用程序执行的操作和功能●对于Callback属性,它可以是一小段M程序如本例,也可以是一个M文件名,例如myfunction.m后缀.m可以省略[例3]创建复选框这个例子说明如何生成2个复选框,用来设置当前坐标系的某些属性值其中,文本对象给出了控件的一个标题,控件对象的位置和大小的单位是相对单位nor__lized,Callback属性定义的操作是设置一些属性值%静态文本框的创建___axes=uincontrol__f,’Style’,’text’,...‘Position’,[.
1.
4.
25.1],’Units’,’nor__lized’,...‘String’,’SetAxesProperties’;%复选框的创建cbbox=uicontrol__f,’Style’,’checkbox’,...‘Position’,[.
1.
3.
25.1],’Units’,’nor__lized’,...‘String’,’Box=On’,...‘Callback’,[‘set__a,”Box”,”off”’,...‘ifgetbcbbox,”Value”==l,’,...set__a”box”,”On”,’...‘end’];cbtdir=uicontrol__f,’Style’,’checkbox’,...‘Position’,[.
1.
2.
25.1],’Units’,’nor__lized’,...‘String’,’TickDir=out’,...‘Callback’,[‘set__a,”TickDir”,”in,’...‘ifgetcbtdir,”Value==l,’...‘set__a,”TickDir”,”out”,’,…‘end’];[例4]单选按钮的创建下面的例子说明如何创建一个具有2个单选按钮的单选按钮组,用来设置当前坐标系坐标轴刻度的方向,即标记是朝向坐标系内还是坐标系外,二者必居其一每个单选按钮检查另外一个单选按钮的状态,保证只有一个按钮的状态是on%静态文本框的创建,___dir=uicontrol__f,’Style’,’text’,...‘String’’SelectTickDirection’,...‘Position’
[200100150200];%单选按钮的创建tdin=uicontrol__f,’Style’,’radio’,...‘String’,’In’...‘Position’,
[2007515025],...Value’1,...‘Callback’[‘settdin,”Value1’,...‘settdout,”Value,0,’,...‘set__a,”TickDir,”in’];tdout=uicontrol__f,’Style’,’radio’,...’String’,’out’,...’Position’,
[2005015025],...‘Callback’,[‘settdout,”Value,1,’...‘settdin,”Value”,0,’,...‘set__a,”TickDir,”out’];说明Callback执行的结果保证只有一个单选按钮的状态为on,因为单选按钮的Value属性是这样定义的如果单选按钮的状态是on,那么属性Value的值是另一个属性__x的属性值,该属性值的默认值是1;如果状态是off那么属性Value的值是单选按钮的另一个属性Min的值,它的默认值是0这样,通过对属性Value设定不同的值,可以得到单选按钮的不同状态在以上的三个例子中,都使用了set函数set函数的基本使用方法很简单,语法为SETH,’PropertyName’,PropertyValue其中,H为图形句柄,PropertyName为属性名,PropertyValue为属性值另外,set函数还有3种调用方法●setH,a:这里,a是一个结构型数组,它的域名是对象属性名,从而可以将域名所指示的对象属性用a中包含的、对应的属性值来赋值●setHpnpv将在单元数组pv中定义的数值赋给pn中定义的属性名,H为相应对象的句柄其中,pn必须是一个1*N维的矩阵,而pv可以是M*N维的矩阵,其中M等于H的长度可以用lengthH来得到,这样才能保证正确赋值●setHPropertyNamelPropertyValuelPropertyName2PropertyValue2...使用本调用方法可以对同一对象的多个属性同时赋值,用法就不再详述了说明●A=setH将会返回句柄为H的对象的所有属性和可能的属性值,并保存在一个单元数组A中●一个属性的默认值可以改变,方法是在属性名的前面加上一个字符串Default例如,要将一个静态文本框对象的默认颜色改为红色,可以使用下面的命令set__f,’DefaultTextColor’,’red’●有3个字符串,如果将它们赋给属性值,则有特殊的意义default使用默认值从最近的父对象开始factory使用默认值remove删除默认值下面再看几个例子[例5]静态文本标志和一个单行可编辑文本框的创建利用它,用户可以在文本框中输入颜色映像名,而后回调字符串把它放到在图形中HC_label=uicontrol__f,’Style’,’text’,...‘Position’,
[10107020],’String’,’Color__p:’;HC___p=uicontrol__f,’Style’,’edit’,...‘Position’,
[80106020],’String’,’hsv’,...‘callback’,’coloor__pevalgetHc___p,”String”’;[例6]下面的例子实现了一个滑标,可以用于设置视点方位角用3个文本框分别指示滑标的最大值、最小值和当前值Vw=get__a,’View’;HC_aZ=uicontrol__f,’Style’,’slider’,...‘Position’,
[10514020],...‘Min’,-90,’__x’,90,’Value’,vw1’...‘CallBack’,[...‘setHc_cur,”String”num22strget{Hc_az”Value”},’...‘set__a,”View”,[getHc_az,”Value”vw2]’...];Hc_min=uicontrol__f,’Style’,’text’,...’Position’,
[10254020],...’String’,num2strgetHc_az,’Min’;num2strgetHc_az,’Min’;HC___x=uicontrol__f,’Style’,’text’,...‘Position’,
[110254020],...‘String’,num2strgetHc_az,’__x’;HC_cur=uicontrol__f,’Style’,’text’,’...‘Position’,
[60254020],...‘String’num2strgetHc_az,’Value’;[例7]建立图形颜色的弹出式菜单回调函数把图形的Color属性值设定为所选值每种与颜色相关的RGB值存储在弹出控制框的UserDate属性中所有句柄图形对象的UserData属性仅仅为单独矩阵提供孤立的存储HC_fcolor=uicontrol__f,”Style”,”popumenu”,...‘Position’,
[20208020],...‘String’,’BlackIRedlYellowlGreenlCyanlBluel__gentalWhite’,...‘Value’,1,...‘UserData’[
[000];...
[100];...
[110];...
[010];...
[011];...
[001];...
[101];...
[111];...‘CallBack’,[‘UD=getHc_fcolor,’UserData’;’,...‘set__f,’Color’,UDgetHc_fcolor,’Value’,’];[例8]建立一个框架,并把两个按钮和一个标志放入其中Hc_frame=uicontrol__f,’Style’’frame’’Position’
[2502009565];Hc_pbl=uicontrol__f,’Style’,’pushbutton’,...‘Position’
[2552054040],’String’,’OK’;Hc_pb2=uicontrol__f,’Style’,’pushbutton’,...‘Position’,
[3002054040],’String’,’NOT’;Hc_lbl=uicontrol__f,’Style’,’text’,...‘Position’,
[2552508510],’String’,’PushMe’;说明在这个例子中,框架对象的位置向量是这样计算的text控件对象为85个像素宽,而根据定位和对象的大小,frame对象的两边比它各宽出5个像素,保证框架是可见的同理,可以得到框架对象的高度值2使用GUI界面处理对象的属性__TLAB提供了一个GUI界面的工具,用以创建修改控件对象而控件对象的创建方法在前面已经介绍过,这里着重介绍属性的修改如前所述,先用Guide控制板创建一个活动的图形窗口,然后单击最上面的PropertyEditor图标,启动属性编辑器也可以在命令窗口中输入propedit启动属性编辑器下面通过一个例子,说明属性编辑器的使用方法首先,用下面的命令创建图形窗口,并打开属性编辑器surfpeaks25;propedit__f打开的属性编辑器窗口如图9.4所示为了将图形窗口的背景颜色改为红色,可以使用下面的命令set__f,’Color’,’red’;用属性编辑器可以做同样的工作在属性编辑器的figure1#”标题下,有一个文本框,称为属性域在其中输入属性名Color,不要引号按Enter键后,Color属性的默认值就会出现在另一个文本框中,称为值域将该默认值改为red带单引号或100,按Enter键后,相应的图形窗口背景颜色变为红色如同使用set命令一样,也必须提供”属性名”属性值对在上述的方法中,由于必须向属性编辑器提供相应的属性名,故使用起来不够方便为了避免这一点不足,属性编辑器提供了属性列表框在属性编辑器中,用ShowPropertyList复选框打开属性列表框图9.4给出的是属性列表框打开时的属性编辑器在属性列表框中,列出了被编辑的图形对象的全部属性和当前的属性值为了编辑某个属性,只要单击相应的属性列表项,相应的属性名和属性值就会出现在属性域和值域文本框中,然后改变相应的属性值就可以了在前面的例子中,如果要改变图形窗口中坐标系对象的某个属性,可以用propedit命令propedit__a将属性编辑器对准图形窗口中的当前坐标系对象如前所述,对坐标系对象的属性进行编辑另一方面,属性编辑器、Callback编辑器和位置调整工具还提供了图形对象的浏览功能这项功能可以在图形对象树型结构层次上管理图形对象可以用ShowObiectBrowser复选框来打开或关闭图形对象列表框在图形对象列表框中会列出当前图形窗口中的图形对象及其层次结构对于前面的例子,只要在图形对象列表框中选择坐标系对象,即可将属性编辑器对准到坐标系,再对其属性进行必要的编辑如果此时属性列表框是打开的,那么该图形对象的所有属性就在属性列表框中列出.
9.2实例
一、源程序清单functiondemo_gui%创建figure对象a=figureColor[
0.
80.
80.8]...Interruptibleoff...Position
[294111514434]...Tagfig1;%创建frame对象b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Position[
17.
2530.
75124.5291]...Styleframe...TagFrame1;%%创建axes以及相关对象b=axesParenta...Unitspoints...CameraUpVector
[010]...CameraUpVectorMode__nual...Color
[111]...Interruptibleoff...Position[
173.
25135185.
25167.25]...TagAxesl...Xcolor
[000]...yColor
[000]...ZcolOr
[000];c=textParentb...Color
[000]...HandleVisibilityCallback...HorizontalAlig__ent__nter...Interruptibleoff...Position[
0.495935-
0.1081080]...TagAxeslText
4...VerticalAlig__entCap;setgetcParentXLabelc;c=textParentb...Color
[000]...HandleVisibilityCallback...HorizontalAlig__ent__nter...Interruptibleoff...Position[-
0.
1178860.4954950]...Rotation
90...TagAxeslText
3...VerticalAlig__entbaseline;setgetcparentYLabelc;c=textParentb...Color
[000]...HandleVisibilityCallback...HorizontalAlig__entright...Interruptibleoff...Position[-
0.9430__
1.135140]...TagAxeslTrex
2...Visibleoff;setgetcParentZlabelc;c=textParentb...Color
[000]...HandleVisibilitycallback...HorizontalAlig__ent__nte...Interruptibleoff...Position[
0.
4959351.031530]...tagAxeslText
1...VerticalAlig__entbottom;setgetcParentTitlec;b=uicontrolParenta...%%创建列表框对象Unitspoints...BackgroundColor
[111]...Interruptibleoff...Position[
27.
75223.
5106.575]...String{sincospolynoMinal}...Stylelistbox...taglistbox
1...Value1;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
75294100.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
30302.
257813.5]...String选择源函数...Styletext...TagStaticText1;b=uicontrolParenta...%%创建四个编辑框对象Unitspoints...BackgroundColor
[111]...Interruptibleoff...Position[
69195.
7566.7515]...String-
5...Styleedit...tagEditText1;b=uicontrolParenta...Unitspoints...BackgroundColor
[111]...Interruptibleoff...Position[
66.
75178.
566.7515]...String
5...Styleedit...TagEditText2;b=uicontrolParenta...Unitspoints...BackgroundColor
[111]...Interruptibleoff...Position[
66.
75138.756615]...String
0...Styleedit...TagEditText3;b=uicontrolParenta...UnitsPoints...BackgroundColor
[111]...Interruptibleoff...Position[
66.
75158.
2566.7515]...String
2...Styleedit...TagEditText4;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
27.
75200.
2534.512]...Stringxfrom...Styletext...TagStaticText2;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
27.
75182.
7534.512]...Stringto...Styletext...TagStaticText2;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
27.
75162.
7534.512]...Stringyfrom...Styletext...TagStaticText2;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
27.
75142.
534.512]...Stringto...Styletext...TagStaticText2;b=uicontrolParenta...%%创建复选框对象Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Interruptibleoff...Position[
28.
5115.
5104.
515.75]...String显示数据标记...Stylecheckbox...Tagcheckbox1;b=uicontrolParenta...%%创建无线按钮对象Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Callbackdemoguilinear...Position[
3070.59015]...String线性标度...Styleradiobutton...Tagradiobutton1;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Callbackdemoguilog...Position[
29.
2550.259015]...String对数标度...Styleradiobutton...Tagradiobutton2;b=uicontrolParenta...%%创建组合框对象Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Enableinactive...Interruptibleoff...Position[
27.
7592.
2531.
513.5]...String类型...Styletext...TagStaticText3;b=uicontrolParenta...Unitspoints...Position[
67.
591.56315]...String{linegraphstemgraphstairgraph}...Stylepopupmenu...TagPopupMenu
1...Value3;b=uicontrolParenta...%%创建按钮对象Unitspoints...Callbackdemoguirefresh...Position[
230.
2533.
756321.75]...String刷新...TagPushbutton1;b=uicontrolParenta...Unitspoints...Callbackdemoguiclose...Position[
294.
7534.
56321.75]...String关闭...TagPushbutton1;b=uicontrolParenta...Unitspoints...Position[
14760.
75227.
2553.25]...Styleframe...TagFrame2b=uicontrolParenta...%%创建滑动器对象Unitspoints...Position[
205.
592.
25153.7512]...Styleslider...Min
10...__x
100...value
50...Tagslider1;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Position[
157.
587.
7541.2518]...String数据点数...Styletext...TagStaticText4;b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Position[
208.
57240.
513.5]...String
10...Styletext...TagStaticText5b=uicontrolParenta...Unitspoints...BackgroundColor[
0.
7529410.
7529410.752941]...Position[
299.
2569.
7550.2515]...String
100...Styletext...TagStaticText6回调函数functiondemoguiactionswitchactioncaserefreshx1=evalgetfindo__tagEditText1string;x2=str2numgetfindo__tagEditText2string;y1=str2numgetfindo__tagEditText3string;y2=str2numgetfindo__tagEditText4string;data_points=getfindo__tagslider1value;x=x1:x2-x1/data_points:x2;b=findo__taglistbox1;switchgetbvaluecase1y=sinx+
1.0001;case2y=cosx+
1.0001;case3y=
2./1+x.*x;endb_data__rk=getfindo__tagcheckbox1value;switchgetfindo__tagPopupMenu1valuecase1ifb_data__rkplotxy+;elseplotxyendcase2stemxy;case3stairsxy;end;axis[x1x2y1y2];ifgetfindo__tagradiobutton2value;set__ayscalelog;elseset__ayscalelinear;end;caseclosedelete__f;caselinearset__bovalue1;setfindo__tagradiobutton2value0;caselogset__bovalue1;setfindo__tagradiobutton1value0;end
二、操作步骤程序比较长,下面分段讲述其中每一部分的作用程序主要的任务包括两部分创建界面和编写回调函数前一个任务由函数demo_gui完成,后一任务由函数demogui完成1.勾画界面制作用户界面的第一步是列举程序的功能,从而根据我们使用别人设计的用户界面的经验,勾画界面的大致内容界面上的控制元素都是根据任务的需要安排的,如下1产生axes对象为了绘图,首先必须有一个axes对象,就象准备一张画布一样;2加入选择__类型的控制由于要求能选择三种不同的__,这可以通过在窗口上加列表框、下拉框或无线按扭等控制实现,这里我们采用列表框;3加入选择标度方式选择的控制针对显示两种标度方式效果的要求,同样可以用列表框、下拉框或无线按扭,为了演示各种控制的用法,这里我们选用无线按扭;4加入输入坐标轴范围的控制坐标轴的范围是四个数值组成的向量[xMin,x__x,yMin,y__x,因此可以采用四个编辑框;5加入控制数据点疏密的对象控制数据点的疏密关键是选择plotx,y中x和y数组的的长度,因为长度必须是整数,这里采用滑动器slider对象输入;6加入控制选择是否显示数据标记是否显示数据标记属于开关型量,因此最方便的控制是复选框;7加入选择三种绘图方式的控制Windows提供的用于选择的控制中,还有combox也就是__TLAB的popupmenu现在还没有用到,刚好可以用来选择三种__的绘图方式上;8加入命令按扭为了根据当前设置显示图形,还需要一个‘刷新’按扭;为了结束程序的运行,以及一个‘关闭’按扭;9加入背景控制相关联的一些项目,用背景框架frame控制组合起来,可以使界面变得更加友好;10加入文字说明最后为了在用户界面上说明各个控制的用途,当然还需要一些文字标签对象现在所需要安排的控制已经定了下来,可以在草稿纸上大致地勾画一下界面的布置,比如说可以有如图所示的布置方式对于这个草图,需要说明一点因为现代人的阅读习惯总是从左到右、从上到下,因此设计时参照这一点,也要把控制按照操作的顺序从左到右、从上到下排列,绘图结果区域和按扭区域应该放在窗口的最右侧关于勾画界面步骤实际上还有许多总的原则,将在任务总结中介绍作为尝试,现在我们就可以进入下一阶段编写代码了9.3使用专用函数1.使用inputdlg函数输入坐标轴的范围和数据点数调用格式a=inputdlgprompta=inputdlgprompttitlea=inputdlgprompttitlelinenoa=inputdlgprompttitlelinenodefans其中prompt:为对话框的提示文字title为对话框的标题文字,是一个一般的字符串lineno指定每行输入项能够接受的输入行数defans指定各变量的初文字因为对话框是模态的,所以在对话框关闭之前,不能切换到__tlab的其它窗口中去,但可以切换到其它窗口中去2.使用warndlg用来产生一个警告窗口Warndlg提示信息title例ifisempty__llswarndlg‘Youpressed“can__l”inthedialog’titleend
3.使用questdlg函数询问是否只绘制数据标记questdlg函数同样是用来输入一个选择的,但是这种选择是在“是”与“否”之间进行的b=questdlg‘Wouldliketodrawonlydata__rks’title;函数返回值是字符串ifstrcmpb’YES’plotxy’+’elseplotxyendif
4.专用函数一览表Dialog:创建一个基本的模态对话框Errordlg:创建出错提示对话框Helpdlg:显示帮助对话框Inputdlg:创建输入对话框Menu:产生一个用来输入选择的对话框Msgbox显示一个消息框Pagedlg:显示页布局对话框Printdlg:显示“正在打印”对话框Questdlg创建输入“是”或“否”的对话框Textwrap:对指定uicontrol对象返回字符串折行矩阵Uigetfile:显示文件打开对话框Uiputfile:显示文件保存对话框Uiresume:和uiwait一起控制程序的流程Uisetcolor:显示颜色选择对话框,返回colorspec类型变量Uisetfont:显示字体选择对话框,并设置指定uicontrol对象的字体Uiwait:和uiresume一起使用控制程序的流程Waitbar:创建“请等待”对话框,用来显示计算进度Waitforbuttonpress:等待在指定figure对象的击键__的发生Warndlg:创建一个警告窗口5.例prompt={x1x2y1y2};title=specFuncDemo;defaults={-5+502};__lls=inputdlgprompttitle1defaults;x1=str2num__lls{1};x2=str2num__lls{2};y1=str2num__lls{3};y2=str2num__lls{4};calls=inputdlgNumberofpointtitle1{50};data_points=str2num__lls{2};stype=menuSelectsour__typesinw__ecosw__equadraticw__e;ftype=menuSelectfiguretypeLinegraphstemgraphstepgraph;x=x1:x2-x1/data_points:x2;x1x2data_pointsxswitchstypecase1y=sinx+
1.0001;case2y=cosx+
1.0001;case3y=
2./1+x.*x;end;yswitchftypecase1b_data__rk=questdlgWouldliketodrawonlydata__rkstitle;ifstrcmpb_data__rkYesplotxy+elseplotxyendcase2stemxycase3stairsxyend;axis[x1x2y1y2];第十章__工具箱__处理工具箱包括两大部分函数部分和GUI工具部分函数部分包括了数十个非常有用的函数,例如__产生,时域,频域分析,功率谱估计,滤波分析和设计等等GUI工具部分主要包含一个交互性的__和系统浏览工具,可以用来对__和系统进行非常直观的分析,使用很方便
10.1__分析__是__分析领域最基本的概念,整个__分析都是围绕着这个概念展开的,如何了解__的时域特征和频域特征、功率或能量域特征,提高信噪比以及为此目的的设计和研究滤波器等等__的时域分析主要提供__的均值、方差和自相关函数等信息,频域特征则测重于了解__的频率组成,功率谱估计方法用来从功率的角度了解__的频率组成为了进行__分析,首先必须产生__数据__TLAB中__都是以向量的形式存储的,例如
[10000]表示一个长度为5的单位冲击__下面先介绍一下,对于常用的一些特殊__,如何用__TLAB产生其波形1.长度为n点的三角__产生方法t=[1:n];A=10;omiga=2*pi;signal=A*sinomiga*t;2.长为n点的单位阶跃__产生方法signal=ones1n;
3.长为n点的单位冲击__产生方法signal=[1zeros1n-1];
4.长为n点的狄里克diric函数混迭的sinc函数狄里克diric函数的定义为-1kn-1x=2πkk=0+1-1+2-
2.....diricx=sinnx/2nsinx/2其它情况产生方法x=linspa__
0.4*pi300;plotxdiricx8这里x是个参考__,因为diric函数根据其第一个参数的长度决定产生__的长度其波形为5.锯齿波__用sawtootht函数产生周期为2π的锯齿波,sawtoothtwidth中,width参数指定锯齿波的波峰出现的位置,width=1为正极,width=0负极性,width=
0.5对称锯齿波如图
6.Sinc函数的定义为sinct=在__TLAB里用sinc函数产生其波形
7.白噪声____TLAB提供两个函数用于产生白噪声rand和randn,前者产生均匀分布的白噪声,后者产生高斯分布的白噪声
8.chirp__chirp__是雷达专业中的专用词汇,即“扫射频率__”,chirp__的特点是__的瞬时频率随时间按照一定规律变化在__TLAB中用chirp函数产生这种__,其语法为y=chirptf0t1f1y=chirptf0t1f1’method’y=chirptf0t1f1’method’phi根据method参数的不同,产生的__的瞬时频率可能有如下的选择
(1)‘linear’__频率随时间按线性规律变化,即
(2)‘quadratic’__频率随时间按平方规律变化,即
(3)‘logrithmic’__频率随时间按对数规律变化,即参数phi指定t=0时的相位,单位是‘度’如t=0:
0.001:2;%以1kHz采样频率观察家秒钟y=chirpt01150;%起始直流,按150Hz/s线性增长specgramy2561e3256250%显示不同时刻的功率谱。