目录
一、结构化程式
1、逻辑运算符
运算符 | 作用 |
---|---|
< | 小于 |
<= | 小于或等于 |
> | 大于 |
>= | 大于或等于 |
== | 等于 |
~= | 不等于 |
&& | 且 |
2、流程控制语句以及示例
流程控制语句 | 作用 |
---|---|
if | 若if语句为真,则执行子句 |
switch | 根据switch语句内容判断执行哪个子句 |
while | 重复执行子句直到while中的条件为假 |
for | 执行子句固定次数 |
①if语句
if condition1 statement1; elseif condition2 statement2; else statement3; end
if语句示例1:
if rem(a,2)==0
disp('a is even');
else
disp('a is odd');
end
运行结果: a is odd
②switch语句
switch expression case value1 statement1; case value2 statement2; …… otherwise statement; end
switch语句示例:2
switch input_num
case -1
disp('negative 1');
case 0
disp('zero');
case 1
disp('positive 1');
otherwise
disp('other value');
end
运行结果:other value
③while语句
while expression statement; end
n = 1;
while prod(1:n) < 1e100 //prod函数用于求数组元素的乘积
n = n + 1;
end
运行结果: n=70
④for语句
for variable=start:increment:end commands; end
for n=1:10
a(n)=2^n;
end
disp(a)
2 4 8 16 32 64 128 256 512 1024
★上述所有循环和条件语句都要在末尾以end闭合
⑤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
3、为变量预分配空间(pre-allocating space to variables)
①NOT pre-allocating
tic
for ii = 1:2000
for jj = 1:2000
A(ii,jj) = ii + jj;
end
end
toc
程序结果:时间已过 3.754662 秒。
②Pre-allocating
tic
A = zeros(2000, 2000); // 预先为变量分配内存空间
for ii = 1:size(A,1)
for jj = 1:size(A,2)
A(ii,jj) = ii + jj;
end
end
toc
程序结果:时间已过 0.038823 秒。
程序一比程序二所用的时间更长.这是因为: 对于程序一,没有预先为变量A分配内存,因此每当A的形状发生改变时,都需要重新为A分配内存地址,这花费了更多的时间。
二、函数(Funtions)
1、查看内置函数
edit(which('mean.m'))
在matlab中看到mean的源代码如下:
2、撰写函数
①自由落体
function x = freebody(x0,v0,t)
% calculation of free falling
% x0: initial displacement in m
% v0: initial velocity in m/sec
% t: the elapsed time in sec
% x: the depth of falling in m
x = x0 + v0.*t + 1/2*9.8*t.*t;
使用方式:
freebody(0, 0, 2)
freebody(0, 0, [0 1 2 3])
freebody(0, 0, [0 1; 2 3])
得到 19.6000
得到 [0 4.9000 19.6000 44.1000]
得到 [0 4.9000; 19.6000 44.1000]
②bubblesort算法
代码运行
运行结果
③判断闰年
判断闰年程序
运行程序
运行程序结果
④华氏温度到摄氏温度的转换
function F2C()
while 1
F_degree = input('tempreature in Fahrenheit: ', 's');
F_degree = str2num(F_degree);
if isempty(F_degree)
return
end
C_degree = (F_degree-32)*5/9;
disp(['tempreature in Celsius: ' num2str(C_degree)])
end