baidut
2/24/2017 - 2:26 AM

for 的用法

for 的用法

% 对于循环之间独立的情形,用 generic for
z = [1, 3, 7, 11, 15];
for each = z
 disp( each ); 
end

% 循环之间不独立
for n = 1: numel(z) % 注意区分函数 numel 和 length
 disp( z(n) );
end

% 用结构体组织数据
Bob.gender = 'male'; Bob.age = 11;
Tom.gender = 'female'; Tom.age = 12;
for person = [Bob Tom] % 注意这里只读,可以防止数据在循环内被修改
	fprintf('Male: %s Age: %d\n', person.gender, person.age);
end

% 读取字符元胞
for s = {'hello', 'world', '!'}, string = s{1};
	disp(string);
end

for string = {'hello', 'world', '!'}, string = string{1};
	disp(string);
end

% 遍历结构体的各个域
% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)', f = f{1};
    s.(f) = s.(f)';
end
s

% 遍历文件夹下的文件
% 方法1
for file = dir('*.m')'
	disp(file.name);
end
% 方法2 需要安装 each 工具箱
for file = each(dir('*.m'))
	disp(file.date);
end

% ref
% http://stackoverflow.com/questions/408080/is-there-a-foreach-in-matlab-if-so-how-does-it-behave-if-the-underlying-data-c
n = 0;
for a = this.algoList, algo = a{1}; n = n+1;

vs

for n = 1:numel(this.algoList), algo = this.algoList{n}; 只读
% 每次取出一列
% for n = I, idx = idx+1;
% 	isequal(n, I(:,idx))
% end

% 遍历矩阵
for n = magic(3)
	disp(n)
end
disp(magic(3))

% 遍历元胞
for n = {1,2,3;4,5,6;7,8,9}
	disp(n)
end

% 遍历图像
I = imread('peppers.png');
idx = 0;
for n = I, idx = idx+1;
	isequal(n, I(:,idx))
end