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

下载本文档

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

文档简介

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

2、转换为摄氏温度并输出将华氏温度转换为摄氏温度并输出”Step 2: Step 2: 确定程序的输入变量和输出变量;确定程序的输入变量和输出变量; “输入变量输入变量:华氏温度;:华氏温度;输出变量输出变量:摄氏温度:摄氏温度”Step 3: Step 3: 设计程序伪代码;设计程序伪代码; % % 读取华氏温度:读取华氏温度:input input T T(F)(F) % % 温度转换:温度转换: % % 输出摄氏温度:输出摄氏温度:print print T T(C)(C)5(C)( (F)32)9TTpagepage3 3Step 4: Step 4: 将伪代码转换为将伪代码转换为Matl

3、abMatlab程序语句程序语句% Script file:temp_conversion.m% Script file:temp_conversion.m% % Purpose:% Purpose:% To convert an input temperature from degrees Fahrenheit to% To convert an input temperature from degrees Fahrenheit to% an output temperature in Celsius.% an output temperature in Celsius.% % Record

4、 of revisions:% Record of revisions:% Date Programmer Description of change% Date Programmer Description of change% = = =% = = =% 21/10/13 Y.Y.Guo Original code% 21/10/13 Y.Y.Guo Original code% % Define variables:% Define variables:% temp_f -Temperature in degrees Fahrenheit% temp_f -Temperature in

5、degrees Fahrenheit% temp_k -Temperature in Celsius% temp_k -Temperature in Celsius% Prompt the user for the input temperature.% Prompt the user for the input temperature.temp_f=input(Enter the temperature in degrees Fahrenheit:);temp_f=input(Enter the temperature in degrees Fahrenheit:);% Convert to

6、 Celsius.% Convert to Celsius.temp_k=(5/9)temp_k=(5/9)* *(temp_f-32);(temp_f-32);% Write out the result.% Write out the result.fprintf(%6.2f degrees Fahrenheit = %6.2f fprintf(%6.2f degrees Fahrenheit = %6.2f Celsius.n,temp_f,temp_k);Celsius.n,temp_f,temp_k);“程序信息程序信息”“名字名字”“用途用途”“修改记录修改记录”“变量定义变量定义

7、”“读取华氏温度读取华氏温度”“温度转换温度转换”“输出摄氏温度输出摄氏温度”pagepage4 4Step 5: Step 5: 调试程序调试程序 run(C:Program FilesMATLABR2010abintemp_conversion.m) run(C:Program FilesMATLABR2010abintemp_conversion.m)Enter the temperature in degrees Fahrenheit:120Enter the temperature in degrees Fahrenheit:120120.00 degrees Fahrenheit

8、= 48.89 Celsius.120.00 degrees Fahrenheit = 48.89 Celsius.Enter the temperature in degrees Fahrenheit:100Enter the temperature in degrees Fahrenheit:100100.00 degrees Fahrenheit = 37.78 Celsius.100.00 degrees Fahrenheit = 37.78 Celsius.MatlabMatlab初学者总是期望,拿到问题就能写出漂亮的代码与完初学者总是期望,拿到问题就能写出漂亮的代码与完美无误的程序

9、,而实际上这是不可能的!美无误的程序,而实际上这是不可能的!MatlabMatlab程序设计中,写代码只是简单的一半,另一半则是程序设计中,写代码只是简单的一半,另一半则是问题的分析与伪代码的设计!问题的分析与伪代码的设计!MatlabMatlab的变量、语句与语法只是的变量、语句与语法只是血肉血肉般的简单存在,在任何般的简单存在,在任何一种语言中都能找到,而一个良好的编程习惯则是一种语言中都能找到,而一个良好的编程习惯则是灵魂灵魂般的般的永恒存在!永恒存在!pagepage5 5M M文件介绍MatlabMatlab是一种高级计算机语言,因而也能够编制一种以是一种高级计算机语言,因而也能够编

10、制一种以.m.m为为扩展名的文本文件,简称扩展名的文本文件,简称M M文件文件。MatlabMatlab是一种解释性语言,命令在运行时被翻译为机器语言是一种解释性语言,命令在运行时被翻译为机器语言被执行,被执行,M M文件就是文件就是命令的集合命令的集合。M M文件是纯文本(文件是纯文本(ASCIIASCII码)文件,因而便于进行编写和修改。码)文件,因而便于进行编写和修改。扩展名必须为扩展名必须为.m.m。M M文件分类:文件分类:p 命令式(命令式(ScriptScript):命令行的简单叠加):命令行的简单叠加p 函数式(函数式(FunctionFunction):参数传递和函数调用):

11、参数传递和函数调用pagepage6 6M M文件建立与编辑M M文件建立:文件建立:p Matlab Matlab窗口中菜单项窗口中菜单项FileFile-OpenOpenp 单击图标单击图标 ,打开一个,打开一个M M文件文件p 找到找到M M文件,直接双击打开文件,直接双击打开M M文件编辑:文件编辑:p Matlab Matlab窗口中菜单项窗口中菜单项FileFile-NewNew-ScriptScript/ /FunctionFunctionp 单击图标单击图标 ,新建一个,新建一个M M文件文件pagepage7 7命令式文件(ScriptScript)命令式文件的运行相当于在命

12、令窗口(命令式文件的运行相当于在命令窗口(Command WindowCommand Window)中逐行输入并运行命令。需注意一下几点:中逐行输入并运行命令。需注意一下几点: 标点符号的运用要恰当好处,每行命令结束时用分号隔标点符号的运用要恰当好处,每行命令结束时用分号隔开,以免程序运行时数据输出造成不便;开,以免程序运行时数据输出造成不便; 建立良好的书写风格,保持程序的可读性,比如程序的建立良好的书写风格,保持程序的可读性,比如程序的层次感,注释行的书写;层次感,注释行的书写; 注释行以符号注释行以符号% %开头,在程序运行中不被执行,只起解开头,在程序运行中不被执行,只起解释说明作用;

13、释说明作用; 不需要用不需要用endend语句作为命令式文件的结束标志;语句作为命令式文件的结束标志; 运行此文件时,将其目录设置为当前目录。运行此文件时,将其目录设置为当前目录。pagepage8 8实例实例1 1:建立一命令式:建立一命令式M M文件绘制文件绘制MatlabMatlab的的LOGOLOGO图图Life is too short to spend writing DO loops.% Script file: logotu.m% Script file: logotu.m% % Purpose:% Purpose:% This file is to create the %

14、This file is to create the Logo of Logo of % Matlab software% Matlab softwareload logoload logosurf(L,R), colormap(M)surf(L,R), colormap(M)n=size(L,1)n=size(L,1)axis offaxis offaxis(1 n 1 n -.2 .8)axis(1 n 1 n -.2 .8)view(-37.5,30)view(-37.5,30)title(Life is too short to title(Life is too short to s

15、pend writing DO loops.)spend writing DO loops.)pagepage9 9函数式文件(FunctionFunction)函数式文件可以实现计算中的参数传递。函数式的标志是第函数式文件可以实现计算中的参数传递。函数式的标志是第1 1行为行为functionfunction语句。语句。 函数式可以有返回值,函数式可以有返回值,也可有无返回值;也可有无返回值; 函数式文件名与函数函数式文件名与函数名应名应一一对应一一对应; 函数式中的变量仅在函数式中的变量仅在函数内部起作用,为局部函数内部起作用,为局部变量;变量; 养成良好的注释习惯,养成良好的注释习惯,方

16、便自己,方便他人。方便自己,方便他人。functionfunction outarg1, outarg1, outarg2, . = outarg2, . = fnamefname(inarg1, inarg2, .)(inarg1, inarg2, .)% H1 comment line% H1 comment line% Other comment lines% Other comment lines.( (Executable codeExecutable code) ).(return)(return)helphelp命令运行后将显示命令运行后将显示M M文件注释语句中的第一个连续块,

17、文件注释语句中的第一个连续块,被空行隔离的其它注释语句,将被忽略;被空行隔离的其它注释语句,将被忽略;lookforlookfor显示第一个注释行内容,为了便于被搜索,第一显示第一个注释行内容,为了便于被搜索,第一行注释尽可能包含特征信息。行注释尽可能包含特征信息。pagepage1010实例实例2 2:建立求一个向量元素平均值的函数:建立求一个向量元素平均值的函数function y=average(x)function y=average(x)% AVERAGE % AVERAGE 求向量元素的平均值求向量元素的平均值% % 语法语法%y=average(x)%y=average(x)%

18、% 其中,其中,x x是向量,是向量,y y为计算得到向量元为计算得到向量元素的均值素的均值% % 若输入参数为非向量时则出错若输入参数为非向量时则出错% % 代码行代码行m,n=size(x);m,n=size(x);% % 判断输入参数是否为向量判断输入参数是否为向量if(m=1)|(n=1)|(m=1& n=1)if(m=1)|(n=1)|(m=1& n=1) % % 若输入参数不是向量,则出错若输入参数不是向量,则出错 error(Input must be a vector!)error(Input must be a vector!)endend% % 计算向量元素的平均值计算向量

19、元素的平均值y=sum(x)/length(x);y=sum(x)/length(x); x=1:10; x=1:10; y=average(x) y=average(x)y =y = 5.5000 5.5000 x=2 4 6 8 10; x=2 4 6 8 10; y=average(x) y=average(x)y =y = 6 6pagepage1111控制语句p 顺序语句顺序语句p 选择语句选择语句p 分支语句分支语句p 循环语句循环语句p 人机交互语句人机交互语句pagepage1212顺序语句MatlabMatlab程序的命令语句按固定的顺序一个接一个的执行,这程序的命令语句按固

20、定的顺序一个接一个的执行,这样的程序称为样的程序称为顺序语句顺序语句。% Script file: % Script file: logotu.mlogotu.m% % Purpose:% Purpose:% This file is to create the % This file is to create the Logo of Logo of % Matlab software% Matlab softwareload logoload logosurf(L,R), surf(L,R), colormapcolormap(M)(M)n=size(L,1)n=size(L,1)axis

21、offaxis offaxis(1 n 1 n -.2 .8)axis(1 n 1 n -.2 .8)view(-37.5,30)view(-37.5,30)title(Life is too short to title(Life is too short to spend writing DO loops.)spend writing DO loops.)顺序语句只能实现简单的功顺序语句只能实现简单的功能,而在解决实际问题时往能,而在解决实际问题时往往会面临往会面临选择执行特定命令选择执行特定命令及及重复性执行特定命令重复性执行特定命令的情的情形,因而需要学习选择语句形,因而需要学习选择语

22、句及循环语句。及循环语句。pagepage1313选择语句选择语句可以使选择语句可以使MATLAB MATLAB 选择性执行指定区域内的代码选择性执行指定区域内的代码( (称之为语句块称之为语句块blocks)blocks),而跳过其他区域的代码。,而跳过其他区域的代码。ifif control_expr_1control_expr_1Statements (Statements (block block 1 1) )elseifelseif control_expr_2control_expr_2Statements (Statements (block block 2 2) )elseif

23、elseif control_expr_3control_expr_3Statements (Statements (block block 3 3) )elseelseStatements (Statements (block block 4 4) )endend 判断表达式判断表达式control_exprcontrol_expr紧跟在紧跟在ifif或或elseifelseif后面;后面; 若判断表达式的结果为若判断表达式的结果为1 1,则执行其后的命令语句块则执行其后的命令语句块(blockblock),若结果为),若结果为0 0,则,则跳过其后的命令语句块;跳过其后的命令语句块; 某一

24、命令语句块被执行后,某一命令语句块被执行后,程序跳至程序跳至endend语句后一可执语句后一可执行语句;行语句; elseifelseif语句可有任意个,语句可有任意个,elseelse语句最多只有一个。语句最多只有一个。pagepage1414实例实例3 3:输入三角形三边长,求面积:输入三角形三边长,求面积 % Script file: triarea.m % Script file: triarea.m% This program is to calculate the area % This program is to calculate the area of a triangula

25、rof a triangularA=input(A=input(请输入三角形的三条边请输入三角形的三条边( (数组形式数组形式) ):);); if A(1)+A(2)A(3) & A(1)+A(3)A(2) & if A(1)+A(2)A(3) & A(1)+A(3)A(2) & A(2)+A(3)A(1)A(2)+A(3)A(1) p=(A(1)+A(2)+A(3)/2; p=(A(1)+A(2)+A(3)/2; s=sqrt(p s=sqrt(p* *(p-A(1)(p-A(1)* *(p-A(2)(p-A(2)* *(p-(p-A(3);A(3); disp(s); disp(s);

26、else else disp( disp(不能构成一个三角形。不能构成一个三角形。) end end run(C:Program run(C:Program FilesMATLABR2010abintriarea.FilesMATLABR2010abintriarea.m)m)请输入三角形的三条边请输入三角形的三条边( (数组形式数组形式) ):3 4 53 4 5 6 6 run(C:Program run(C:Program FilesMATLABR2010abintriarea.FilesMATLABR2010abintriarea.m)m)请输入三角形的三条边请输入三角形的三条边( (

27、数组形式数组形式) ):1 2 31 2 3不能构成一个三角形。不能构成一个三角形。()()()Sp papbpc三角形面积三角形面积海伦公式海伦公式:1()2pabc其中:其中:pagepage1515实例实例4 4:求一元二次方程的根:求一元二次方程的根20(0)axbxcaStep 1: Step 1: 清晰地陈述出你要解决的问题;清晰地陈述出你要解决的问题; “求一个一元二次方程的根求一个一元二次方程的根”Step 2: Step 2: 确定程序的输入变量和输出变量;确定程序的输入变量和输出变量; “输入变量输入变量:方程系数:方程系数a a, , b b, , c c;输出变量输出变

28、量:两根:两根x x1 1, , x x2 2”Step 3: Step 3: 设计程序伪代码;设计程序伪代码;% % 输入方程系数输入方程系数 input input a a, , b b, , c c% % 求根过程求根过程:% % 求根公式求根公式242bbacxa 伪代码整体框架:伪代码整体框架: 输入方程系数;输入方程系数; 求根过程;求根过程; 输出求根结果。输出求根结果。pagepage1616Step 3: Step 3: 设计程序伪代码设计程序伪代码- -续续% % ifif% % % else ifelse if% % elseelse ( (对对应应 ) )% % end

29、 end% % 输出结果输出结果 print print x x1 1, , x x2 2240bac21224242bbacxabbacxa 240bac122bxxa 240bac2122422422bacbxiaabacbxiaa TipsTips: 伪代码的设计伪代码的设计由上由上而下而下,先分析总体框架,先分析总体框架,再局部细化;再局部细化; 伪代码不是真实的伪代码不是真实的MatlabMatlab代码,其书写类代码,其书写类似于数学表达式;似于数学表达式; 伪代码只需在草稿伪代码只需在草稿纸上书写,力求简洁、纸上书写,力求简洁、整齐、清晰。整齐、清晰。pagepage1717St

30、ep 4: Step 4: 将伪代码转换为将伪代码转换为MatlabMatlab程序语句程序语句% % Script fileScript file: calc_roots.m: calc_roots.m% % % PurposePurpose: :% This program solves for the roots of a quadratic equation% This program solves for the roots of a quadratic equation% of the form a% of the form a* *x2 + bx2 + b* *x + c = 0

31、. It calculates the answersx + c = 0. It calculates the answers% regardless of the type of roots that the equation possesses.% regardless of the type of roots that the equation possesses.% % % Record of revisionsRecord of revisions: :% Date Programmer Description of change% Date Programmer Descripti

32、on of change% = = =% = = =% 21/10/13 Y.Y.Guo Original code% 21/10/13 Y.Y.Guo Original code% % % Define variablesDefine variables: :% a -Coefficient of x2 term of equation% a -Coefficient of x2 term of equation% b -Coefficient of x term of equation% b -Coefficient of x term of equation% c -Constant t

33、erm of equation% c -Constant term of equation% discriminant -Discriminant of the equation% discriminant -Discriminant of the equation% imag_part -Imag part of equation (for complex roots)% imag_part -Imag part of equation (for complex roots)% real_part -Real part of equation (for complex roots)% rea

34、l_part -Real part of equation (for complex roots)% x1 -First solution of equation (for real roots)% x1 -First solution of equation (for real roots)% x2 -Second solution of equation (for real roots)% x2 -Second solution of equation (for real roots)“名字名字”“用途用途”“修改记录修改记录”“变量定义变量定义”“程序信息程序信息”TipsTips: 一

35、般而言,变一般而言,变量的定义可以在量的定义可以在后续程序编写过后续程序编写过程中进行,每出程中进行,每出现一个新的变量现一个新的变量时,则在程序段时,则在程序段前面进行定义;前面进行定义; 若为物理变量,若为物理变量,则最好将其单位则最好将其单位列出。列出。pagepage1818Step 4: Step 4: 将伪代码转换为将伪代码转换为MatlabMatlab程序语句程序语句- -续续% Prompt the user for the coefficients of the equation% Prompt the user for the coefficients of the equ

36、ationdisp (This program solves for the roots of a quadratic );disp (This program solves for the roots of a quadratic );disp (equation of the form Adisp (equation of the form A* *X2 + BX2 + B* *X + C = 0.);X + C = 0.);a = input(Enter the coefficient A: );a = input(Enter the coefficient A: );b = input

37、(Enter the coefficient B: );b = input(Enter the coefficient B: );c = input(Enter the coefficient C: );c = input(Enter the coefficient C: );% % Calculate discriminantCalculate discriminantdiscriminant = b2 - 4 discriminant = b2 - 4 * * a a * * c; c;% Solve for the roots, depending on the value of the

38、 % Solve for the roots, depending on the value of the discriminant.discriminant.ifif discriminant 0 discriminant 0 % there are two real roots, so .% there are two real roots, so .x1 = (-b + sqrt(discriminant) / (2x1 = (-b + sqrt(discriminant) / (2* *a);a);x2 = (-b - sqrt(discriminant) / (2x2 = (-b -

39、 sqrt(discriminant) / (2* *a);a);disp(This equation has two real roots:);disp(This equation has two real roots:);fprintf(x1 = %fn, x1);fprintf(x1 = %fn, x1);fprintf(x2 = %fn, x2);fprintf(x2 = %fn, x2);elseifelseif discriminant = 0 discriminant = 0 % there is one repeated root, so .% there is one rep

40、eated root, so .x1 = ( -b ) / (2x1 = ( -b ) / (2* *a);a);disp(This equation has two identical real roots:);disp(This equation has two identical real roots:);fprintf(x1 = x2 = %fn, x1);fprintf(x1 = x2 = %fn, x1);“输入方程系数输入方程系数”“计算方程判别式计算方程判别式”“方程有两不等方程有两不等 实根的情况实根的情况”“方程有两相等方程有两相等 实根的情况实根的情况”pagepage1

41、919Step 4: Step 4: 将伪代码转换为将伪代码转换为MatlabMatlab程序语句程序语句- -续续elseelse % there are complex roots, % there are complex roots, so .so .real_part = (-b) / (2real_part = (-b) / (2* *a);a);imag_part = sqrt( abs(discriminant) imag_part = sqrt( abs(discriminant) / (2/ (2* *a);a);disp(This equation has complex

42、disp(This equation has complex roots:);roots:);fprintf(x1 = %f + i %f fprintf(x1 = %f + i %f n,real_part, imag_part);n,real_part, imag_part);fprintf(x1 + %f - i %f n, fprintf(x1 + %f - i %f n, real_part, imag_part);real_part, imag_part);endend“方程有两共轭方程有两共轭复根的情况复根的情况”Step 5: Step 5: 调试程序调试程序 run(C:Pr

43、ogram run(C:Program FilesMATLABR2010abincalc_roots.m)FilesMATLABR2010abincalc_roots.m)This program solves for the roots of a quadratic This program solves for the roots of a quadratic equation of the form Aequation of the form A* *X2 + BX2 + B* *X + C = 0.X + C = 0.Enter the coefficient A: 1Enter th

44、e coefficient A: 1Enter the coefficient B: 4Enter the coefficient B: 4Enter the coefficient C: 3Enter the coefficient C: 3This equation has two real roots:This equation has two real roots:x1 = -1.000000 x2 = -3.000000 x1 = -1.000000 x2 = -3.000000212430(1,3)xxxx pagepage2020Step 5: Step 5: 调试程序调试程序-

45、 -续续 run(C:Program run(C:Program FilesMATLABR2010abincalc_roots.m)FilesMATLABR2010abincalc_roots.m)This program solves for the roots of a quadratic This program solves for the roots of a quadratic equation of the form Aequation of the form A* *X2 + BX2 + B* *X + C = 0.X + C = 0.Enter the coefficient

46、 A: 1Enter the coefficient A: 1Enter the coefficient B: 2Enter the coefficient B: 2Enter the coefficient C: 1Enter the coefficient C: 1This equation has two identical real roots:This equation has two identical real roots:x1 = x2 = -1.000000 x1 = x2 = -1.000000212210(1)xxxx run(C:Program run(C:Progra

47、m FilesMATLABR2010abincalc_roots.m)FilesMATLABR2010abincalc_roots.m)This program solves for the roots of a quadratic This program solves for the roots of a quadratic equation of the form Aequation of the form A* *X2 + BX2 + B* *X + C = 0.X + C = 0.Enter the coefficient A: 1Enter the coefficient A: 1

48、Enter the coefficient B: 1Enter the coefficient B: 1Enter the coefficient C: 1Enter the coefficient C: 1This equation has complex roots:This equation has complex roots:x1 = -0.500000 + i 0.866025 x1 = -0.500000 + i 0.866025 x1 = -0.500000 - i 0.866025x1 = -0.500000 - i 0.866025212101313(,)2222xxxixi

49、 pagepage2121分支语句switchswitch ( (switch_exprswitch_expr) )casecase case_expr_1, case_expr_1,Statements (Statements (block 1block 1) )casecase case_expr_2, case_expr_2,Statements (Statements (block 2block 2) )otherwiseotherwise, ,Statements (Statements (block 3block 3) )endend分支语句是一种特殊的选择语句,可以实现多种情况下

50、分支语句是一种特殊的选择语句,可以实现多种情况下的开关控制。的开关控制。 switch_exprswitch_expr 可以是数可以是数字、字符串或者逻辑变量;字、字符串或者逻辑变量; 当当case_exprcase_expr表达式与表达式与switch_exprswitch_expr相符时,其后相符时,其后的命令语句块的命令语句块(block)(block)将被将被执行,不符时,其后的命令执行,不符时,其后的命令语句块将被跳过;语句块将被跳过; 当某一命令语句块被执当某一命令语句块被执行后,程序跳至行后,程序跳至endend语句后语句后一可执行语句。一可执行语句。pagepage2222实例

51、实例5 5:分支语句的简单应用:分支语句的简单应用num=input(num=input(请输入一个数:请输入一个数:););switch numswitch numcase -1case -1disp(I am a teacher.);disp(I am a teacher.);case 0case 0disp(I am a student.);disp(I am a student.);case 1case 1disp(You are a teacher.);disp(You are a teacher.);otherwiseotherwisedisp(You are a student.

52、);disp(You are a student.);endendpagepage2323循环语句实际问题中,需要反复执行某些语句,这时就需要用到实际问题中,需要反复执行某些语句,这时就需要用到循环语句。循环语句。在循环语句中,一组被重复执行的语句称为在循环语句中,一组被重复执行的语句称为循环体循环体,每,每循环一次,都必须做出判断,是继续循环执行还是终止循环一次,都必须做出判断,是继续循环执行还是终止执行跳出循环,这个判断的依据称为执行跳出循环,这个判断的依据称为循环的终止条件循环的终止条件。循环语句分类:循环语句分类:p forfor循环:循环前循环次数已知;循环:循环前循环次数已知;p

53、whilewhile循环:循环前循环次数未知。循环:循环前循环次数未知。pagepage2424循环语句之“forfor循环”forfor循环以指定的数目重复地执行特定的语句块。循环以指定的数目重复地执行特定的语句块。for for index=index=exprexpr1:1:exprexpr2:2:expexpr r3 3 statement 1statement 1 statement statement n nendend exprexpr1 1为循环变量为循环变量indexindex的初始值,的初始值,exprexpr2 2为为indexindex的步长,的步长,exprexpr3

54、 3为为indexindex的终值;的终值; 当步长当步长exprexpr2=12=1时,时,可以省略不写。可以省略不写。Example 1Example 1:for for i=1:2:9i=1:2:9 endendExample 2Example 2:for for i=1:9i=1:9 endendpagepage2525实例实例6 6:已知向量:已知向量t=-1 0 13 5t=-1 0 13 5,生成其,生成其VandermondeVandermonde矩阵矩阵 t=-1 0 1 3 5; t=-1 0 1 3 5; n=max(size(t); n=max(size(t); for

55、for j=1:n j=1:nforfor i=1:n i=1:na(i,j)=t(i)(n-j);a(i,j)=t(i)(n-j);endendendend a aa =a = 1 -1 1 -1 1 -1 1 -1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 81 27 9 3 81 27 9 3 1 1 625 125 25 5 625 125 25 5 1 1 a(:,n)=ones(n,1); a(:,n)=ones(n,1); for for j=n-1:-1:1j=n-1:-1:1a(:,j)=t.a(:,j)=t.* *a(:,j+1

56、);a(:,j+1);endend a aa =a = 1 -1 1 -1 1 1 -1 1 -1 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 81 27 9 3 1 81 27 9 3 1 625 125 25 5 1 625 125 25 5 1另一种方案另一种方案pagepage2626实例实例7 7:计算给定日期是一年中的第几天:计算给定日期是一年中的第几天Step 1: Step 1: 清晰地陈述出你要解决的问题;清晰地陈述出你要解决的问题; “计算给定的一天是这一年中的第几天计算给定的一天是这一年中的第几天”Step 2: Step 2: 确

57、定程序的输入变量和输出变量;确定程序的输入变量和输出变量; “输入变量输入变量:年:年year, year, 月月month, month, 日日dayday; 输出变量输出变量:一年中的第几天:一年中的第几天day_of_yearday_of_year”Step 3: Step 3: 设计程序伪代码;设计程序伪代码;伪代码整体框架:伪代码整体框架: 输入年、月、日;输入年、月、日; 计算第几天计算第几天: 先加上当月的天数;先加上当月的天数; 加上这一年往月的加上这一年往月的天数,若包括二月,天数,若包括二月,则需考虑是否为闰年;则需考虑是否为闰年; 输出计算结果。输出计算结果。% % 输入

58、年、月、日输入年、月、日input year, month, dayinput year, month, day% % 计算第几天计算第几天% % 首先判断年份是否为闰年首先判断年份是否为闰年ifif year/400 year/400余余0 0 是闰年是闰年 leap_day=1leap_day=1else if else if year/100year/100余余0 0 不是闰不是闰年年 leap_day=0leap_day=0pagepage2727Step 3: Step 3: 设计程序伪代码设计程序伪代码- -续续elseifelseif year/4 year/4余余0 0 是闰年

59、是闰年 leap_day=1leap_day=1elseelse 不是闰年不是闰年 leap_day=0 %leap_day=0 %四年一闰;百年不闰四年一闰;百年不闰, ,四百年再闰四百年再闰endend% % 开始计算第几天开始计算第几天% % 首先加上当月的天数首先加上当月的天数day_of_year=dayday_of_year=day% % 加上这一年往月的天数加上这一年往月的天数forfor i=1:month-1 i=1:month-1 switchswitch (i) (i) case 1, 3, 5, 7, 8,10 case 1, 3, 5, 7, 8,10 day_of_

60、year=day_of_year+31day_of_year=day_of_year+31 case 4, 6, 9, 11 case 4, 6, 9, 11 day_of_year=day_of_year+30day_of_year=day_of_year+30 case 2 case 2 day_of_year=day_of_year+28+leap_dayday_of_year=day_of_year+28+leap_day endendendend% % 输出结果输出结果 print day_of_yearprint day_of_yearpagepage2828Step 4: Ste

温馨提示

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

评论

0/150

提交评论