- Matlab教程
- MATLAB - 主页
- MATLAB - 概述
- MATLAB - 环境设置
- MATLAB - 语法
- MATLAB - 变量
- MATLAB - 命令
- MATLAB - M 文件
- MATLAB - 数据类型
- MATLAB - 运算符
- MATLAB - 决策
- MATLAB - 循环
- MATLAB - 向量
- MATLAB - 矩阵
- MATLAB - 数组
- MATLAB - 冒号表示法
- MATLAB - 数字
- MATLAB - 字符串
- MATLAB - 函数
- MATLAB - 数据导入
- MATLAB - 数据输出
- MATLAB 高级版
- MATLAB - 绘图
- MATLAB - 图形
- MATLAB - 代数
- MATLAB - 微积分
- MATLAB - 微分
- MATLAB - 集成
- MATLAB - 多项式
- MATLAB - 变换
- MATLAB - GNU Octave
- MATLAB - Simulink
- MATLAB 有用资源
- MATLAB - 快速指南
- MATLAB - 有用的资源
- MATLAB - 讨论
MATLAB - The for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in MATLAB is −
for index = values <program statements> ... end
values has one of the following forms −
Sr.No. | Format & Description |
---|---|
1 | initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval. |
2 | initval:step:endval increments index by the value step on each iteration, or decrements when step is negative. |
3 | valArray creates a column vector index from subsequent columns of array valArray on 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. |
Example 1
Create a script file and type the following code −
for a = 10:20 fprintf('value of a: %d\n', a); end
When you run the file, it displays the following result −
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
Example 2
Create a script file and type the following code −
for a = 1.0: -0.1: 0.0 disp(a) end
When you run the file, it displays the following result −
1 0.90000 0.80000 0.70000 0.60000 0.50000 0.40000 0.30000 0.20000 0.10000 0
Example 3
Create a script file and type the following code −
for a = [24,18,17,23,28] disp(a) end
When you run the file, it displays the following result −
24 18 17 23 28