MATLAB还允许在另一个循环中使用一个循环。
MATLAB中嵌套的for循环语句的语法如下:
for m = 1:j for n = 1:k <
statements>
;
end end
MATLAB中嵌套的while循环语句的语法如下:
while <
expression1>
while <
expression2>
<
statements>
endend
例子【MATLAB嵌套循环语句】我们可以使用嵌套的for循环显示从1到100的所有素数。
for i=2:100for j=2:100if(~mod(i, j))break;
% if factor found, not primeendendif(j >
(i/j))fprintf('%d is prime\n', i);
endend
输出
2 is prime3 is prime5 is prime7 is prime11 is prime13 is prime17 is prime19 is prime23 is prime29 is prime31 is prime37 is prime41 is prime43 is prime47 is prime53 is prime59 is prime61 is prime67 is prime71 is prime73 is prime79 is prime83 is prime89 is prime97 is prime
推荐阅读
- MATLAB while循环语句
- MATLAB for循环语句
- MATLAB中的工作区,变量和函数
- MATLAB循环语句
- MATLAB switch语句
- MATLAB嵌套if-else语句
- MATLAB if-elseif-else…end语句
- MATLAB if-else…end语句
- MATLAB if…end语句