控制循环退出的关键字Break、Continue和Return——MATLAB

控制循环退出的关键字Break、Continue和Return

for i = 1:2
    for j = 2:4
        disp(["i = " + num2str(i) + ", j = " + num2str(j)]);
    end
end

for i = 1: 2
    for j = 1 : 4
        if(j == 2)
            continue;   % 结束当前循环(continue后面的语句不再执行)
        end
        disp(["i = " + num2str(i) + ",j = " + num2str(j)]);
    end
end

for i = 1:2
    for j = 1 : 100
        if(j == 2)
            break ; %退出整层循环(一层)
        end
        disp(["i = " + num2str(i) + ", j = " + num2str(j)]);
    end
end

for i = 1:2
    for j = 1:3
        if(j == 2)
            return;%退出多层循环
        end
        disp(["i = " + num2str(i) + ", j = " + num2str(j)]);
    end
end

% Ctrl + i:智能缩进
for k = 1:5
    for i = 1:2
        for j = 1:3
            if(j == 2)
                return;     % 退出多层循环
            end
            disp(["k = " + num2str(k)+ " , i = " + num2str(i)+ ", j = " + num2str(j)]);
        end
    end
end









2021年8月24日笔记

    原文作者:晏清。
    原文地址: https://blog.csdn.net/weixin_46427623/article/details/119900575
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞