MATLAB程序设计实验

科学计算与数据处理实验报告

学 号 实验名称 姓 名 MATLAB程序设计实验 实验目的 1.掌握M文件的编辑、调试和性能剖析方法 2.掌握MATLAB脚本和函数的设计方法 3.掌握MATLAB程序的基本语法、关系运算和控制结构 4.掌握串演算函数的用法 实验方案 1. 编写两段简短的代码,演示MATLAB脚本和函数的不同: 脚本和函数的不同点是:函数需要通过function来声明,一般有输入参数和输出参数。脚本是按顺序一条一条命令逐行执行。编写一个函数文件myfun.m和一个脚本文件myfunscript.m,来演示脚本和函数的不同。 2. 编写程序演示控制结构的用法: 编写程序分别来演示循环(for、while)、分支(if-else-end、switch-case)和异常处理(try-catch)控制结构的用法。 3.编写程序分别演示以下命令的功能。return的返回功能,input的输入功能。keyboard语句常用在程序调试和运行中的变量修改。用户在程序中使用keyboard语句,在系统执行此语句时,将停止文件的执行,显示提示符“K>>”并把控制权交给键盘,等待用户的输入。当pause语句执行时,系统暂停执行,等待用户按任意键继续执行。break终止本次循环,跳出最内层循环中剩下的语句。error输出错误信息。lasterr显示或返回上一条出错的信息。warning遇到错误需要给使用者必要的提示,warning语句是常见的警告提示语句。lastwarn存放最新的警告信息。 4.串演算实验:设计实验演示以下函数的功能和用法。eval是执行包含MATLAB表达式/命令的字符串,feval是调用某个函数的另一个方法。 5.程序调试实验:对程序错误进行调试,总结调试过程,指出并改正所给程序的出错语句,记录程序出错时和调通后显示的图形。 6.程序性能剖析实验:利用剖析器(profile viewer)对relaxzzy(300)进行运行分析,找出relaxzzy函数中最耗时的语句,记录其执行时间、被调用次数,并指出该语句是否可以被加速。 实验记录 1. 编写两段简短的代码,演示MATLAB脚本和函数的不同: (1) 函数文件: 文件名:myfun.m function y =myfun(a,b) disp(sprintf('My first input is \disp(sprintf('My second input is \y=a+b; 运行结果: >>x=5;y=6;y=myfun(x,y) >>My first input is \My second input is \>>y = 11 (2) 脚本文件: 文件名:myfunscript.m a=2; b=2; clf; x=-a:0.2:a; y=-b:0.2:b; for i=1:length(y) for j=1:length(x) if x(j)+y(i)>1 z(i,j)=0.5457*exp(-0.75*y(i)^2-3.75*x(j)^2-1.5*x(j)); elseif x(j)+y(i)<=-1 z(i,j)=0.5457*exp(-0.75*y(i)^2-3.75*x(j)^2+1.5*x(j)); else z(i,j)=0.7575*exp(-y(i)^2-6.*x(j)^2); end end end axis([-a,a,-b,b,min(min(z)),max(max(z))]); colormap(flipud(winter));surf(x,y,z); 运行结果: 0.80.60.40.20210-1-2-2-1102 2. 编写程序演示控制结构的用法: (1) for循环: >> syms n fact_n >> fact_n=1; >> n=input('please enter a positive integer:'); please enter a positive integer:5 >> fact_n=1; >> for ii=1:n fact_n=fact_n*ii; end >> fprintf('The factional function of %f is :%f\\n',n,fact_n); The factional function of 5. is :120. (2) While循环: clear syms x n sum_x sum_x2 xbar std_dev n=0;sum_x=0;sum_x2=0; x=input('Please enter the first sample:'); while isnumeric(x)&&isempty(x)==0 n=n+1; xmat(n)=x; sum_x=sum_x+x; x=input('Please enter next sample'); end x_bar=sum_x/n; for ii=1:n sum_x2=sum_x2+(xmat(ii)-x_bar)^2; end std_dev=sqrt(sum_x2/n); fprintf('The number of data points is :%f\\n',n); fprintf('The mean of this data set is :%f\\n',x_bar); fprintf('The standard deviation is :%f\\n',std_dev); 运行结果: Please enter the first sample:12 Please enter next sample24 Please enter next sample12 Please enter next sample23 Please enter next sample23 Please enter next sample1 Please enter next sample45 Please enter next sample45 Please enter next sample45 Please enter next sample21 Please enter next sample12 Please enter next sample11 Please enter next sample111 Please enter next sample11 Please enter next sample45 Please enter next sample45 Please enter next sample45 Please enter next sample1 Please enter next sample1 Please enter next sample1

3

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4