MATLAB-程序设计

Matlab_3 程序设计

 M脚本文件
 流程控制
 函数
 文件管理
 调试和优化

M脚本文件

关于脚本语言
http://zh.wikipedia.org/wiki/%E8%84%9A%E6%9C%AC%E8%AF%AD%E8%A8%80

M文件的创建和编辑
Matlab Editor提供文本编辑和运行调试的集成环境。
Editor自动进行文法检查。
Editor自动给出语句格式如循环和条件语句的缩进格式、程序分块等辅助工具。
M文件以扩展名.m标识。

M文件的运行
在命令窗口中输入文件名或Editor中选择直接运行。
M文件代码和在Command Window中逐条输入效果相同,变量在Matlab Workspace中显示。

编写M脚本文件的注意事项:

文件名:
与变量命名规则相同。

行注释:
一行中,百分号%以后的为注释内容。
第一行注释(H1)很重要,用于简要说明文件的用途、功能等。
第一个可执行代码前的注释区可以通过help直接查看。

块注释:
以%{开头的行的至以%}开头的行之间的所有内容,注意这两行不要写其它内容

代码单元:
以%%标识,至下个%%或文件结尾
仅为代码书写、阅读和调试提供方便,不影响运行

续行:
对一个很长表达式,在该行的末尾处用换行符 ‘…’ 表示续行。

%% 例:M-file格式
%(复制以下代码到mfileform.m文件)
% --------------------------------------------------
% H1:简要说明程序功能
% 符号、公式、算法、流程说明
% …
% Matlab版本;程序创建和修改信息
% 以上信息可以用 help filename 查看

%% 变量定义单元
s1 = ‘M文件’;
s2 = ‘推荐格式’;
%…

%% 计算代码单元
output = { [s1 s2] ‘Thank you for your attention.’ } ;
%…

%% 结果处理单元
celldisp(output)
%…

几个控制文件执行的函数:

beep
disp(…)
echo on/off
input
keyboard
pause, pause(n)
waitforbuttonpress

%% copy to demoinput.m
% ----------------------------------------------------
% demo input function

answer = input( ‘is this okay? [y/n]:’, ‘s’);

if( answer == ‘y’ )
disp(‘great, lets go.’)
else
disp(‘anything wrong?’)
end

%% copy to demokeyboard.m
% ----------------------------------------------
% demo keyboard function
% K>> (in debug mode)
% K>> dbcont (return/continue the programm)

x = (-3:3)*pi/3;
y = sin(x)./x;

keyboard; % turn to debug mode

result = mean(y)

% …

程序定时器—timer

% timer函数创建定时器对象

help timer % 了解timer功能

doc timer % 查看timer函数用法

%% 例:延时启动
% 运行结果不回送Word文档

% 设置定时器:20秒后启动应用程序

t = timer( ‘TimerFcn’, ‘mfileform’, ‘StartDelay’, 20 );

start(t) % 启动定时器

%% 设置定时启动

t1 = timer( ‘TimerFcn’, ‘disp(’‘task over!’’)’ );

startat( t1, ‘hh:mm:ss’ ); % start at set time.

startat( t1, now + 1/24/3600*20 ) % start after 20sec.

%% 查找和删除定时器对象

timerfind

delete( t )

delete( t1 )

delete( timerfind ) % delete all

流程控制

Matlab提供的5种流程控制结构:

For
While
If-Else-End
Switch-Case
Try-Catch

For循环

格式
for x = array
( commands…)
end
x: 循环变量,array: 条件数组

For循环根据array的列数确定循环次数。
Array有几列,commands就执行几次。

% 比较下列两段代码的循环次数
n=0;
for i = 1:10
a(i) = sin(i*pi/180);
n = n+1;
end;
n, a

n = 0;
for i = (1:10).’
b(i) = sin(i*pi/180);
n=n+1;
end;
n, b

% 条件数组可以是任何合法的数组
array = randperm(10), % again, array = magic(3)
n=0;
for i = array
a(i) = i.^2;
n = n+1;
end;
n, a

% 循环嵌套(生成pasacal矩阵)
n = 5;
a = ones(5);

for j = 2:n
for i = 2:n
a(i, j) = a(i-1,j)+a(i,j-1);
end
disp(j)
end
a

While循环

格式
while expression
(commands…)
end

expression为条件表达式
expression可以是标量,也可以是表达式。只要expression为True,commands一直执行下去。
如expression为数组,只有数组所有元素为True,commands才一直执行下去。

% 测试N = 1, 10, 1e10的相对浮点精度

iteration = 0; Eps = 1; N = 1;

while (N+E

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值