结构化编程和函数定义

脚本

文件后缀:.m

  1. 新建脚本
  2. 编辑脚本
  3. 运行脚本
    run:

    在命令界面直接输入文件

流程控制

语句

运算符

实例

  1. if
if rem(a, 2) == 0
	disp('a is even');
else
	disp('a is odd');
end

2 switch

switch input_num
case -1
	disp('negative 1');
case 0
	disp('zero');
case 1
	disp('positive 1');
otherwise
	disp('other value');
end
  1. while
n = 1;
while prod(1:n) < 1e100
	n = n + 1;
end
  1. for
for n = 1:2:10
  a(n)=2^n;
end
disp(a)
  1. break
x = 2; k = 0; error = inf;
error_threshold = 1e-32;
while error > error_threshold
    if k > 100
    	break
    end
    x = x - sin(x)/cos(x);
    error = abs(x - pi);
    k = k + 1;
end
  1. Tips:
  • 使用省略号...拼接多行语句
annPoints_sampled = annPoints(annPoints(:,1)>x1 & ...
    annPoints(:,1) < x2 & ...
    annPoints(:,2) > y1 & ...
    annPoints(:,2) < y2);

函数

查看内置函数

which命令查看内置函数源代码文件位置,edit命令结合查看内置函数源代码
实例:edit(which('mean.m'))

定义函数

function [输出变量名] = 函数名(输入变量名)
% 函数文档

函数代码
  • 函数名因与.m文件名相同,且不包含特殊字符.

函数内置参数

句柄形式定义函数

函数句柄 = @(输入变量) 输出变量
实例:

f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x, f(x));

详细内容请看

posted @ 2021-09-08 10:17  常进  阅读(126)  评论(0编辑  收藏  举报