当MATLAB中发生错误时,如何继续循环?

编程入门 行业动态 更新时间:2024-10-28 10:30:42
本文介绍了当MATLAB中发生错误时,如何继续循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用功能将某些.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中发生错误时,如何继续循环?

本文发布于:2023-10-24 07:49:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发生错误   MATLAB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!