MATLAB嵌套循環(huán)

2018-08-11 14:30 更新

MATLAB嵌套循環(huán)允許使用一個(gè)循環(huán)的另一循環(huán)內(nèi)。

MATLAB嵌套循環(huán)語(yǔ)法:

在 MATLAB 中嵌套 for 循環(huán)語(yǔ)句的語(yǔ)法如下:

for m = 1:j
    for n = 1:k
        <statements>;
    end
end

在 MATLAB 中嵌套 while 循環(huán)語(yǔ)句的語(yǔ)法如下:

while <expression1>
   while <expression2>
       <statements>
   end
end

詳細(xì)例子

我們將使用一個(gè)嵌套循環(huán)來(lái)把所有從1到100的素?cái)?shù)顯示出來(lái)。

現(xiàn)在MATLAB中建立一個(gè)腳本文件,并輸入下述代碼:

for i=2:100
       for j=2:100
        if(~mod(i,j)) 
            break; % if factor found, not prime
        end 
      end
      if(j > (i/j))
          fprintf('%d is prime
', i);
      end
end

然后運(yùn)行該文件,顯示如下結(jié)果:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)