Matlab Extensions for the Development, Testing and Verification of Real-Time DSP Software
MatLab中文版(word版)第五章

目录第五章自定义函数 (1)5.1 MA TLAB函数简介 (1)5.2 在MA TLAB中传递变量:按值传递机制 (6)例5.3 (7)5.3 选择性参数 (14)测试5.1 (16)5.4 用全局内存分享数据 (17)例5.4 (18)5.5 在函数调用两次之间本地数据的存储 (22)例5.5 运行平均数 (22)5.6 函数的函数(function functions), (26)例5.6 (27)5.7 子函数和私有函数 (29)5.8 总结 (29)5.9 练习 (30)5.1 (30)5.2 (30)5.3 (31)5.4 (31)5.5 (31)5.6 (31)5.7 (31)5.8 (31)5.9 (31)5.10 (31)5.11 (31)5.12 (32)5.13 (32)5.14 (32)5.15 (33)5.16 (33)5.17 (33)5.18 (34)5.19 (35)5.20 (35)5.21 (35)5.22 (35)5.23 (36)5.24 (36)5.25 (37)5.26 (37)第五章自定义函数在第三章中,我们强调了好的编程习惯的重要性。
我们进行开发的基本手段是自上而下的编程方法。
在自上而下的编程方法中,它开始于对所要解决问题的精确陈述和定义输入量和输出量。
下一步,我们在大面上进行算法的描述,然后把算法分解成一个一个的子问题。
再然后,程序员把这一个个子问题进行再一次的分解,直到分解成简单而且能够清晰理解的伪代码。
最后把伪代码转化为MATLAB代码。
尽管我们在前面的例子中,按照上面的步骤进行了编程。
但是产生的结果在某种程度上还是受限制的。
因为我们必须把每一个子问题产生的MATLAB代码嵌入到一个单独的大程序中。
在嵌入之前我们无法对每一次子问题的代码进行独立地验证和测试。
幸运的是,MATLAB有一个专门的机制,在建立最终的程序之前用于独立地开发与调试每一个子程序。
MATLAB的中英文翻译

MATLAB - The Language Of Technical ComputingMATLAB is a high-level language and interactive environment that enables you to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran. You can use MATLAB in a wide range of applications, including signal and image processing, communications, control design, test and measurement, financial modeling and analysis, and computational biology. Add-on toolboxes (collections of special-purpose MATLAB functions, available separately) extend the MATLAB environment to solve particular classes of problems in these application areas.MATLAB provides a number of features for documenting and sharing your work. You can integrate your MATLAB code with other languages and applications, and distribute your MATLAB algorithms and applications.MATLAB has key featuers as follows:(1)High-level language for technical computing (2)Development environment for managing code, files, and data (3)Interactive tools for iterative exploration, design, and problem solving 4)Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration (5)2-D and 3-D graphics functions for visualizing data (6)Tools for building custom graphical user interfaces (7) Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java, COM, and Microsoft ExcelThe MATLAB language supports the vector and matrix operations that are fundamental to engineering and scientific problems. It enables fast development and execution. With the MATLAB language, you can program and develop algorithms faster than with traditional languages because you do not need to perform low-level administrative tasks, such as declaring variables, specifying data types, and allocating memory. In many cases, MATLAB eliminates the need for ‘for’ loops. As a result, one line of MATLAB code can often replace several lines of C or C++ code. At the same time, MATLAB provides all the features of a traditional programming language, including arithmetic operators, flow control, data structures, data types, object-oriented programming (OOP), and debugging features. MATLAB lets you execute commands or groups of commands one at a time, without compiling and linking, enabling you to quickly iterate to the optimal solution. For fast execution of heavy matrix and vector computations, MATLAB uses processor-optimized libraries. For general-purpose scalar computations, MATLAB generates machine-code instructions using its JIT (Just-In-Time) compilation technology. This technology, which is available on most platforms, provides execution speeds that rival those of traditional programming languages. MATLAB includes development tools that help you implement your algorithm efficiently. These include the following: MATLAB Editor - Provides standard editing and debugging features, such as setting breakpoints and single stepping. M-Lint Code Checker - Analyzes your code and recommends changes to improve its performance and maintainability. MATLAB Profiler - Records the time spentexecuting each line of code. Directory Reports- Scan all the files in a directory and report on code efficiency, file differences, file dependencies, and code coverage。
MATLAB简介

�
该对话框会出现b次,直至电路全部支路拓扑结构信 息输入完毕.电路拓扑信息的输入是用来形成回路 矩阵的.
二,求各支路电流
4.
电路拓扑结构信息输入完毕后,出现如下图 所示提问对话框,询问是否继续进行回路分 析.此时应选择"Yes",继续回路分析法其
电路拓扑结构信息全部输入 完毕后,会出现支路1元件 类型选择对话框,如右图所 示.
一,求各节点电压
电路各支路信息输入完毕后,MATLAB命令 窗口中就会显示求得的电路相关信息及各节 点电压.输出如下所示:
the number of the nodes: 4 the number of the branches: 5 the number of VS: 1 the number of VCVS: 0 the number of CCVS: 0 the voltage of each node(V): V1=100∠0° V2=46.8165∠20.556° V3=93.6329∠-159.444°
一,求各节点电压
2.
确定分析方法后,出现下图对话框,要求输 入电路的总体信息.
一,求各节点电压
3.
总体信息输入完毕后,会 出现支路1元件类型选择 框图,如右图所示.
一,求各节点电压
4.
支路1类型选择完毕后,会出现支路1相应类 型的元件参数输入对话框,如下图所示.
一,求各节点电压
3,4两步为支路1的元件类型和参 数信息的输入.设电路支路数为b, 则会重复3,4步骤b次,直至将电 路所有支路信息输入完毕.
二,求各支路电流
1.
在MATLAB命令窗口中键入命令ca,运行电 路分析程序,同样出现如下图所示对话框. 点击"Loop"按钮,选择回路分析法.
Matlab使用方法和简介

Matlab使用方法和简介绪论Matlab是“Matrix Laboratory”的缩写,意为“矩阵实验室”,是当今美国很流行的科学计算软件.信息技术、计算机技术发展到今天,科学计算在各个领域得到了广泛的应用.在许多诸如控制论、时间序列分析、系统仿真、图像信号处理等方面产生了大量的矩阵及其相应的计算问题.自己去编写大量的繁复的计算程序,不仅会消耗大量的时间和精力,减缓工作进程,而且往往质量不高.美国Mathwork软件公司推出的Matlab软件就是为了给人们提供一个方便的数值计算平台而设计的.Matlab是一个交互式的系统,它的基本运算单元是不需指定维数的矩阵,按照IEEE的数值计算标准(能正确处理无穷数Inf(Infinity)、无定义数NaN(not-a-number)及其运算)进行计算.系统提供了大量的矩阵及其它运算函数,可以方便地进行一些很复杂的计算,而且运算效率极高.Matlab命令和数学中的符号、公式非常接近,可读性强,容易掌握,还可利用它所提供的编程语言进行编程完成特定的工作.除基本部分外,Matlab还根据各专门领域中的特殊需要提供了许多可选的工具箱,如应用于自动控制领域的Control System工具箱和神经网络中Neural Network工具箱等.第一节Matlab的安装及使用§1.1 Matlab的安装Matlab有各种版本,早期有Matlab 1.0 for 386的DOS版本,后来逐步发展.这里介绍的版本是Matlab 6.x for Windows.因为它使用方便,界面美观,我们选择它作为主要讲解版本.Matlab还有许多附加的部分,最常见的部分称为Simulink,是一个用作系统仿真的软件包,它可以让您定义各种部件,定义各自对某种信号的反应方式及与其它部件的连接方式.最后选择输入信号,系统会仿真运行整个模拟系统,并给出统计数据.Simulink有时是作为Matlab的一部分提供的,称为Matlab with Simulink版本.Matlab还有许多工具箱,它们是根据各个特殊领域的需要,用Matlab自身的语言编写的程序集,使用起来非常方便.您可以视工作性质和需要购买相应的工具箱.常见的工具箱有:Signal Process 信号处理System Identification 系统辨识Optimization 优化Neural Network 神经网络Control System 自动控制Spline 样条Symbolic Math 符号代数Image Process 图像处理Nonlinear Control 非线性控制Statistics 统计§1.2 Matlab基本用法从Windows中双击Matlab图标,会出现Matlab命令窗口(Command Window),在一段提示信息后,出现系统提示符“>>”.Matlab是一个交互系统,您可以在提示符后键入各种命令,通过上下箭头可以调出以前打入的命令,用滚动条可以查看以前的命令及其输出信息.如果对一条命令的用法有疑问的话,可以用Help菜单中的相应选项查询有关信息,也可以用help命令在命令行上查询,您可以试一下help、help help和help eig(求特征值的函数)命令.下面我们先从输入简单的矩阵开始掌握Matlab的功能.§1.2.1输入简单的矩阵输入一个小矩阵的最简单方法是用直接排列的形式.矩阵用方括号括起,元素之间用空格或逗号分隔,矩阵行与行之间用分号分开.例如输入:A=[1 2 3 ; 4 5 6 ; 7 8 0]系统会回答A =1 2 34 5 67 8 0表示系统已经接收并处理了命令,在当前工作区内建立了矩阵A.大的矩阵可以分行输入,用回车键代替分号,如:A=[ 1 2 34 5 67 8 0 ]结果和上式一样,也是A =1 2 34 5 67 8 0§1.2.2矩阵元素Matlab的矩阵元素可以是任何数值表达式.如:x=[ -1.3 sqrt(3) (1+2+3)*4/5]结果:x =-1.3000 1.7321 4.8000在括号中加注下标,可取出单独的矩阵元素.如:x(5)=abs(x(1))结果x =-1.3000 1.7321 4.8000 0 1.3000注:结果中自动产生了向量的第5个元素,中间未定义的元素自动初始为零.大的矩阵可把小的矩阵作为其元素来完成,如:A=[A; [10 11 12]]结果A =1 2 34 5 67 8 010 11 12小矩阵可用“:”从大矩阵中抽取出来,如:A=A(1:3,:);即从A中取前三行和所有的列,重新组成原来的A. (详细介绍参见第二节的相关内容)§1.2.3语句和变量Matlab的表述语句、变量的类型说明由Matlab系统解释和判断.Matlab语句通常形式为:变量=表达式或者使用其简单形式为:表达式表达式由操作符或其它特殊字符、函数和变量名组成.表达式的结果为一个矩阵,显示在屏幕上,同时保存在变量中以留用.如果变量名和“=”省略,则具有ans名(意思指回答)的变量将自动建立.例如:键入1900/81结果为:ans =23.4568需注意的问题有以下几点:*语句结束键入回车键,若语句的最后一个字符是分号,即“;”,则表明不输出当前命令的结果.*如果表达式很长,一行放不下,可以键入“…”(三个点,但前面必须有个空格,目的是避免将形如“数2 …”理解为“数2.”与“..”的连接,从而导致错误),然后回车.*变量和函数名由字母加数字组成,但最多不能超过63个字符,否则系统只承认前63个字符.*Matlab变量字母区分大小写,如A和a不是同一个变量,函数名一般使用小写字母,如inv(A)不能写成INV(A),否则系统认为未定义函数.§1.2.4 who和系统预定义变量输入who命令可检查工作空间中建立的变量,键入:who系统输出为:Your variables are:A ans x这里表明三个变量已由前面的例子产生了.但列表中列出的并不是系统全部的变量,系统还有以下内部变量:eps、pi、Inf、NaN变量eps在决定诸如矩阵的奇异性时,可作为一个容许差,容许差的初值为1.0到1.0以后计算机所能表示的下一个最大浮点数,IEEE在各种计算机、工作站和个人计算机上使用这个算法.用户可将此值置为任何其它值(包括0值).Matlab的内部函数pinc和rank以eps为缺省的容许差.变量pi是 ,它是用imag(log(-1))建立的.Inf表示无穷大.如果您想计算1/0S=1/0结果会是Warning:Divide by zeroS=Inf具有IEEE规则的机器,被零除后,并不引出出错条件或终止程序的运行,而产生一个警告信息和一个特殊值在计算方程中列出来.变量NaN表示它是个不定值.由Inf/Inf或0/0运算产生.要了解当前变量的信息请键入whos,屏幕将显示:Name Size Bytes ClassA 4x3 96 double arrayS 1x1 8 double arrayans 1x1 8 double arrayx 1x5 40 double arrayGrand total is 19 elements using 152 bytes从size及bytes项目可以看出,每一个矩阵实元素需8个字节的内存.4×3的矩阵使用96个字节,全部变量的使用内存总数为152个字节.自由空间的大小决定了系统变量的多少,如计算机上有虚拟内存的话,其可定义的变量个数会大大增加.§1.2.5数和算术表达式Matlab中数的表示方法和一般的编程语言没有区别.如:3 -99 0.00019.63972 1.6021E-20 6.02252e23在计算中使用IEEE浮点算法其舍入误差是eps.浮点数表示范围是10-308~10308.数学运算符有:+ 加- 减* 乘/ 右除\ 左除^ 幂这里1/4和4\1有相同的值都等于0.25(注意比较:1\4=4).只有在矩阵的除法时左除和右除才有区别.§1.2.6复数与矩阵在Matlab中输入复数首先应该建立复数单位:i=sqrt(-1)及j=sqrt(-1)之后复数可由下面语句给出:Z=3+4i (注意:在4与i之间不要留有任何空间!)输入复数矩阵有两个方便的方法,如:A=[1 2; 3 4] + i*[5 6; 7 8]和A=[1+5i 2+6i; 3+7i 4+8i]两式具有相等的结果.但当复数作为矩阵的元素输入时,不要留有任何空间,如1+5i,如在“+”号左右留有空格,就会被认为是两个分开的数.不过实际使用复数时并没有这么麻烦,系统有一个名为startup.m的Matlab命令文件,建立复数单位的语句也放在其中.当Matlab启动时,此文件自动执行,i和j将自动建立.§1.2.7输出格式任何Matlab语句执行结果都可在屏幕上显示,同时赋给指定的变量,没有指定变量时赋给ans.数字显示格式可由format命令来控制(Windows系统下的Matlab系统的数字显示格式可以由Option菜单中的Numerical Format菜单改变).format仅影响矩阵的显示,不影响矩阵的计算与存贮.(Matlab以双精度执行所有的运算)首先,如果矩阵元素是整数则矩阵显示就没有小数,如x=[-1 0 1],结果为:x=-1 0 1如果矩阵元素不是整数则输出形式有:(用命令:format 格式进行切换)格式中文解释说明format 短格式(缺省格式)Default. Same as SHORTformat short 短格式(缺省格式)Scaled fixed point format with 5 digits (只显示五位十进制数)format long 长格式Scaled fixed point format with 15 digitsformat short e 短格式e方式Floating point format with 5 digitsformat long e 长格式e方式Floating point format with 15 digitsformat short g 短格式g方式Best of fixed or floating point format with 5 digits format long g 长格式g方式Best of fixed or floating point format with 15 digits format hex 16进制格式Hexadecimal formatformat + +格式The symbols +, - and blank are printedfor positive, negative and zero elements.Imaginary parts are ignoredformat bank 银行格式Fixed format for dollars and centsformat rat 有理数格式Approximation by ratio of small integersformat compact 压缩格式Suppress extra line-feedsformat loose 自由格式Puts the extra line-feeds back in例如:x=[4/3 1.2345e-6]在不同的输出格式下的结果为:短格式 1.3333 0.0000短格式e方式 1.3333e+000 1.234e-006长格式 1.333333333333333 0.000001234500000长格式e方式 1.333333333333333e-000 1.23450000000000e-006有理数格式4/3 1/81004516进制格式3ff5555555555555 3eb4b6231abfd271+格式+ +对于短格式,如果矩阵的最大元素比数999999999大,或者比数0.0001小,则在打印时,将加入一个普通的长度因数.如y=1.e20*x,意为x被1020乘,结果为:y=1.0e+020*1.3333 0.0000“+”格式是显示大矩阵的一种紧凑方法,“+”,“-”和空格显示正数、负数和零元素.最后format compact命令压缩显示的矩阵,以允许更多的信息显示在屏幕上.§1.2.8 Help求助命令和联机帮助Help求助命令很有用,它对Matlab大部分命令提供了联机求助信息.您可以从Help 菜单中选择相应的菜单,打开求助信息窗口查询某条命令,也可以直接用help命令.键入help得到help列表文件,键入“help 指定项目”,如:键入help eig则提供特征值函数的使用信息.键入help [显示如何使用方括号等.键入help help显示如何利用help本身的功能.还有,键入lookfor <关键字>:可以从m文件的help中查找有关的关键字.§1.2.9 退出和存入工作空间退出Matlab可键入quit或exit或选择相应的菜单.中止Matlab运行会引起工作空间中变量的丢失,因此在退出前,应键入save命令,保存工作空间中的变量以便以后使用.键入save则将所有变量作为文件存入磁盘Matlab.mat中,下次Matlab启动时,键入load将变量从Matlab.mat中重新调出.save和load后边可以跟文件名或指定的变量名,如仅有save时,则只能存入Matlab.mat 中.如save temp命令,则将当前系统中的变量存入temp.mat中去,命令格式为:save temp x 仅仅存入x变量.save temp X Y Z 则存入X、Y、Z变量.load temp可重新从temp.mat文件中提出变量,load也可读ASCII数据文件.详细语法见联机帮助.第二节向量与矩阵运算Matlab能处理数、向量和矩阵.但一个数事实上是一个1×1的矩阵,1个n维向量也不过是一个1×n或n×1的矩阵.从这个角度上来讲,Matlab处理的所有的数据都是矩阵.Matlab的矩阵处理能力是非常灵活、强大的.以下我们将从矩阵的产生、基本运算、矩阵函数等几个方面来说明.§2.1向量及矩阵的生成除了我们在上节介绍的直接列出矩阵元素的输入方法,矩阵还可以通过几种不同的方式输入到Matlab中.§2.1.1 通过语句和函数产生1. 向量的产生除了直接列出向量元素(即所谓的“穷举法”)外,最常用的用来产生相同增量的向量的方法是利用“:”算符(即所谓的“描述法”).在Matlab中,它是一个很重要的字符.如:z=1:5z =1 2 3 4 5即产生一个1~5的单位增量是1的行向量,此为默认情况.用“:”号也可以产生单位增量不等于1的行向量,语法是把增量放在起始量和结尾量的中间.如:x=0:pi/4:pi即产生一个由0~pi的行向量,单位增量是pi/4=3.1416/4=0.7854.x =0 0.7854 1.5708 2.3562 3.1416也可以产生单位增量为负数的行向量.如:y=6:-1:1y =6 5 4 3 2 12. 矩阵的产生Matlab提供了一批产生矩阵的函数:zeros 产生一个零矩阵diag 产生一个对角矩阵ones 生成全1矩阵tril 取一个矩阵的下三角eye 生成单位矩阵triu 取一个矩阵的上三角magic 生成魔术方阵pascal 生成PASCAL矩阵例如:ones(3)ans =1 1 11 1 11 1 1eye(3)ans =1 0 00 1 00 0 1除了以上产生标准矩阵的函数外,Matlab还提供了产生随机(向量)矩阵的函数rand 和randn,及产生均匀级数的函数linspace、产生对数级数的函数logspace和产生网格的函数meshgrid等等.详细使用请查阅随机文档.“: ”冒号可以用来产生简易的表格,为了产生纵向表格形式,首先用冒号“: ”产生行向量,再进行转置,计算函数值的列,然后形成有二列的矩阵.例如命令:x=(0.0:0.2:3.0)';y=exp(-x).*sin(x);[x y]产生结果为:ans =0 00.2000 0.16270.4000 0.26100.6000 0.30990.8000 0.32231.0000 0.30961.2000 0.28071.4000 0.24301.6000 0.20181.8000 0.16102.0000 0.12312.2000 0.08962.4000 0.06132.6000 0.03832.8000 0.02043.0000 0.0070§2.1.2 通过后缀为.m的命令文件产生如有文件data.m,其中包括正文:A=[ 1 2 34 5 67 8 0]则用data命令执行data.m,可以产生名为A的矩阵.§2.2 矩阵操作在Matlab中可以对矩阵进行任意操作,包括改变它的形式,取出子矩阵,扩充矩阵,旋转矩阵等.其中最重要的操作符为“:”,它的作用是取出选定的行与列.例如:A(:,:) 代表A的所有元素;试比较A(:), 将A按列的方向拉成长长的1列(向量);A(:,J) 代表A的第J列;A(J:K) 代表A(J), A(J+1), …, A(K),如同A(:)的第J到第K个元素;A(:,J:K) 代表A(:,J), A(:,J+1), …, A(:,K),如此类推.对矩阵可以进行各种各样的旋转、变形、扩充:Matlab中有内部函数fliplr ( Flip matrix in the left/right direction),它对矩阵进行左右旋转.例x = 1 2 3 fliplr(x)为 3 2 14 5 6 6 5 4同样有flipud:x = 1 4 flipud(x)为 3 62 5 2 53 6 1 4矩阵的转置用符号“' ”表示:如A=[1 2 3; 4 5 6 ; 7 8 0]那么:计算B=A'B =1 4 72 5 83 6 0符号“' ”为矩阵的转置,如果Z为复矩阵,则Z'为它的复数共轭转置,非共轭转置使用Z.' 或conj(Z')求得.reshape改变矩阵的形状,这是什么意思呢?可举一个例子来说明.A=[A;[10 11 12]]A =1 2 34 5 67 8 010 11 12则reshape(A,2,6)ans =1 72 83 04 105 116 12 可见,reshape 是将矩阵元素以列为单位进行重组,原来4×3的矩阵变为了2×6的矩阵.那么以下的语句也不难理解了,它将矩阵A 按列打开(函数返回矩阵A 的行数与列数).reshape(A,1,size(A,1)*size(A,2)),它等价于A(:)' .还有函数rot90,它可以将矩阵进行各种90度的旋转;tril 及triu 取出矩阵的下三角及上三角阵等.详细的用法可以在需要使用时查阅手册.第三节 矩阵的基本运算§3.1 加和减如矩阵A 和B 的维数相同,则A+B 与A-B 表示矩阵A 与B 的和与差.如果矩阵A 和B 的维数不匹配,Matlab 会给出相应的错误提示信息.如:A= B=1 2 3 1 4 7 4 5 6 2 5 8 7 8 0 3 6 0 C =A+B 返回:C =2 6 10 6 10 14 10 14 0如果运算对象是个标量(即1×1矩阵),可和其它矩阵进行加减运算.例如: x= -1 y=x-1= -20 -1 2 1§3.2矩阵乘法Matlab 中的矩阵乘法有通常意义上的矩阵乘法,也有Kronecker 乘法,以下分别介绍. §3.2.1 矩阵的普通乘法矩阵乘法用“ * ”符号表示,当A 矩阵列数与B 矩阵的行数相等时,二者可以进行乘法运算,否则是错误的.计算方法和线性代数中所介绍的完全相同.如:A=[1 2 ; 3 4]; B=[5 6 ; 7 8]; C=A*B , 结果为C=⎪⎪⎭⎫ ⎝⎛4321×⎪⎪⎭⎫ ⎝⎛8765=⎪⎪⎭⎫ ⎝⎛⨯+⨯⨯+⨯⨯+⨯⨯+⨯8463745382617251=⎪⎪⎭⎫ ⎝⎛50432219 即Matlab 返回: C =19 22 43 50如果A 或B 是标量,则A*B 返回标量A (或B )乘上矩阵B (或A )的每一个元素所得的矩阵.§3.2.2 矩阵的Kronecker 乘法 对n ×m 阶矩阵A 和p ×q 阶矩阵B ,A 和B 的Kronecher 乘法运算可定义为:⎪⎪⎪⎪⎪⎭⎫ ⎝⎛=⊗=B a B a B a B a B a B a B a B a B a B A C nm n n m m (21)2222111211 由上面的式子可以看出,Kronecker 乘积A ⊗B 表示矩阵A 的所有元素与B 之间的乘积组合而成的较大的矩阵,B ⊗A 则完全类似.A ⊗B 和B ⊗A 均为np ×mq 矩阵,但一般情况下A ⊗B ≠B ⊗A .和普通矩阵的乘法不同,Kronecker 乘法并不要求两个被乘矩阵满足任何维数匹配方面的要求.Kronecker 乘法的Matlab 命令为C=kron(A,B),例如给定两个矩阵A 和B :A =1234⎛⎝ ⎫⎭⎪ B=132246⎛⎝ ⎫⎭⎪则由以下命令可以求出A 和B 的Kronecker 乘积C :A=[1 2; 3 4]; B=[1 3 2; 2 4 6]; C=kron(A,B) C =1 32 2 6 4 2 4 6 4 8 123 9 64 12 8 6 12 18 8 16 24作为比较,可以计算B 和A 的Kronecker 乘积D ,可以看出C 、D 是不同的: A=[1 2; 3 4]; B=[1 3 2; 2 4 6]; D=kron(B,A) D =1 2 3 6 2 4 3 4 9 12 6 8 2 4 4 8 6 12 6 8 12 16 18 24§3.3 矩阵除法在Matlab 中有两种矩阵除法符号:“\”即左除和“/”即右除.如果A 矩阵是非奇异方阵,则A\B 是A 的逆矩阵乘B ,即inv(A)*B ;而B/A 是B 乘A 的逆矩阵,即B*inv(A).具体计算时可不用逆矩阵而直接计算.通常:x=A\B 就是A*x=B 的解; x=B/A 就是x*A=B 的解.当B 与A 矩阵行数相等可进行左除.如果A 是方阵,用高斯消元法分解因数.解方程:A*x(:, j)=B(:, j),式中的(:, j)表示B 矩阵的第j 列,返回的结果x 具有与B 矩阵相同的阶数,如果A 是奇异矩阵将给出警告信息.如果A 矩阵不是方阵,可由以列为基准的Householder 正交分解法分解,这种分解法可以解决在最小二乘法中的欠定方程或超定方程,结果是m ×n 的x 矩阵.m 是A 矩阵的列数,n 是B 矩阵的列数.每个矩阵的列向量最多有k 个非零元素,k 是A 的有效秩.右除B/A 可由B/A=(A'\B')'左除来实现.§3.4矩阵乘方A^P 意思是A 的P 次方.如果A 是一个方阵,P 是一个大于1的整数,则A^P 表示A 的P 次幂,即A 自乘P 次.如果P 不是整数,计算涉及到特征值和特征向量的问题,如已经求得:[V,D]=eig(A),则:A^P=V*D.^P/V (注:这里的.^表示数组乘方,或点乘方,参见后面的有关介绍)如果B 是方阵, a 是标量,a^B 就是一个按特征值与特征向量的升幂排列的B 次方程阵. 如果a 和B 都是矩阵,则a^B 是错误的.§3.5 矩阵的超越函数在Matlab中解释exp(A)和sqrt(A)时曾涉及到级数运算,此运算定义在A的单个元素上.Matlab可以计算矩阵的超越函数,如矩阵指数、矩阵对数等.一个超越函数可以作为矩阵函数来解释,例如将“m”加在函数名的后边而成expm(A)和sqrtm(A),当Matlab运行时,有下列三种函数定义:expm 矩阵指数logm 矩阵对数sqrtm 矩阵开方所列各项可以加在多种m文件中或使用funm.请见应用库中sqrtm.m,1ogm.m,funm.m 文件和命令手册.§3.6数组运算数组运算由线性代数的矩阵运算符“*”、“/”、“\”、“^”前加一点来表示,即为“.*”、“./”、“.\”、“.^”.注意没有“.+”、“.-”运算.§3.6.1数组的加和减对于数组的加和减运算与矩阵运算相同,所以“+”、“-”既可被矩阵接受又可被数组接受.§3.6.2数组的乘和除数组的乘用符号.*表示,如果A与B矩阵具有相同阶数,则A.*B表示A和B单个元素之间的对应相乘.例如x=[1 2 3]; y=[ 4 5 6];计算z=x.*y结果z=4 10 18数组的左除(.\)与数组的右除(./),由读者自行举例加以体会.§3.6.3 数组乘方数组乘方用符号.^表示.例如:键入:x=[ 1 2 3]y=[ 4 5 6]则z=x.^y=[1^4 2^5 3^6]=[1 32 729](1) 如指数是个标量,例如x.^2,x同上,则:z=x.^2=[1^2 2^2 3^2]=[ 1 4 9](2) 如底是标量,例如2 .^[x y] ,x、y同上,则:z=2 .^[x y]=[2^1 2^2 2^3 2^4 2^5 2^6]=[2 4 8 16 32 64] 从此例可以看出Matlab算法的微妙特性,虽然看上去与其它乘方没什么不同,但在2和“.”之间的空格很重要,如果不这样做,解释程序会把“.”看成是2的小数点.Matlab 看到符号“^”时,就会当做矩阵的幂来运算,这种情况就会出错,因为指数矩阵不是方阵.§3.7 矩阵函数Matlab的数学能力大部分是从它的矩阵函数派生出来的,其中一部分装入Matlab本身处理中,它从外部的Matlab建立的M文件库中得到,还有一些由个别的用户为其自己的特殊的用途加进去的.其它功能函数在求助程序或命令手册中都可找到.手册中备有为Matlab 提供数学基础的LINPACK和EISPACK软件包,提供了下面四种情况的分解函数或变换函数:(1)三角分解;(2)正交变换;(3) 特征值变换;(4)奇异值分解.§3.7.1三角分解最基本的分解为“LU”分解,矩阵分解为两个基本三角矩阵形成的方阵,三角矩阵有上三角矩阵和下三角矩阵.计算算法用高斯变量消去法.从lu函数中可以得到分解出的上三角与下三角矩阵,函数inv得到矩阵的逆矩阵,det 得到矩阵的行列式.解线性方程组的结果由方阵的“\”和“/”矩阵除法来得到.例如:A=[ 1 2 34 5 67 8 0]LU分解,用Matlab的多重赋值语句[L,U]=lu(A)得出L =0.1429 1.0000 00.5714 0.5000 1.00001.0000 0 0U =7.0000 8.0000 00 0.8571 3.00000 0 4.5000注:L是下三角矩阵的置换,U是上三角矩阵的正交变换,分解作如下运算,检测计算结果只需计算L*U即可.求逆由下式给出:x=inv(A)x =-1.7778 0.8889 -0.11111.5556 -0.7778 0.2222-0.1111 0.2222 -0.1111从LU分解得到的行列式的值是精确的,d=det(U)*det(L)的值可由下式给出:d=det(A)d =27直接由三角分解计算行列式:d=det(L)*det(U)d =27.0000为什么两种d的显示格式不一样呢? 当Matlab做det(A)运算时,所有A的元素都是整数,所以结果为整数.但是用LU分解计算d时,L、U的元素是实数,所以Matlab产生的d也是实数.例如:线性联立方程取b=[ 135]解Ax=b方程,用Matlab矩阵除得到x=A\b结果x=0.33330.33330.0000由于A=L*U,所以x也可以有以下两个式子计算:y=L\b,x=U\y.得到相同的x值,中间值y为:y =5.00000.28570.0000Matlab中与此相关的函数还有rcond、chol和rref.其基本算法与LU分解密切相关.chol函数对正定矩阵进行Cholesky分解,产生一个上三角矩阵,以使R'*R=X.rref用具有部分主元的高斯-约当消去法产生矩阵A的化简梯形形式.虽然计算量很少,但它是很有趣的理论线性代数.为了教学的要求,也包括在Matlab中.§3.7.2正交变换“QR”分解用于矩阵的正交-三角分解.它将矩阵分解为实正交矩阵或复酉矩阵与上三角矩阵的积,对方阵和长方阵都很有用.例如A=[ 1 2 34 5 67 8 910 11 12]是一个降秩矩阵,中间列是其它二列的平均,我们对它进行QR分解:[Q,R]=qr(A)Q =-0.0776 -0.8331 0.5444 0.0605-0.3105 -0.4512 -0.7709 0.3251-0.5433 -0.0694 -0.0913 -0.8317-0.7762 0.3124 0.3178 0.4461R =-12.8841 -14.5916 -16.29920 -1.0413 -2.08260 0 0.00000 0 0可以验证Q*R就是原来的A矩阵.由R的下三角都给出0,并且R(3,3)=0.0000,说明矩阵R与原来矩阵A都不是满秩的.下面尝试利用QR分解来求超定和降秩的线性方程组的解.例如:b=[ 1357]讨论线性方程组Ax=b,我们可以知道方程组是超定的,采用最小二乘法的最好结果是计算x=A\b.结果为:Warning: Rank deficient, rank = 2 tol = 1.4594e-014x =0.50000.1667我们得到了缺秩的警告.用QR分解法计算此方程组分二个步骤:y=Q'*bx=R\y求出的y值为y =-9.1586-0.34710.00000.0000x的结果为Warning: Rank deficient, rank = 2 tol = 1.4594e-014x =0.50000.1667用A*x来验证计算结果,我们会发现在允许的误差范围内结果等于b.这告诉我们虽然联立方程Ax=b是超定和降秩的,但两种求解方法的结果是一致的.显然x向量的解有无穷多个,而“QR”分解仅仅找出了其中之一.§3.7.3奇异值分解在Matlab中三重赋值语句[U,S,V]=svd(A)在奇异值分解中产生三个因数:A=U*S*V 'U矩阵和V矩阵是正交矩阵,S矩阵是对角矩阵,svd(A)函数恰好返回S的对角元素,而且就是A的奇异值(其定义为:矩阵A'*A的特征值的算术平方根).注意到A矩阵可以不是方的矩阵.奇异值分解可被其它几种函数使用,包括广义逆矩阵pinv(A)、秩rank(A)、欧几里德矩阵范数norm(A,2)和条件数cond(A).§3.7.4 特征值分解如果A是n×n矩阵,若λ满足Ax=λx,则称λ为A的特征值,x为相应的特征向量.函数eig(A)返回特征值列向量,如果A是实对称的,特征值为实数.特征值也可能为复数,例如:A=[ 0 1-1 0]eig(A)产生结果ans =0 + 1.0000i0 - 1.0000i如果还要求求出特征向量,则可以用eig(A)函数的第二个返回值得到:[x,D]=eig(A)D的对角元素是特征值.x的列是相应的特征向量,以使A*x=x*D.计算特征值的中间结果有两种形式:Hessenberg形式为hess(A),Schur形式为schur(A).schur形式用来计算矩阵的超越函数,诸如sqrtm(A)和logm(A).如果A和B是方阵,函数eig(A,B)返回一个包含一般特征值的向量来解方程Ax=λBx双赋值获得特征向量[X,D]=eig(A,B)产生特征值为对角矩阵D.满秩矩阵X的列相应于特征向量,使A*X=B*X*D,中间结果由qz(A,B)提供.§3.7.5秩Matlab计算矩阵A的秩的函数为rank(A),与秩的计算相关的函数还有:rref(A)、orth(A)、null(A)和广义逆矩阵pinv(A)等.利用rref(A),A的秩为非0行的个数.rref方法是几个定秩算法中最快的一个,但结果上并不可靠和完善.pinv(A)是基于奇异值的算法.该算法消耗时间多,但比较可靠.其它函数的详细用法可利用Help求助.第四节 Matlab 中的图形§4.1 二维作图绘图命令plot 绘制x-y 坐标图;loglog 命令绘制对数坐标图;semilogx 和semilogy 命令绘制半对数坐标图;polor 命令绘制极坐标图.§4.1.1 基本形式如果y 是一个向量,那么plot(y)绘制一个y 中元素的线性图.假设我们希望画出 y=[0., 0.48, 0.84, 1., 0.91, 6.14 ] 则用命令:plot(y)它相当于命令:plot(x, y),其中x=[1,2,…,n]或x=[1;2;…;n],即向量y 的下标编号, n 为向量y 的长度Matlab 会产生一个图形窗口,显示如下图形,请注意:坐标x 和y 是由计算机自动绘出的.12345601234567图4.1.1.1 plot([0.,0.48,0.84,1.,0.91,6.14])上面的图形没有加上x 轴和y 轴的标注,也没有标题.用xlabel ,ylabel ,title 命令可以加上.如果x ,y 是同样长度的向量,plot(x,y)命令可画出相应的x 元素与y 元素的x-y 坐标图.例:x=0:0.05:4*pi; y=sin(x); plot(x,y) grid on, title(' y=sin( x ) 曲线图' ) xlabel(' x = 0 : 0.05 : 4Pi ') 结果见下图.024********-1-0.8-0.6-0.4-0.20.20.40.60.81 y=sin( x ) 曲线图x = 0 : 0.05 : 4Pi图4.1.1.2 y=sin(x)的图形title图形标题xlabel x坐标轴标注ylabel y坐标轴标注text 标注数据点grid 给图形加上网格hold 保持图形窗口的图形表4.1.1.1 Matlab图形命令§4.1.2 多重线在一个单线图上,绘制多重线有三种办法.第一种方法是利用plot的多变量方式绘制:plot(x1,y1,x2,y2,...,xn,yn)x1,y1,x2,y2,...,xn,yn是成对的向量,每一对x, y在图上产生如上方式的单线.多变量方式绘图是允许不同长度的向量显示在同一图形上.第二种方法也是利用plot绘制,但加上hold on/off命令的配合:plot(x1,y1)hold onplot(x2,y2)hold off第三种方法还是利用plot绘制,但代入矩阵:如果plot用于两个变量plot(x,y),并且x,y是矩阵,则有以下情况:(1)如果y是矩阵,x是向量,plot(x,y)用不同的画线形式绘出y的行或列及相应的x 向量,y的行或列的方向与x向量元素的值选择是相同的.(2)如果x是矩阵,y是向量,则除了x向量的线族及相应的y向量外,以上的规则也适用.(3)如果x,y是同样大小的矩阵,plot(x,y)绘制x的列及y相应的列.还有其它一些情况,请参见Matlab的帮助系统.§4.1.3 线型和颜色的控制如果不指定划线方式和颜色,Matlab会自动为您选择点的表示方式及颜色.您也可以用不同的符号指定不同的曲线绘制方式.例如:plot(x,y,'*') 用'*'作为点绘制的图形.plot(x1,y1,':',x2,y2,'+') 用':'画第一条线,用'+'画第二条线.线型、点标记和颜色的取值有以下几种:线型点标记颜色- 实线. 点y 黄: 虚线o 小圆圈m 棕色-. 点划线x 叉子符 c 青色-- 间断线+ 加号r 红色* 星号g 绿色s 方格 b 蓝色d 菱形w 白色^ 朝上三角k 黑色v 朝下三角> 朝右三角< 朝左三角p 五角星h 六角星表4.1.3.1线型和颜色控制符如果你的计算机系统不支持彩色显示,Matlab将把颜色符号解释为线型符号,用不同的线型表示不同的颜色.颜色与线型也可以一起给出,即同时指定曲线的颜色和线型.例如:t=-3.14:0.2:3.14;。
MATLAB概述

MATLAB概述
MATLAB是一种用于科学计算、算法开发、数据可视化和图像处理的
高级交互式编程语言和环境。
它非常适合那些希望快速实现算法的研究人
员和分析师。
MATLAB是由The MathWorks公司开发的,该公司一直在推
广这种语言和环境,旨在加速科学计算领域的研究和开发。
MATLAB的数学功能和函数十分强大,并且可以实现各种大数据分析
领域的计算。
它也可以应用于科学计算和工程计算,可以大大提高解决问
题的效率。
MATLAB还可以用来实现数据可视化,它可以利用绘图函数或
者图形界面来显示数据的模拟和可视化结果,从而更直观地解释数据。
另外,MATLAB还可以用来编写算法并对其进行验证,便于深入研究。
使用MATLAB可以快速获得算法及其性能的见解,可以改进算法,提高其
性能。
2024版Matlab简介PPT课件

拟合曲线原理
通过已知数据点,寻找最佳函数 逼近的方法。
插值法分类
线性插值、多项式插值、样条插 值等。
Matlab实现
使用Matlab内置函数进行插值和 拟合操作,如`interp1`、 `polyfit`等。
数值积分、微分运算过程剖析
数值积分基本概念
通过数值方法求解定积分的近 似值。
1
数值积分方法
应用实例 通过具体实例演示特征值和特征向量在计算物理、工程等 领域的应用。
矩阵分解方法及其应用场景
矩阵分解定义
介绍矩阵分解的概念和目的。
分解方法
介绍常见的矩阵分解方法,如LU 分解、QR分解、SVD分解等,并 阐述它们的计算步骤和原理。
应用场景
讨论矩阵分解在数值计算、信号 处理、图像处理等领域的应用场 景,并给出具体实例。
Matlab实现
使用Matlab内置函数进行最优化问题求解,如`fmincon`、`ga`等。
偏微分方程数值解法
01
偏微分方程基本概 念
包含未知函数及其偏导数的方程。
02
偏微分方程数值解 法
有限差分法、有限元法、谱方法 等。
03
Matlab实现
使用Matlab内置函数或工具箱进 行偏微分方程数值求解,如PDE Toolbox等。
表达式书写规则
在书写表达式时,需要注意运算符的优先级 和结合性,以及使用括号来改变运算顺序。
流程控制语句使用方法
条件语句
01
Matlab中常用的条件语句有if语句和switch语句,用于根据条
件执行不同的代码块。
循环语句
02
Matlab提供了for循环和while循环两种循环结构,用于重复执
一MATLAB概述
Fuzzy Logic:模糊逻辑
Nerual NetWork:神经网络
Symbolic Math:符号数学
5
Hale Waihona Puke (2)MATLAB旳桌面环境
Command window:命令窗口 Workspace:工作空间 Current Directory:目前途径 Command History:历史命令 Launch Pad:公布平台
Stateflow Coder:自动代码生成
4
经典工具箱:
Signal processing:信号处理
Image processing:图像处理
Communication:通信
Wavlet:小波
Filter Design:滤波器设计
Control System:控制系统
System Identification:系统辨识
一 MATLAB概述
主要内容: (1)MATLAB发展历史和产品族简介 (2)MATLAB旳桌面环境 (3)MATLAB旳主要功能 (4)MATLAB通用指令(要点) (5)MATLAB帮助系统
1
(1) MATLAB发展历史和产品族简介
MATLAB源于美国Cleve Moler博士开发旳 两个线性代数软件包EISPACK和LINPACK, 随即,Cleve Moler博士与其别人合作开办了 Mathworks企业,推动了MATLAB旳迅速发展。 如今已成为一种集数值计算、符号计算、图形 系统以及多种专业工具箱与一体旳高级语言。
下载地址:
❖功能强大,操作简朴!
2
MATLAB发展历史 1984年,MATLAB第1版(DOS版) 1992年,MATLAB4.0版 1994年,MATLAB 4.2版 1997年,MATLAB 5.0版 1999年,MATLAB 5.3版 2023年,MATLAB 6.0版 2023年,MATLAB 6.1版 2023年,MATLAB 6.5版 2023年9月, 版 2023年6月,MATLAB 7.0版 2023年9月, 版 2023年3月, 版 2023年9月, MATLAB7.1版 2023年3月, MATLAB7.2版 2023年9月, MATLAB7.3版 2023年3月,MATLAB7.4版
matlab是什么编程语言-matlab是编程语言吗
matlab是什么编程语言?matlab是编程语言吗一、matlab定义The MathWorks公司的MATLAB 是一种用于算法开发、数据可视化、数据分析以及数值计算的高级技术计算语言和交互式环境。
使用 MATLAB,您可以较使用传统的编程语言(如 C、C++和 F or tran)更快地解决技术计算问题。
MATLAB 是美国MathWorks公司出品的商业数学软件,用于算法开发、数据可视化、数据分析以及数值计算的高级技术计算语言和交互式环境,主要包括MATLAB和Simulink两大部分。
MATLAB是矩阵实验室(Matrix Laboratory)的简称,和Mathemat ic a、Maple并称为三大数学软件。
它在数学类科技应用软件中在数值计算方面首屈一指。
MATLAB可以进行矩阵运算、绘制函数和数据、实现算法、创建用户界面、连接其他编程语言的程序等,主要应用于工程计算、控制设计、信号处理与通讯、图像处理、信号检测、金融建模设计与分析等领域。
MATLAB的基本数据单位是矩阵,它的指令表达式与数学、工程中常用的形式十分相似,故用MATLAB来解算问题要比用C,FORTRAN等语言完相同的事情简捷得多,并且mathwork也吸收了像Maple等软件的优点,使MATLAB成为一个强大的数学软件。
在新的版本中也加入了对C,FORTRAN,C++ ,JAVA的支持。
可以直接调用,用户也可以将自己编写的实用程序导入到MATLAB函数库中方便自己以后调用,此外许多的MATLAB爱好者都编写了一些经典的程序,用户可以直接进行下载就可以用。
二、matlab是编程语言吗?严格的来说matlab不算是编程语言。
只有你有C语言的基础,Matlab就很容易。
Matlab是边解释边执行。
另外Matlab集成了大量的自带函数,比如矩阵计算,画图,谱分析。
这就不符合标准编程语言的特点。
你如果明白类和对象的概念,对用好Matlab很有帮助。
MATLAB及其应用概述
在Matlab中,可以使用方括号[]来索引矩阵的元素。例如, `A(1,2)`表示矩阵A的第1行第2列的元素。
矩阵操作
可以对矩阵进行各种操作,如加法、减法、乘法等。例如,`B = A + C`表示矩阵A和矩阵C相加,结果保存在矩阵B中。
矩阵的运算
01
02
03
矩阵加法
将两个相同大小的矩阵对 应元素相加,得到一个新 的矩阵。
常量
在Matlab中,常量是在程序运行过程中不能改变的值,如pi 和Inf。
Matlab的运算符
算术运算符
包括加、减、乘、除等基本算术运算。
关系运算符
用于比较两个值的大小关系,返回逻辑值。
逻辑运算符
包括与、或和非等逻辑运算,返回逻辑值。
赋值运算符
用于将运算结果赋值给变量,如“=”、“+=”、“-=”等。
特征值与特征向量
Matlab可以计算矩阵的特征 值和特征向量。
线性方程组求解
Matlab可以求解线性方程组 ,包括高斯消元法、LU分解 等。
非线性方程求解
迭代法
01
Matlab提供了多种迭代法求解非线性方程,如牛顿法、二分法
等。
函数零点查找
02
Matlab可以找到函数的零点,通过迭代或搜索算法实现。
矩阵减法
将一个矩阵的对应元素减 去另一个矩阵的对应元素, 得到一个新的矩阵。
矩阵乘法
将一个矩阵的每一行与另 一个矩阵的每一列对应元 素相乘,得到一个新的矩 阵。
矩阵的函数运算
01
矩阵求和
使用`sum`函数可以对矩阵的列或行 进行求和。例如,`sum(A)`表示对矩 阵A的所有元素求和,`sum(A,2)`表 示对矩阵A的每一列求和。
MatLab中文版(word版)第二章
目录第二章MA TLAB基础 (1)2.1 变量和数组 (1)2.2 MA TLAB变量的初始化 (3)2.2.1 用赋值语句初始化变量 (3)2.2.2 用捷径表达式(short expressions)来赋值 (4)2.2.3 用内置函数来初始化 (5)2.2.4用关键字input初始化变量 (6)测试2.1 (6)2.3 多维数组 (6)2.3.1 多维数组在内存中的存储 (7)2.3.1 用单个下标访问多标数组 (8)2.4 子数组 (8)2.4.1 end函数 (9)2.4.2 子数组在左边的赋值语句的使用 (9)2.4.3 用一标量来给子数组赋值 (10)2.5 特殊变量 (11)测试2.2 (11)2.6 显示输出数据 (12)2.6.1 改变默认格式 (12)2.6.2 disp函数 (13)2.6.3 用fprintf函数格式化输出数据 (13)2.7 数据文件 (13)测试2.3 (14)2.8 标量运算和数组运算 (15)2.8.1 标量运算符 (15)2.8.2 数组运算和矩阵运算 (15)例2.1 (16)2.9 运算的优先级 (17)例2.2 (18)测试2.4 (18)2.10 MATLAB的内建函数 (19)2.10.1 选择性结果 (19)2.10.2 带数组输入的MA TLAB函数的应用 (19)2.10.3 常见的MATLAB函数 (19)2.11 画图入门 (19)2.11.1 简单的xy画图的应用 (20)2.11.2 打印图象 (21)2.11.3 联合作图 (22)2.11.4 线的颜色,线的形式,符号形式和图例 (22)2.11.5 对数尺度 (24)2.12 例子 (25)例2.3 (25)例2.4 (26)例2.5 (28)2.13 调试MATLAB程序 (29)2.14 总结 (30)2.14.1 好的编程习惯 (31)2.14.2 MA TLAB总结 (31)2.15 练习 (33)2.1 (33)2.2 (33)2.3 (33)2.4 (33)2.5 (34)2.6 (34)2.7 (34)2.8 (34)2.9 (34)2.10 (34)2.11 (35)2.12 (35)2.13 (35)2.14 (35)2.15 (35)2.16 (36)2.17 (36)2.18 (36)第二章MATLAB 基础在本章我将向大家介绍MATLAB 的基本元素。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
36.2603Matlab Extensions for the Development, Testing and Verification of Real-Time DSP SoftwareDavid P. Magee, Ph.D.Texas Instruments12500 TI Boulevard, MS 8649Dallas, TX 75243 (214) 480-1236magee@ABSTRACTThe purpose of this paper is to present the required tools for the development, testing and verification of DSP software in Matlab. The paper motivates a DSP Simulator concept that can be combined with the MATLAB executable interface to develop, evaluate and test DSP software within a single environment. Programming guidelines and optimization results are also provided to demonstrate the effectiveness of the intrinsics software development approach.Categories and Subject DescriptorsD.2.6 [Programming Languages ]: Programming Environments – Integrated Environments.General TermsAlgorithms, Design, Experimentation, Verification.KeywordsC Intrinsics, Matlab, DSP Software, Optimization, Verification1. INTRODUCTIONOver the past ten years, Matlab has become the preferred algorithm development, verification and simulation tool for many engineers. With its suite of application specific toolboxes, an engineer can quickly integrate and test newly developed algorithms with existing toolbox modules to create an algorithm simulation for a particular application. With this simulation, the performance of the individual modules as well as the entire algorithm chain can be evaluated. For system modeling and simulation requirements, Simulink has become a popular choice for many engineers. For simulating and generating embedded DSP software for a system, the Real-Time Workshop is available within Simulink. The tool contains a blockset of algorithms for a variety of applications so that the user can co-simulate the bit true performance of the DSP software with other algorithms and components in the system. For each algorithm in the blockset, there is a corresponding library function that has been optimized for the target DSP. Once the system performance has been validated in simulation, target software can be generated bylinking the appropriate modules from the library in the preferred software development environment.This bit true simulation and software development flow from MathWorks works well for algorithms that exist in the Real-Time Workshop blockset because there is an optimized version of the software for the target DSP in the library. However, the Real-Time Workshop tool currently cannot generate optimized DSP software from a general m-file in Matlab or a general Simulink block diagram. As a result, DSP software engineers are forced to translate Matlab files to DSP software manually.However, steps are underway to automate this process so that DSP software can be automatically generated from Matlab and Simulink. This paper will discuss a design flow for DSP software development and testing within Matlab to ensure that efficient and optimized DSP instruction level code is generated by the DSP compiler. The concepts and tools discussed in this paper can then be leveraged to develop an automated tool.2. DESIGN FLOWMatlab provides a quick and easy mechanism for engineers to conduct algorithm exploration and experimentation. This work often occurs long before a product or a prototype has even been considered. Once a design proceeds from the initial stages of development, a system architecture must be developed and hardware/software partitioning decisions are made. From a verification perspective, the fixed-point implementation of each algorithm must be compared to its floating-point equivalent. Many times, the original Matlab code is used as the floating point reference. The issue becomes how to represent the hardware or software implementation in Matlab.For software, the representation can be performed using a DSP instruction set simulator written in C [1,2]. Using Matlab’s executable (MEX) file interface, this simulator can be compiled with DSP software written in C/C++ to create an object file that can be executed directly from the Matlab prompt. Figure 1 shows a block diagram of the individual components required for this design flow. Currently, the C/C++ code is generated manually, i.e. by the DSP software engineer. However, automation of this step is being investigated by several companies [3].The process begins with the DSP software engineer defining the MEX interface between Matlab and the C/C++ code. This process includes defining the input arguments, the output arguments, the argument data types and the argument data sizes. Matlab has many pre-defined functions for handling input data, output data, temporary data and dynamic memory allocation. ForPermission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee.DAC 2005, June 13-17, 2005, Anaheim, California, USA. Copyright 2005 ACM 1-59593-058-2/05/0006…$5.00.a complete list of functions and a description of the MEX interface, see [4].The next step is to interface the MEX function to the DSP software functions. By properly mapping the MEX function input and output data to the input and output data for the DSP software function, the DSP software function prototypes can remain the same in the Matlab simulation and the real DSP hardware. Note that special care must be taken when passing complex valued arrays of data from the Matlab environment to the DSP software function. Matlab stores a complex data array in memory as two arrays: the first array contains all of the real parts and the second array contains all of the imaginary parts. However in DSP memory, a complex data array should be stored as real and imaginary pairs, which is equivalent to interleaving the Matlab data.Figure 1. DSP Software Development in MatlabThe last step is for the DSP software engineer to write the relevant DSP software for the particular algorithm. This software can be strictly C/C++ code or can more tightly coupled to the target processor using intrinsics and the DSP Simulator. The use of the DSP Simulator will be discussed in the next section. Once all of the C/C++ software is written, it is then compiled in the Matlab host environment and then executed like any other function from the Matlab prompt.The importance of a single design, development and verification environment should not be underestimated. The time savings for software development, the number of engineers required to support the floating-point and fixed-point development, the ability for more thorough testing and the ability to compare floating-point vs. fixed-point performance are some of the tangible benefits.3. DSP SIMULATORWith the DSPs and associated compiler features from Texas Instruments (TI), the DSP Simulator can be designed to numerically represent the instruction set of the processor so that the C/C++ software can make direct calls to assembly instructions. This mapping can occur because the TI compiler recognizes special C instructions called intrinsics. Intrinsics are special function calls in C that the compiler recognizes and understands so that it can map them directly to the corresponding assembly instruction. The DSP Simulator is simply a collection of C functions that represent the mathematical behavior for each intrinsic. Figure 2 shows the _add2() intrinsic as an example.Figure 2. Intrinsic Example: _add2()To further demonstrate how a DSP software engineer might write a particular algorithm using intrinsics, the radix-2 portion of an FFT algorithm is shown in Figure 3.Figure 3. Radix-2 FFT StageDSP Simulator604Notice that the _mpyhir() and _mpylir() intrinsics are used to twiddle the real and imaginary parts of the radix-2 stage. Since the real and imaginary parts of the complex data are stored as the upper and lower 16 bit parts of a 32 memory location, these intrinsics, which perform special dot products, can compute the complex multiplication in fewer cycles than the common implementation using multiplier and adders.The benefit of this programming style is that the DSP software engineer can write “assembly” level programs in a C/C++ programming environment and avoid the associated hassles of assembly programming (pipeline scheduling, register allocation, unit allocation, stack manipulation, parallel instruction debugging, etc.). These burdens are placed on the compiler, which is better designed to handle such issues. Furthermore, since the same fixed-point C/C++ software can simulated in Matlab and compiled to run on the DSP, the software engineer only has to maintain one version of C/C++ software for a particular algorithm. This benefit can greatly impact the support requirements for a system, particularly when the design becomes a full product.4. PROGRAMMING GUIDELINESTo get the best optimization results from the TI compiler, the C/C++ software must be structured so that it compiler friendly. This process can be broken down into several steps. First, the data path for the software must be carefully designed. The endianness of the input and output data for the algorithm must be prescribed as well as the storage format for complex data. Data alignment (8/16/32 bit boundaries) of input, output and internal data is also an important design consideration for the data path. As part of this consideration, the incrementing of the input and output data should also be considered. Finally, the load and store capabilities of the target processor should be well understood because most software optimizations are limited by data bus bandwidth.Once the data path for the algorithms has been determined, the instruction set of the processor must be studied. The particular set of intrinsics supported by the compiler for the target processor must be understood. This information along with the DSP processor architecture, will determine the number of multiplications and additions that can occur per clock cycle. It is also important to understand the level of intrinsics support for manipulating real and complex data types. For example, many new processors can perform several complex multiples per cycle if the data is stored appropriately. Finally, the register sizes and the associated instructions must be understood when using the corresponding intrinsic.After considering these guidelines, the DSP software engineer must map the algorithm to target DSP instruction set. For TI DSPs, the registers are often 32 bits. As a result, it is convenient to compress four 8 bit real values, two 16 bit real values or one 32 bit real value into a 32 bit memory location. Similarly, it is convenient to map two 16 bit complex values (8 bit real/8 bit imag) or one 32 bit complex value (16 bit real/16 bit imag) into a 32 bit memory location. For 64 bit complex values (32 bit real/32 bit imag), two 32 bit registers are required. Once the data has been compressed in memory, the mathematical operations required by the algorithm must be mapped to the appropriate set of intrinsics. The easiest and most straightforward mapping is one-to-one. However, most algorithms are not initially designed with a DSP instruction set in mind. Thus, the DSP software engineer should consider and evaluate different mappings to achieve the most efficient software in terms of DSP cycles required for execution while maintaining a mathematically equivalent implementation.Once the algorithms have been mapped to DSP software with intrinsic function calls, additional compiler directives can be added to the software to improve compilation of the software. For example, pragmas such as MUST_ITERATE, PROB_ITERATE and UNROLL can be used to tell the TI compiler how to unwrap software loops. The DATA_ALIGN pragma tells the compiler to align data arrays on specific memory boundaries. The _amemX_const() intrinsic can then be used in functions to tell the compiler how data is aligned so that the appropriate load and store operations can be performed.Compiler keywords such as const, interrupt, restrict and volatile are also important for getting highly optimized DSP software:• The const keyword should be added to scalars and arrays to denote constant data values.• The interrupt keyword should be added to interrupt service routines (ISRs) to make them maskable interrupt functionsand to ensure proper context switching.• The restrict keyword is added to function pointer arguments to denote that only this pointer will access the particularmemory in question.• The volatile keyword is added to pointers to denote that the data value in the corresponding memory address location istemporary and that another process can change the value.This keyword is particularly useful when reading a register todetermine if a process has completed.For a complete list of programming guidelines for TI DSPs, see the relevant programmer’s guide [5,6,7].5. SOFTWARE OPTIMIZATIONThe previous section discussed many programming guidelines for developing DSP software using intrinsics. However, the problemis how you determine when the software is fully optimized. Unfortunately, there is usually no clear cut answer. For a particular mapping, the DSP software engineer can determine the limiting operation for a particular algorithm and determine how close the compiled software is to an ideal number. For example, many algorithms are multiply intensive. Once the total number of multiplies required for an algorithm is divided by the number of multiplies that the target process can perform per cycle, the ideal limit can be computed. The engineer must then decide if the overhead for the particular function (ratio of actual cycles to the ideal cycles) is acceptable. If not, then further optimization is necessary. This additional optimization may include a new mapping of the algorithm which will require a new ideal limit.605Table 1. Optimization ResultsFor target processors that process multiple instructions in parallel, the DSP software engineer can also evaluate the resulting assembly code to determine of all of the units are being utilized during each clock cycle of the function. If not, then additional optimization may be required. Loop unrolling can often help in this area. The pragmas described in the previous section can help the compiler perform this operation automatically.To demonstrate the effectiveness of the TI compiler to handle C/C++ software written with intrinsics, Table 1 shows TMS320C64x cycle and code size comparisons between intrinsics software and assembly code for several algorithms related to communications systems. For most of the algorithms, the cycle counts for the intrinsics software are within 10% of the cycle counts for the assembly code. What is not shown here is the development time required for each algorithm, where assembly programming can take from 4 to 5 times longer than the intrinsics approach.6. LIMITATIONSWhile the design flow discussed in the previous sections has many benefits, it is not without limitation. Currently, the DSP software engineer must perform the algorithm mapping from floating-point to fixed-point manually. Furthermore, the resulting DSP software architecture is limited to the creativity of the engineer. To reduce the amount of time required to generate fixed-point DSP software from floating-point Matlab code, the mapping process could be automated. The same programming guidelines presented in this paper can be incorporated into an automated software generation tool to reduce the amount of time required to produce compiler friendly and cycle efficient DSP software. By analyzing data types (i.e. real, complex) and data value ranges in Matlab, the tool could easily map the data path and mathematical operations to the appropriate intrinsic functions. Once the DSP software has been generated, the floating-point versus fixed-point performance can be evaluated in Matlab. Once an acceptable level of performance has been achieved, the same DSP software can be ported to the embedded processor in the system.7. CONCLUSIONSThis paper has presented a design flow for the development, verification and simulation of DSP software within Matlab. The combination of C/C++ software with intrinsic function calls and a DSP simulator allow the DSP software engineer to evaluate the performance of a fixed-point implementation of an algorithm without hardware. This flexibility permits the engineer to evaluate many algorithm mappings more efficiently as well as to evaluate the mapping of an algorithm to different target processors.The importance of a single design environment for development, verification and simulation should not be underestimated. The time savings for software development, the number of engineers required to support the floating-point and fixed-point development, the ability for more thorough testing and the ability to compare floating-point vs. fixed-point performance are some of the tangible benefits. Furthermore, the need to only maintain one version of DSP software can greatly minimize code maintenance issues in production software systems.8. REFERENCES[1] Magee, David P., “Intrinsic Modeling within Matlab toAccelerate DSP Software Development”, Texas Instruments Developer’s Conference, Houston, TX, August 2002.[2] Magee, David P., “Programming the C6x Family of DSPs: AC Intrinsics Tutorial”, Texas Instruments Developer’sConference, Houston, TX, February 2005.[3] Catalytic, Inc. Web Page, http:// /,April 2005.[4] Matlab External Interfaces Reference, Version 6, July 2002.[5] TMS320C28x Optimizing C/C++ Compiler User’s Guide,SPRU514, August 2001.[6] TMS320C2x/C2xx/C5x Optimizing C Compiler User’sGuide, SPRU025e, August 1999.[7] TMS320C6000 Programmer’s Guide, SPRU198D, March2004.606。