Loop Statement

Matlab Control Statements


!! MATLAB 循环效率低, 尽量用数组结构和内部函数代替循环

循环语句 loop statement, 又可以称为循环控制语句, 是 MATLAB 四大程序结构控制语句之一, 包含两种循环结构 for, while 和两个控制语句 continue, break.

for Loop

for i = <[start:<increment>:end]>
    block
end
  • 循环开始先将 i 赋值为 start
  • “增量” increment 默认为 1
    • 正数时, 每次判断 i 是否小于等于 end
    • 负数时, 每次判断 i 是否小于等于 end

!! 以上同 Matlab Array - Creating, 就是 i 遍历赋值为数组中元素

所以特别地, 对于一般的数值数组 A 可以有

for i = A
    block
end

其中 i 被赋值为 A 中的列向量, 于是 A 有多少列向量就循环多少轮. 例如对于 A = rand(2,2,2), 上面代码输出如下 (4 个列向量 )

    0.5060
    0.6991
 
    0.8909
    0.9593
 
    0.5472
    0.1386
 
    0.1493
    0.2575

while Loop

while condExp
    block
end

这里的条件表达式 condExp 判定完全同 if, else, elseif 语句

continue Statement

continue 语句用于退出当层, 当轮循环, 进入下一轮. 例子如下

for i = 1:3
    for j = 1:3
        if j == 2
            continue;
        end
        disp([i j])
    end
end

output:

1     1
 
1     3
 
2     1
 
2     3
 
3     1
 
3     3

break Statement

break 语句用于退出当层循环. 例子如下

for i = 1:3
    for j = 1:3
        if j == 2
            break;
        end
        disp([i j])
    end
end

output:

1     1
 
2     1
 
3     1