Matlab 循环及跳出循环

目录

一、循环语句 for / while

二、三种循环中断语句 continue / break / return

三、如何在出现错误时继续下一次循环 try-catch-end

四、程序运行日志 diary

五、程序用时 tic toc


一、循环语句 for / while

需要重复运行的语句在 matlab 中可以用 for 或 while 循环来实现。

for
while

除了根据循环次数或循环条件选择合适的循环语句,为了使循环真正提高效率,提高循环的鲁棒性,并记录循环中的必要信息就尤为重要。

另外需要提醒的是,matlab 是更适合矩阵运算的语言,矩阵计算可行时优先选用矩阵计算。

二、三种循环中断语句 continue / break / return

continue 将控制传递给 for 或 while 循环的下一迭代。它跳过当前迭代的循环体中剩余的任何语句。程序继续从下一迭代执行。
break 终止执行(完全退出) for 或 while 循环。
return 将控制权交还给调用脚本或函数。(退出函数

三、如何在出现错误时继续下一次循环 try-catch-end

cd
diary()
diary off; % 如果希望只记录错误信息,创建日志文件后先关闭

tic
for i = 1:length()
    try
        statement
    catch ME
        diary on
        disp(['Error Message:'])
        disp(ME.identifier)
        disp(ME.message)
        for i = 1:numel(ME.stack)
           disp(ME.stack(i))
        end
        diary off
        continue
    end
end
toc

四、程序运行日志 diary

cd ''
diary('.txt')
diary on;
% statement
diary off

五、程序用时 tic toc

t1 = tic;
%statement
t2 = tic;
%statement
toc(t2)
toc(t1)

猜你喜欢

转载自blog.csdn.net/RainaRaina/article/details/127076639