【问题标题】:Save struct in middle of running MATLAB function在运行 MATLAB 函数的中间保存结构
【发布时间】:2015-09-07 13:02:44
【问题描述】:

我有一个函数可以迭代一堆代码大约 10-20 次,以生成一个 n*1 结构,该结构的每一行都有大量数据。运行每一行代码需要一段时间,当我运行它时,有可能我犯了错误或需要一些手动更正。我不想阻止代码运行,因为那样我将不得不失去以前所做的所有工作。是否可以将结构的每次迭代保存到工作区中,即使该函数尚未完成运行,然后在下一次迭代中用较新的版本覆盖该版本?

(例如,如果我运行了第一次迭代,我有一个 1*1 结构,这将保存,然后函数继续,给出一个 2*1 结构。我可以让它覆盖第一个版本,然后继续这样做,以防我在中间停止该功能?)

【问题讨论】:

  • 在循环中包含save fileName myStruct?这里myStruct 代表你的结构变量,filename 是你要保存到的文件。或者更好的是,在覆盖之前复制旧文件。在 Windows 上,! copy filename.mat filename.bak

标签: matlab function struct save


【解决方案1】:

您可以在循环中包含save fileName myStruct,其中myStruct 代表您的结构变量,filename 是您要保存到的名称。

如果程序在保存过程中停止或崩溃,最好在覆盖之前复制旧文件。你可以通过copyfile 做到这一点。

所以,代码是:

%// ...
fname = 'filename'; %// string contianing the file name
fid = fopen([fname '.mat'],'w'); %// create file, even if myStruct doesn't exist yet
fclose(fid); %// close file
for [...] %// your loop
    %// loop operations
    copyfile([fname '.mat'], [fname '.bak'], 'f') %// back up file
    save(fname, 'myStruct') %// overwrite file with updated myStruct 
end

【讨论】:

    【解决方案2】:

    我会使用try/catch 控制结构。这允许您定义在发生错误或运行时异常时应该发生的情况。

    假设你的函数返回有问题的结构,

    function foo = bar(baz)
    
    try
        % your code here
    catch some_exception
        warning(some_exception.msg);% print the exception so you can correct the error later. 
        return % instead of exiting with an error message, return to the caller, the last value of foo is returned 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 2017-02-21
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      相关资源
      最近更新 更多