结构化程式与自定函数

MATLAB Script

  • .m结尾的文件
  • 不需要像c/c++一样需要编译
  • %开头表示注解, %%则表示section一个块,可选择run section来运行一个子块来debug。
  • 设置断点直接点击代码对应那行最左边序号,显示红点
  • ctrl+A或者手动选代码右键有注释与解注释以及智能缩进smart-indent功能

structure programming

1

1

所有块语法都要带上end结尾

if elseif else

“elseif” and “else” are optional

1
2
3
4
5
6
a = 3;
if rem(a,2) == 0 % rem求余
disp('a is even')
else
disp('a is odd')
end

switch

1
2
3
4
5
6
7
8
9
10
11
input_num = 1;
switch input_num
case -1
disp('negative 1');
case 0
disp('zero');
case 0
disp('positive 1');
otherwise
disp('other value');
end

while

1
2
3
4
n = 1;
while prod(1:n) < 1e100 % prod-> product 乘的意思 1:n->[1,2,3,...,n] n! < 1e100 ->1*10^100
n = n+1;
end

for

1
2
3
4
for n = 1:10
a(n) = 2^10; % a(n) 表示a中第n个元素
end
disp(a)

Tips for Script Writing

  • At the beginning of your script, use:
    • clear all to remove previous variables
    • close all to close all figures
  • use ‘;’ at the end of commands unwanted output
  • use ellipsis … to make scripts more readable:

    1
    2
    A = [1 2 3 4 5 6; ...
    6 5 4 3 2 1];
  • Press Ctrl+c to terminate the script before conclusion

Scripts vs Functions

  • Scripts and functions are both .m files that contain MATLAB commands
  • Function are written when we need to perform routines

Content of MATLAB Built-in Functions

edit(which('mean.m'))

1

User Define Functions

1

Functions with Multiple Inputs and Outputs

1

Function Handles

a way to create anonymous functions

one line expression functions that do not have to be defined in .m files

1
2
3
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x, f(x));
Donate? comment?