MATLAB嵌套循环
示例
可以嵌套循环,以在另一个迭代任务中执行迭代任务。考虑以下循环:
ch = 'abc';
m = 3;
for c = ch
for k = 1:m
disp([c num2str(k)]) % NUM2STR converts the number stored in k to a charachter,
% so it can be concataneted with the letter in c
end
end我们使用2个迭代器来显示abc和中元素的所有组合1:m,从而得出:
a1 a2 a3 b1 b2 b3 c1 c2 c3
我们还可以使用嵌套循环来组合每次要完成的任务和几次迭代中要完成的任务:
N = 10;
n = 3;
a1 = 0; % the first element in Fibonacci series
a2 = 1; % the secound element in Fibonacci series
for j = 1:N
for k = 1:n
an = a1 + a2; % compute the next element in Fibonacci series
a1 = a2; % save the previous element for the next iteration
a2 = an; % save ht new element for the next iteration
end
disp(an) % display every n'th element
end这里我们要计算所有的斐波那契数列,但是n每次只显示第一个元素,所以我们得到
3 13 55 233 987 4181 17711 75025 317811 1346269
我们可以做的另一件事是在内部循环中使用第一个(外部)迭代器。这是另一个示例:
N = 12;
gap = [1 2 3 4 6];
for j = gap
for k = 1:j:N
fprintf('%d ',k) % FPRINTF prints the number k proceeding to the next the line
end
fprintf('\n') % go to the next line
end这次我们使用嵌套循环来格式化输出,并且仅当j在元素之间引入新的间隙()时才制动行。我们循环遍历外部循环中的间隙宽度,并在内部循环中使用它来遍历向量:
1 2 3 4 5 6 7 8 9 10 11 12 1 3 5 7 9 11 1 4 7 10 1 5 9 1 7
热门推荐
5 简短元宵节祝福语
10 给妈妈祝福语简短内容
11 生日祝福语 简短独特潮
12 祝福语15字以内简短
13 中秋祝福语简短女朋友
14 生活老师离别祝福语简短
15 升学宴同学祝福语简短
16 老人去世简短祝福语
17 过生日祝福语简短爸爸
18 退伍祝福语老师简短