MATLAB for循环

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

语法:

在MATLAB中的 for循环的语法是:

for index = values
  <program statements>
          ...
end

值有下列形式之一:

格式 描述
initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.
initval:step:endval increments index by the value step on each iteration, or decrements when step is negative.
valArray creates a column vector index from subsequent columns of array valArrayon each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct.

例子 1

创建一个脚本文件,并键入下面的代码:

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

创建一个脚本文件,并键入下面的代码:

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

创建一个脚本文件,并键入下面的代码:

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

当您运行该文件,它会显示以下结果:

24
18
17
23
28
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3