11.控制流。包括
if if和else, elseif组合,条件执行一组语句
for 指定次数重复执行一组语句
while 按条件反复执行一组语句
break 终止for或者while循环
continue 马上开始下一次for或者while循环
switch switch和case,otherwise结合,按照条件值的不同执行不同的语句块
return 终止当前函数,返回到调用它的地方
try...catch 捕获异常状况
if语句
if expression1
statements1
elseif expression2
statements2
else
statements3
end
for循环
for index = start:increment:end
statements
end
比如
count = 0;
for k = 0:0.1:1
count = count +1
end
while循环
while expression
statements
end
比如
a = 10;
b = 5;
while a
a = a - 1;
while b
b = b - 1;
end
end
switch语句
switch switch_expression
case case_expression
statements
case {case_expression1, case_expression2}
statements
otherwise
statements
end
比如
switch newclass
case 'uint8'
g = im2uint8(f);
case 'uint16'
g = im2uint16(f);
case 'double'
g = im2double(f);
otherwise
error('Unknown or improper image class.')
end
例子:写一个函数计算一幅灰度图像所有像素的平均值
function av = average(A)
%AVERAGE Computes the average value of an array
% AV = AVERAGE(A) computes the average value of input array, A,
% which must be a 1D or 2D array.
% Check the validity of input.
if ndims(A) > 2
error('The dimensions of the input cannot exceed 2.')
end
% Computes the average
av =
例子:比较各种不同的JPEG质量下的图像质量
for q = 0:5:100
filename = sprintf('series_%3d.jpg', q);
imwrite(f, filename, 'quality', q);
end
其中sprintf语句和c语言的fprintf语句用法类似。例子:写一个函数从一个图像中取出一个矩形的子图。
function s = subdim(f, m, n, rx, cy)
%SUBDIM Extracts a subimage, s, from a given image, f.
% The subimage is of size m-by-n, and the coordinates of its top, left
% corner are (rx, cy).
s = zeros(m, n);
rowhigh = rx + m - 1;
colhigh = cy + n - 1;
xcount = 0;
for r = rx:rowhigh
xcount = xcount + 1;
ycount = 0;
for c = cy:colhigh
ycount = ycount + 1;
s(xcount, ycount) = f(r, c);
end
end
实际上这个功能可以用一个matlab语句就可以实现了。