第5讲-Matlab程序设计.ppt_第1页
第5讲-Matlab程序设计.ppt_第2页
第5讲-Matlab程序设计.ppt_第3页
第5讲-Matlab程序设计.ppt_第4页
第5讲-Matlab程序设计.ppt_第5页
已阅读5页,还剩76页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、第五讲 Matlab程序设计,课程提纲,引子 M文件介绍 控制语句 函数变量及变量作用域 程序设计的辅助函数 程序设计的优化 程序调试 信息接口 小结,page2,引子华氏温度和摄氏温度的转换,Problem: 设计一个MATLAB 程序,读取一个华氏温度的输入,输出摄氏温度。,Solution:,Step 1: 清晰地陈述出你要解决的问题; “将华氏温度转换为摄氏温度并输出”,Step 2: 确定程序的输入变量和输出变量; “输入变量:华氏温度;输出变量:摄氏温度”,Step 3: 设计程序伪代码; % 读取华氏温度:input T(F) % 温度转换: % 输出摄氏温度:print T(C

2、),page3,Step 4: 将伪代码转换为Matlab程序语句,% Script file:temp_conversion.m % % Purpose: % To convert an input temperature from degrees Fahrenheit to % an output temperature in Celsius. % % Record of revisions: % Date Programmer Description of change % = = = % 21/10/13 Y.Y.Guo Original code % % Define variabl

3、es: % temp_f -Temperature in degrees Fahrenheit % temp_k -Temperature in Celsius % Prompt the user for the input temperature. temp_f=input(Enter the temperature in degrees Fahrenheit:); % Convert to Celsius. temp_k=(5/9)*(temp_f-32); % Write out the result. fprintf(%6.2f degrees Fahrenheit = %6.2f C

4、elsius.n,temp_f,temp_k);,“程序信息”,“名字”,“用途”,“修改记录”,“变量定义”,“读取华氏温度”,“温度转换”,“输出摄氏温度”,page4,Step 5: 调试程序, run(C:Program FilesMATLABR2010abintemp_conversion.m) Enter the temperature in degrees Fahrenheit:120 120.00 degrees Fahrenheit = 48.89 Celsius. Enter the temperature in degrees Fahrenheit:100 100.00

5、degrees Fahrenheit = 37.78 Celsius.,Matlab初学者总是期望,拿到问题就能写出漂亮的代码与完美无误的程序,而实际上这是不可能的!,Matlab程序设计中,写代码只是简单的一半,另一半则是问题的分析与伪代码的设计!,Matlab的变量、语句与语法只是血肉般的简单存在,在任何一种语言中都能找到,而一个良好的编程习惯则是灵魂般的永恒存在!,page5,M文件介绍,Matlab是一种高级计算机语言,因而也能够编制一种以.m为扩展名的文本文件,简称M文件。,Matlab是一种解释性语言,命令在运行时被翻译为机器语言被执行,M文件就是命令的集合。,M文件是纯文本(AS

6、CII码)文件,因而便于进行编写和修改。扩展名必须为.m。,M文件分类:,命令式(Script):命令行的简单叠加 函数式(Function):参数传递和函数调用,page6,M文件建立与编辑,M文件建立:,Matlab窗口中菜单项File-Open 单击图标 ,打开一个M文件 找到M文件,直接双击打开,M文件编辑:,Matlab窗口中菜单项File-New-Script/Function 单击图标 ,新建一个M文件,page7,命令式文件(Script),命令式文件的运行相当于在命令窗口(Command Window)中逐行输入并运行命令。需注意一下几点: 标点符号的运用要恰当好处,每行命令

7、结束时用分号隔开,以免程序运行时数据输出造成不便; 建立良好的书写风格,保持程序的可读性,比如程序的层次感,注释行的书写; 注释行以符号%开头,在程序运行中不被执行,只起解释说明作用; 不需要用end语句作为命令式文件的结束标志; 运行此文件时,将其目录设置为当前目录。,page8,实例1:建立一命令式M文件绘制Matlab的LOGO图,% Script file: logotu.m % % Purpose: % This file is to create the Logo of % Matlab software load logo surf(L,R), colormap(M) n=siz

8、e(L,1) axis off axis(1 n 1 n -.2 .8) view(-37.5,30) title(Life is too short to spend writing DO loops.),page9,函数式文件(Function),函数式文件可以实现计算中的参数传递。函数式的标志是第1行为function语句。,函数式可以有返回值,也可有无返回值; 函数式文件名与函数名应一一对应; 函数式中的变量仅在函数内部起作用,为局部变量; 养成良好的注释习惯,方便自己,方便他人。,function outarg1, outarg2, . = fname(inarg1, inarg2,

9、 .) % H1 comment line % Other comment lines . (Executable code) . (return),help命令运行后将显示M文件注释语句中的第一个连续块,被空行隔离的其它注释语句,将被忽略; lookfor显示第一个注释行内容,为了便于被搜索,第一行注释尽可能包含特征信息。,page10,实例2:建立求一个向量元素平均值的函数,function y=average(x) % AVERAGE 求向量元素的平均值 % 语法 %y=average(x) % 其中,x是向量,y为计算得到向量元素的均值 % 若输入参数为非向量时则出错 % 代码行 m,

10、n=size(x); % 判断输入参数是否为向量 if(m=1)|(n=1)|(m=1, x=1:10; y=average(x) y = 5.5000 x=2 4 6 8 10; y=average(x) y = 6,page11,控制语句,顺序语句 选择语句 分支语句 循环语句 人机交互语句,page12,顺序语句,Matlab程序的命令语句按固定的顺序一个接一个的执行,这样的程序称为顺序语句。,% Script file: logotu.m % % Purpose: % This file is to create the Logo of % Matlab software load l

11、ogo surf(L,R), colormap(M) n=size(L,1) axis off axis(1 n 1 n -.2 .8) view(-37.5,30) title(Life is too short to spend writing DO loops.),顺序语句只能实现简单的功能,而在解决实际问题时往往会面临选择执行特定命令及重复性执行特定命令的情形,因而需要学习选择语句及循环语句。,page13,选择语句,选择语句可以使MATLAB 选择性执行指定区域内的代码(称之为语句块blocks),而跳过其他区域的代码。,if control_expr_1 Statements (b

12、lock 1) elseif control_expr_2 Statements (block 2) elseif control_expr_3 Statements (block 3) else Statements (block 4) end,判断表达式control_expr紧跟在if或elseif后面; 若判断表达式的结果为1,则执行其后的命令语句块(block),若结果为0,则跳过其后的命令语句块; 某一命令语句块被执行后,程序跳至end语句后一可执行语句; elseif语句可有任意个,else语句最多只有一个。,page14,实例3:输入三角形三边长,求面积, % Script f

13、ile: triarea.m % This program is to calculate the area of a triangular A=input(请输入三角形的三条边(数组形式):); if A(1)+A(2)A(3) else disp(不能构成一个三角形。) end, run(C:Program FilesMATLABR2010abintriarea.m) 请输入三角形的三条边(数组形式):3 4 5 6 run(C:Program FilesMATLABR2010abintriarea.m) 请输入三角形的三条边(数组形式):1 2 3 不能构成一个三角形。,三角形面积海伦公

14、式:,其中:,page15,实例4:求一元二次方程的根,Step 1: 清晰地陈述出你要解决的问题; “求一个一元二次方程的根”,Step 2: 确定程序的输入变量和输出变量; “输入变量:方程系数a, b, c;输出变量:两根x1, x2”,Step 3: 设计程序伪代码;,% 输入方程系数 input a, b, c % 求根过程: % 求根公式,伪代码整体框架: 输入方程系数; 求根过程; 输出求根结果。,page16,Step 3: 设计程序伪代码-续,% if % % else if % else (对应 ) % end % 输出结果 print x1, x2,Tips: 伪代码的设

15、计由上而下,先分析总体框架,再局部细化; 伪代码不是真实的Matlab代码,其书写类似于数学表达式; 伪代码只需在草稿纸上书写,力求简洁、整齐、清晰。,page17,Step 4: 将伪代码转换为Matlab程序语句,% Script file: calc_roots.m % % Purpose: % This program solves for the roots of a quadratic equation % of the form a*x2 + b*x + c = 0. It calculates the answers % regardless of the type of ro

16、ots that the equation possesses. % % Record of revisions: % Date Programmer Description of change % = = = % 21/10/13 Y.Y.Guo Original code % % Define variables: % a -Coefficient of x2 term of equation % b -Coefficient of x term of equation % c -Constant term of equation % discriminant -Discriminant

17、of the equation % imag_part -Imag part of equation (for complex roots) % real_part -Real part of equation (for complex roots) % x1 -First solution of equation (for real roots) % x2 -Second solution of equation (for real roots),“名字”,“用途”,“修改记录”,“变量定义”,“程序信息”,Tips: 一般而言,变量的定义可以在后续程序编写过程中进行,每出现一个新的变量时,

18、则在程序段前面进行定义; 若为物理变量,则最好将其单位列出。,page18,Step 4: 将伪代码转换为Matlab程序语句-续,% Prompt the user for the coefficients of the equation disp (This program solves for the roots of a quadratic ); disp (equation of the form A*X2 + B*X + C = 0.); a = input(Enter the coefficient A: ); b = input(Enter the coefficient B:

19、 ); c = input(Enter the coefficient C: ); % Calculate discriminant discriminant = b2 - 4 * a * c; % Solve for the roots, depending on the value of the discriminant. if discriminant 0 % there are two real roots, so . x1 = (-b + sqrt(discriminant) / (2*a); x2 = (-b - sqrt(discriminant) / (2*a); disp(T

20、his equation has two real roots:); fprintf(x1 = %fn, x1); fprintf(x2 = %fn, x2); elseif discriminant = 0 % there is one repeated root, so . x1 = ( -b ) / (2*a); disp(This equation has two identical real roots:); fprintf(x1 = x2 = %fn, x1);,“输入方程系数”,“计算方程判别式”,“方程有两不等 实根的情况”,“方程有两相等 实根的情况”,page19,Step

21、 4: 将伪代码转换为Matlab程序语句-续,else % there are complex roots, so . real_part = (-b) / (2*a); imag_part = sqrt( abs(discriminant) / (2*a); disp(This equation has complex roots:); fprintf(x1 = %f + i %f n,real_part, imag_part); fprintf(x1 + %f - i %f n, real_part, imag_part); end,“方程有两共轭复根的情况”,Step 5: 调试程序,

22、 run(C:Program FilesMATLABR2010abincalc_roots.m) This program solves for the roots of a quadratic equation of the form A*X2 + B*X + C = 0. Enter the coefficient A: 1 Enter the coefficient B: 4 Enter the coefficient C: 3 This equation has two real roots: x1 = -1.000000 x2 = -3.000000,page20,Step 5: 调

23、试程序-续, run(C:Program FilesMATLABR2010abincalc_roots.m) This program solves for the roots of a quadratic equation of the form A*X2 + B*X + C = 0. Enter the coefficient A: 1 Enter the coefficient B: 2 Enter the coefficient C: 1 This equation has two identical real roots: x1 = x2 = -1.000000, run(C:Pro

24、gram FilesMATLABR2010abincalc_roots.m) This program solves for the roots of a quadratic equation of the form A*X2 + B*X + C = 0. Enter the coefficient A: 1 Enter the coefficient B: 1 Enter the coefficient C: 1 This equation has complex roots: x1 = -0.500000 + i 0.866025 x1 = -0.500000 - i 0.866025,p

25、age21,分支语句,switch (switch_expr) case case_expr_1, Statements (block 1) case case_expr_2, Statements (block 2) otherwise, Statements (block 3) end,分支语句是一种特殊的选择语句,可以实现多种情况下的开关控制。,switch_expr 可以是数字、字符串或者逻辑变量; 当case_expr表达式与switch_expr相符时,其后的命令语句块(block)将被执行,不符时,其后的命令语句块将被跳过; 当某一命令语句块被执行后,程序跳至end语句后一可执行

26、语句。,page22,实例5:分支语句的简单应用,num=input(请输入一个数:); switch num case -1 disp(I am a teacher.); case 0 disp(I am a student.); case 1 disp(You are a teacher.); otherwise disp(You are a student.); end,page23,循环语句,实际问题中,需要反复执行某些语句,这时就需要用到循环语句。,在循环语句中,一组被重复执行的语句称为循环体,每循环一次,都必须做出判断,是继续循环执行还是终止执行跳出循环,这个判断的依据称为循环的终

27、止条件。,循环语句分类:,for循环:循环前循环次数已知; while循环:循环前循环次数未知。,page24,循环语句之“for循环”,for循环以指定的数目重复地执行特定的语句块。,for index=expr1:expr2:expr3 statement 1 statement n end,expr1为循环变量index的初始值,expr2为index的步长,expr3为index的终值; 当步长expr2=1时,可以省略不写。,Example 1: for i=1:2:9 end,Example 2: for i=1:9 end,page25,实例6:已知向量t=-1 0 13 5,生

28、成其Vandermonde矩阵, t=-1 0 1 3 5; n=max(size(t); for j=1:n for i=1:n a(i,j)=t(i)(n-j); end end a a = 1 -1 1 -1 1 0 0 0 0 1 1 1 1 1 1 81 27 9 3 1 625 125 25 5 1, a(:,n)=ones(n,1); for j=n-1:-1:1 a(:,j)=t.*a(:,j+1); end a a = 1 -1 1 -1 1 0 0 0 0 1 1 1 1 1 1 81 27 9 3 1 625 125 25 5 1,另一种方案,page26,实例7:计算给

29、定日期是一年中的第几天,Step 1: 清晰地陈述出你要解决的问题; “计算给定的一天是这一年中的第几天”,Step 2: 确定程序的输入变量和输出变量; “输入变量:年year, 月month, 日day; 输出变量:一年中的第几天day_of_year”,Step 3: 设计程序伪代码;,伪代码整体框架: 输入年、月、日; 计算第几天: 先加上当月的天数; 加上这一年往月的天数,若包括二月,则需考虑是否为闰年; 输出计算结果。,% 输入年、月、日 input year, month, day % 计算第几天 % 首先判断年份是否为闰年 if year/400余0 是闰年 leap_day=

30、1 else if year/100余0 不是闰年 leap_day=0,page27,Step 3: 设计程序伪代码-续,elseif year/4余0 是闰年 leap_day=1 else 不是闰年 leap_day=0 %四年一闰;百年不闰,四百年再闰 end % 开始计算第几天 % 首先加上当月的天数 day_of_year=day % 加上这一年往月的天数 for i=1:month-1 switch (i) case 1, 3, 5, 7, 8,10 day_of_year=day_of_year+31 case 4, 6, 9, 11 day_of_year=day_of_ye

31、ar+30 case 2 day_of_year=day_of_year+28+leap_day end end % 输出结果 print day_of_year,page28,Step 4: 将伪代码转换为Matlab程序语句,% Script file: dayofyear.m % % Purpose: % This program calculates the day of year corresponding % to a specified date. It illustrates the use switch % and for constructs. % % Record of

32、revisions: % Date Programmer Description of change % = = = % 21/10/13 Y.Y.Guo Original code % % Define variables: % day -Day (dd) % day_of_year -Day of year % i -Loop index % leap_day -Extra day for leap year % month -Month (mm) % year -Year(yyyy),“名字”,“用途”,“修改记录”,“变量定义”,“程序信息”,page29,Step 4: 将伪代码转换

33、为Matlab程序语句-续,% Get day, month, and year to convert disp(This program calculates the day of year given the ); disp(current date.); month = input(Enter current month (1-12):); day = input(Enter current day(1-31):); year = input(Enter current year(yyyy): ); % Check for leap year, and add extra day if

34、necessary if mod(year,400) = 0 leap_day = 1; % Years divisible by 400 are leap years elseif mod(year,100) = 0 leap_day = 0; % Other centuries are not leap years elseif mod(year,4) = 0 leap_day = 1; % Otherwise every 4th year is a leap year else leap_day = 0; % Other years are not leap years end,“输入年

35、、月、日”,“判断该年是否为闰年”,page30,% Calculate day of year by adding current day to the % days in previous months. day_of_year = day; for i = 1: month - 1 % Add days in months from January to last month switch (i) case 1,3,5,7,8,10, day_of_year = day_of_year + 31; case 4,6,9,11, day_of_year = day_of_year + 30

36、; case 2, day_of_year = day_of_year + 28 + leap_day; end end % Tell user fprintf(The date %2d/%2d/%4d is day of year %d.n,. month, day, year, day_of_year),Step 4: 将伪代码转换为Matlab程序语句-续,“首先加上当月天数”,“再加上往月天数”,“输出计算结果”,page31,Step 5: 调试程序, run(C:Program FilesMATLABR2010abindayofyear.m) This program calcul

37、ates the day of year given the current date. Enter current month (1-12):10 Enter current day(1-31):30 Enter current year(yyyy): 2013 The date 10/30/2013 is day of year 303. run(C:Program FilesMATLABR2010abindayofyear.m) This program calculates the day of year given the current date. Enter current mo

38、nth (1-12):10 Enter current day(1-31):30 Enter current year(yyyy): 1992 The date 10/30/1992 is day of year 304.,page32,循环语句之“while循环”,while循环是一个通过逻辑判断来确定重复次数的语句块。,while expression statement 1 statement n end,如果expression的值非零,程序将执行代码块,然后返回到while语句执行; 当expression的值为零时,这个重复过程结束,程序将跳至end后面的一可执行语句。,page3

39、3,实例8:计算Fibonacci数列第一个大于10000的元素,Fibonacci数列数组元素满足如下规则:,a=zeros(1,10000); a(1)=1; a(2)=2; i=2; while a(i)=10000 a(i+1)=a(i-1)+a(i); i=i+1; end i a(i), i i=20 ans =10946,page34,实例9:计算给定数据的平均值和标准差,Step 1: 清晰地陈述出你要解决的问题; “计算给定数据的平均值和标准差,且数据的数目未知,但非负”,Step 2: 确定程序的输入变量和输出变量; “输入变量:给定数据; 输出变量:这些数据的平均值和标准

40、差”,Step 3: 设计程序伪代码;,伪代码整体框架: 输入数据; 计算平均值和标准差; 输出计算结果。,% 输入数据 input % 计算平均值和标准差,N=N+1; sum_x=sum_x+x; sum_x2=sum_x2+x2,page35,Step 3: 设计程序伪代码-续,% 输出计算结果:print x_bar, std_dev,Step 4: 将伪代码转换为Matlab程序语句,% Script file: stats_1.m % % Purpose: % To calculate mean and the standard deviation of % an input da

41、ta set containing an arbitrary number % of input values. % % Record of revisions: % Date Programmer Description of change % = = = % 21/10/13 Y.Y. Guo Original code %,% Define variables: % n - The number of input samples % std_dev - The standard deviation of the input samples % sum_x - The sum of the

42、 input values % sum_x2 - The sum of the squares of the input values % x - An input data value % xbar - The average of the input samples,“名字”,“用途”,“修改记录”,“变量定义”,page36,Step 4: 将伪代码转换为Matlab程序语句-续,% Initialize sums. n = 0; sum_x = 0; sum_x2 = 0; % Read in first value x = input(Enter first value: ); %

43、While Loop to read input values. while x = 0 % Accumulate sums. n = n + 1; sum_x = sum_x + x; sum_x2 = sum_x2 + x2; % Read in next value x = input(Enter next value: ); end,% Calculate the mean and standard deviation x_bar = sum_x / n; std_dev = sqrt( (n * sum_x2 - sum_x2) / (n * (n-1) ); % Tell user

44、. fprintf(The mean of this data set is: %fn, x_bar); fprintf(The standard deviation is: %fn, std_dev); fprintf(The number of data points is: %dn, n);,“输入非负数据并计算平均值和标准差”,“输出计算结果”,page37,Step 5: 调试程序, run(C:Program FilesMATLABR2010abinstats_1.m) Enter first value: 1 Enter next value: 3 Enter next valu

45、e: 5 Enter next value: 9 Enter next value: -1 The mean of this data set is: 4.500000 The standard deviation is: 3.415650 The number of data points is: 4 run(C:Program FilesMATLABR2010abinstats_1.m) Enter first value: 100 Enter next value: 98 Enter next value: 97 Enter next value: 93 Enter next value

46、: 76 Enter next value: 80 Enter next value: -9 The mean of this data set is: 90.666667 The standard deviation is: 10.152175 The number of data points is: 6,Note: 当输入数据为负数时,计算终止。 在计算平均值和标准差时只考虑之前输入的非负数据。,page38,循环语句之“嵌套循环”,如果一个循环完全出现在另一个循环当中,则称这两个循环为带嵌套的循环。此外,也会出现多重嵌套的循环。,for i = 1:3 for j = 1:3 prod

47、uct = i * j; fprintf(%d * %d = %d n, i, j, product); end end,1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9,page39,人机交互语句,echo on 指令:显示其后所有执行文件的指令; echo off 指令:关闭其后所有执行文件的指令显示; input 指令:提示用户从键盘输入数值、字符串或表达式,并接受输入; pause 指令:使程序运行停止,等待用户按任意键继续; disp指令:在屏幕上显示字符

48、串; fprintf指令:在屏幕上按一定格式输出字符串。,page40,input命令,调用格式为:input(提示信息,选项), reply = input(Do you want more? Y/N Y: , s); Do you want more? Y/N Y: Y reply reply = Y reply = input(Please input your height: ) Please input your height: 177 reply = 177,Note: s表示允许用户输入一个字符串,如果省略不写,则表示数字变量。,人机交互语句,page41,pause命令,人机交

49、互语句,此命令有如下几种调用格式: pause: 程序暂停等待回应,直到用户按任意键继续运行; pause(n): 程序暂停n秒时间; pause on: 执行其后的pause命令; pause off: 不执行其后的pause命令。,pause 命令在程序的调试过程或者用户需要查看中间结果时十分有用。,page42,人机交互语句,disp命令,调用格式为:disp(输出项), A=I miss you very much!;disp(A) I miss you very much!,fprintf命令,调用格式为:fprintf(格式,输出项), a=9; fprintf(%dn,a) 9,

50、Note: 常见输出格式 %d -整型格式输出; %f -浮点型格式输出; %e -指数形式输出; n -换行。,Matlab的输出格式控制与C语言相同!,page43,函数变量及变量作用域,函数文件的内部变量是局部变量,与其他函数文件及MATLAB工作空间相互隔离。但是,如果在若干函数中,都把某一变量定义为全局变量,那么这些函数将公用这一个变量。 在MATLAB中,全局变量用命令global定义。全局变量的作用域是整个MATLAB工作空间,即全程有效。所有的函数都可以对它进行存取和修改。因此,定义全局变量是函数间传递信息的一种手段。,page44,实例10:全局变量使用简例,function

51、 f=wadd(x,y) % add two variable global ALPHA BETA f=cos(ALPHA)*x+sin(BETA)*y;,求x, y按照如下加权方式的和:, global ALPHA BETA ALPHA=pi/3;BETA=pi/4; wadd(5,6) ans = 6.7426,Tips: 使用全局变量时,函数内部以及命令窗口(或者命令式M文件)中均应该定义相应的全局变量; 定义多个全局变量时,用空格隔开,不能用逗号。,page45,MATLAB在函数调用上有一个与众不同之处:函数所传递参数数目的可调性。凭借这一点,一个函数可完成多种功能。 在调用函数时,

52、MATLAB用两个永久变量nargin和nargout分别记录调用该函数时的输入实参和输出实参的个数。只要在函数文件中包含这两个变量,就可以准确地知道该函数文件被调用时的输入输出参数个数,从而决定函数如何进行处理。,page46,函数变量及变量作用域-续,实例11:nargin变量使用简例,编制一个函数,函数名为test_nargin,它能实现如下功能:如果调用函数时只有一个输入变量,则求该变量的模(对矩阵而言则为行列式),如果有两个输入变量,则求两个变量的和。,function c=test_nargin(a,b) % This function is to test the nargin

53、% variable if nargin=1 c=det(a); elseif nargin=2 c=a+b; end, A=1,2,3;4:6;10 12 18; B=eye(3); test_nargin(A) ans = -12.0000 test_nargin(B) ans = 1 test_nargin(A, B) ans = 2 2 3 4 6 6 10 12 19,page47,程序设计的辅助函数,在Matlab语言的程序设计中,有几组辅助函数可用以支持M文件的编辑,对这些函数的合理使用可以增加函数的鲁棒性或丰富函数功能。辅助函数包括:,执行函数 容错函数 时间控制函数,page

54、48,执行函数,page49,Matlab中提供了一系列的执行函数。,容错函数,一个程序设计的好坏在很大程度上取决于其容错能力的大小。Matlab语言中提供了相应的报错及警告函数error, warning等。,函数error可以在窗口中显示错误的信息,以提示用户输入错误或者调用错误,其调用格式如下:,error(错误信息):如果调用M文件时触发error,则程序将中断运行,并显示错误信息。,函数warning的用法类似于函数error,但与其不同的是,函数warning不会中断程序的执行,而仅仅给出警告信息。,与容错相关的函数或命令还有: lasterr、lastwarn以及errortra

55、p on/off等。,page50,Matlab语言还提供了一个流程控制结构用于容错处理,即try-catch-end结构,其调用格式如下:,try block 1 catch block 2 end,容错函数,在执行该语句段时,将先执行block 1,如果block 1内出现错误,则将执行block 2,如果block 2也出现错误,则程序将报错并终止; 如果block 1内出现错误,block 2执行后,则可由容错函数lasterr获得错误详情。,page51,实例12:容错控制结构try-catch-end示例,function c=testtce(a,b) % This functio

56、n is to test the % try-catch-end structure try c=a+b; catch c=strcat(a,b); end, a=I miss a = I miss b= you very much! b = you very much! c=testtce(a,b) c = I miss you very much! lasterr ans = Error using = + Matrix dimensions must agree., a+b ? Error using = plus Matrix dimensions must agree.,page52

57、,时间控制函数,Matlab中提供了一些时间控制函数,可以用来监视程序运行的时间,如下表所示。,page53,例如: date ans = 22-Oct-2013,另外,Matlab还提供了一些计时函数,如下表所示。,page54,程序设计的优化,以矩阵作为操作主体,尽量避免对矩阵元素的操作; 尽量避免循环运算,尤其是多重循环; 数据的预定义:尤其在循环中使用数组变量时,可以预先估计变量可能出现的最大维数,进行预定义; 内存的管理:即使清理内容,clear。,page55,实例13:循环运算和向量运算时间对比,function y=test_opt1 for i=1:10000 y(i)=si

58、n(pi*i); end function y=test_opt2 x=1:10000*pi; y=sin(x);, tic;test_opt1;t1=toc t1 = 0.0658 tic;test_opt2;t1=toc t1 = 0.0172,计算y=sin(x),其中,page56,程序调试,使用pause函数; 在程序内设置断点; 调试出现错误时,学会查看Workspace,分析变量取值是否科学合理。,page57,page58,信息接口,文件接口 应用程序接口 独立程序,page59,文件接口,文件可分为两类: 文本文件 由字符和与字符的显示格式有关的控制符构成 常见扩展名:“TXT” 、“BAT”、“HTM” 二进制文件 二进制文件为非文本文件 常见扩展名:“COM”、“EXE” 、“BMP” 、“WAV”,Note:简单来说,文本文件是基于字符编码的文件,常见的编码有ASCII编码,其它则可认为是二进制文件。,page60,文件的打开与关闭,fopen函数 fidfopen(filename,permission) fid,message=fopen(filename,permssion) filename,permission,machineformat=fopen(fid) fid =fopen(all) fclose函数 status=fclose(fi

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论