How can I continue with a loop when an error occurs in MATLAB?

前端 未结 1 1584
渐次进展
渐次进展 2021-02-13 13:27

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

相关标签:
1条回答
  • 2021-02-13 13:51

    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
    

    EDIT:

    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
    

    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
    

    When your loop is done, you can then look at failedFiles to easily see what didn't convert properly.

    0 讨论(0)
提交回复
热议问题