我有一个函数,它遍历一堆代码大约10-20次,得到一个n*1的结构,结构的每一行都有大量数据。它需要一段时间来遍历每一行代码,当我运行它时,有可能我犯了一个错误,或者需要一些手动更正。我不想停止代码的运行,因为那样我将不得不丢失我以前所做的所有工作。有没有可能将结构的每次迭代保存到工作区中,即使函数还没有运行完,然后在下一次迭代中用较新的版本覆盖该版本?
(例如,如果我运行了第一次迭代,我有一个1*1的结构,这将保存,然后函数继续,给出一个2*1的结构。我是否可以让它覆盖第一个版本,然后继续这样做,以防我在中间停止函数?)
发布于 2015-09-07 22:40:56
您可以在循环中包含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
发布于 2015-09-07 23:16:05
我将使用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
https://stackoverflow.com/questions/32439464
复制相似问题