matlab 怎么嵌套循环,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值