问题描述
我正在使用功能将某些.dat文件转换为.mat文件.我在循环内调用此函数以转换许多文件.在某些情况下,我的.dat文件已损坏,函数无法转换并且发生错误,从而停止了循环.
I'm converting some .dat files into .mat files using a function. I'm calling this function inside a loop to convert a number of files. There are some cases where my .dat file is corrupted and the function cannot convert and an error occurs, stopping the loop.
现在我的问题是:是否有任何命令在发生错误时应跳过循环中的当前(i)值,并寻找下一个增量值(在我的情况下为下一个文件)?
Now my question is: Is there any command wherein when the error occurs it should skip the current (i) value in the loop and go for the next increment value (in my case the next file)?
推荐答案
您可以使用 TRY/CATCH 语句以及 CONTINUE .将以下内容放入循环中:
You can do this using a TRY/CATCH statement along with CONTINUE. Place the following inside your loop:
try %# Attempt to perform some computation
%# The operation you are trying to perform goes here
catch exception %# Catch the exception
continue %# Pass control to the next loop iteration
end
Amro在下面的评论中提出了一个好主意.您可能要发出警告,以显示该错误发生了以及针对哪个文件,或者您甚至可能希望保存未能正确转换的文件列表.要进行后者,您可以在开始循环之前首先初始化一个空单元格数组:
Amro suggests a good idea in his comment below. You may want to issue a warning showing that the error occurred and for which file, or perhaps you may even want to save a list of the files that failed to convert properly. To do the latter, you can first initialize an empty cell array before you start your loop:
failedFiles = {}; %# To store a list of the files that failed to convert
然后,在捕获异常之后但在发出continue
命令之前,将要转换的当前文件的名称/路径添加到列表中:
Then, after you catch the exception but before you issue the continue
command, add the name/path of the current file being converted to the list:
...
catch exception
failedFiles = [failedFiles; {'currentFile.dat'}];
continue
end
循环完成后,您可以查看failedFiles
轻松查看未正确转换的内容.
When your loop is done, you can then look at failedFiles
to easily see what didn't convert properly.
这篇关于当MATLAB中发生错误时,如何继续循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!