Matlab嵌套迴圈

MATLAB允許在一個迴圈中使用另一個迴圈。以下部分顯示了幾個例子來說明這個概念。

語法

MATLAB中嵌套for迴圈語句的語法如下:

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

MATLAB中的嵌套while迴圈語句的語法如下:

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

例子

讓使用一個嵌套的for迴圈來顯示從1100的所有素數。創建腳本檔並編寫以下代碼 -

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 是一個素數\n', i);
   end
end

執行以上示例代碼,得到以下結果 -

2 是一個素數

3 是一個素數

5 是一個素數

7 是一個素數

11 是一個素數

13 是一個素數

17 是一個素數

19 是一個素數

23 是一個素數

29 是一個素數

31 是一個素數

37 是一個素數

41 是一個素數

43 是一個素數

47 是一個素數

53 是一個素數

59 是一個素數

61 是一個素數

67 是一個素數

71 是一個素數

73 是一個素數

79 是一個素數

83 是一個素數

89 是一個素數

97 是一個素數


上一篇: Matlab迴圈 下一篇: Matlab向量