MATLAB for循环||MATLAB嵌套循环

MATLAB for循环

MATLAB中 for 循环是一个重复的控制结构,可以有效地写一个循环,只是执行的次数是特定的。

MATLAB for 循环语法:

MATLAB中的 for循环的语法如下:

for index = values
  
          ...
end

for 循环的值有下述三种形式之一:

格式 描述
initval:endval 将索引变量从初始到终值递增1,并重复执行程序语句,直到索引值大于终值。
initval:step:endval 按每次迭代中的值步骤递增索引, 或在步骤为负值时递减。
valArray 在每个迭代 valArrayon 数组的后续列中创建列向量索引。例如, 在第一次迭代中, index = valArray (:, 1),循环执行最大 n 次, 其中 n 是 valArray 的列数,由 numel (valArray, 1,:) 给出。输入 valArray 可以是任何 MATLAB 数据类型, 包括字符串、单元格数组或结构。

详细例子如下:

例子 1

在MATLAB中建立一个脚本文件,并输入下述代码:

for a = 10:20 
  fprintf('value of a: %d
', a);
end

运行文件,显示下述结果:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

例子 2

在MATLAB中建立一个脚本文件,并输入下述代码:

for a = 1.0: -0.1: 0.0
   disp(a)
end

运行该文件,显示以下结果:

1

    0.9000

    0.8000

    0.7000

    0.6000

    0.5000

    0.4000

    0.3000

    0.2000

    0.1000

     0

例子3

在MATLAB中建立一个脚本文件,并输入下述代码:

for a = [24,18,17,23,28]
   disp(a)
end

运行该文件,显示下述结果:

    24

    18

    17

    23

    28

MATLAB嵌套循环

MATLAB嵌套循环允许使用一个循环的另一循环内。

MATLAB嵌套循环语法:

在 MATLAB 中嵌套 for 循环语句的语法如下:

for m = 1:j
    for n = 1:k
        ;
    end
end

在 MATLAB 中嵌套 while 循环语句的语法如下:

while 
   while 
       
   end
end

详细例子

我们将使用一个嵌套循环来把所有从1到100的素数显示出来。

现在MATLAB中建立一个脚本文件,并输入下述代码:

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

然后运行该文件,显示如下结果:

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

你可能感兴趣的:(matlab入门教程,matlab,数据结构,开发语言,算法,c语言,c++)