190 likes | 330 Views
Matlab 计算与仿真技术 第七讲 : Matlab 编程 -III http://human-robot.sysu.edu.cn/course. 王国利. http://sysu.edu.cn/~isswgl. 信息科学与技术学院. 中山大学. 第七讲提纲. 第六讲回顾 Matlab 编程 (III). 第六讲回顾. 函数及变量传递 - 使用方式 : 调用 / 嵌套 - 协作方式 : 主函数 / 子函数 / 嵌套函数 - 内部变量 : 生存周期控制 - 变量传递 : 变量查询功能 函数句柄 - 支持匿名函数 - 支持变量传递
E N D
Matlab计算与仿真技术 第七讲: Matlab编程-III http://human-robot.sysu.edu.cn/course 王国利 http://sysu.edu.cn/~isswgl 信息科学与技术学院 中山大学
第七讲提纲 • 第六讲回顾 • Matlab编程(III)
第六讲回顾 • 函数及变量传递 - 使用方式: 调用/嵌套 - 协作方式: 主函数/子函数/嵌套函数 - 内部变量: 生存周期控制 - 变量传递: 变量查询功能 • 函数句柄 - 支持匿名函数 - 支持变量传递 • 控制语句 - if /if-else/if-elseif-…-else - switch-case - for/while
Matlab编程 (续) if 语句一般形式 if logical_expression block of statements elseif logical_expression block of statements … … else block of statements end
Matlab编程 (续) switch语句 一般形式 switch expression case value1, block of statements case value2, block of statements ... otherwise, block of statements end
Matlab编程 (续) - 循环结构 根据条件重复执行程序指令或模块 for 语句 %计数循环 一般形式 for index = expression block of statements end
Matlab编程 (续) while语句 一般形式 while expression block of statements end
Matlab编程 (续) while语句实例: 循环中断控制 x = rand(1,10); k = 1; while k<=10 if x(k)>0.8 break end k = k + 1; end
Matlab编程 (续) while语句实例: 函数返回控制 x = rand(1,10); k = 1; while k<=10 if x(k)>0.8 return end k = k + 1; end
Matlab编程 (续) • 综合练习五:菲波那锲序列 -菲波那锲序列回顾 初值: f1=1,f2=1 递推: fn=fn-1+fn-2 - 方式一: 序列生成 目标: 产生前n个菲波那锲数 - 方式二: 元素生成 目标: 产生第n个菲波那锲数 回想兔子种群繁殖的规律
Matlab编程 (续) - 方式一: m-函数实例 1: function f=fibonacci(n) % generating first n fibonacci numbers 2: f=zeros(n,1); 3: f(1)=1; f(2)=1; 4: for k=3:n 5: f(k)=f(k-1)+f(k-2); 6: end >> F=fibonacci(20); >> phi=F(15)/F(14) phi = 1.6180
Matlab编程 (续) - 方式二: m-函数实例 1: function f=bnum(n) % generating the nth fibonacci number 2: if n <=1 3: f=1; 4: else 5: f=bnum(n-1)+bnum(n-2); 6: end >> phi=fibnum(15)/fibnum(14) phi = 1.6180
Matlab编程 (续) 综合练习六: 利用级数展开近似计算 sin - 提示 sin的级数展开为 - m-函数实例 1: function s=powersin(x); 2: % POWERSIN. Power series for sin(x). 3: % POWERSIN(x) tries to compute… sin(x) from a power series.
Matlab编程 (续) 4: s=0; 5: t=x; 6: n=1: 7: while abs(t) > eps 8: s=s+t; 9: t=-x.^2/((n+1)*(n+2)).*t; 10: n=n+2; 11: end
Matlab编程 (续) • 综合练习七: 生命周期曲线 - 提示: 生理-23天; 情感-28天; 智力-33天 function biorythm(mybirthday) t0=datenum(mybirthday); t1=fix(now); t=(t1-28):1:(t1+28); t=t'; y=100*[sin(2*pi*(t-t0)/23) … sin(2*pi*(t-t0)/28) … sin(2*pi*(t-t0)/33)];
Matlab编程 (续) plot(t,y(:,1),t,y(:,2),'--',t,y(:,3),'.-',[t1 t1],[-100 100],'k:'); datetick('x','dd/mm','keeplimits'); axis tight; title(mybirthday); legend('Physical','Emotional','Intellectual'); xlabel('time[dd/mm]'); ylabel('biorythm index [%]')
Matlab编程 (续) • 程序调试初步 - 程序错误 语法错误: 重点检查语法 运行错误: 需要综合分析 - 错误查询 显示中间结果: 去掉分号 设置断点监控: m-文件编辑器中的Debug工具
交互式计算单元测验 遵守考试规则! 提示: - 填入你的姓名 - 填入你的班级 - 填入你的学号
结束语 第八讲预告: Matlab编程 (IV) (2007年11月5日)