【问题标题】:how to save matlab running code and resume it later如何保存matlab运行代码并稍后恢复
【发布时间】:2018-07-16 08:28:55
【问题描述】:

我正在运行一个需要几天才能完成的 Matlab 程序。由于我国缺电的一些问题!程序无法在所需的时间内继续运行。因此,我想在某些时候保存正在运行的进程,以便能够在任何中断之前从上次保存的位置恢复代码。 我可以保存变量并编写一个复杂的代码来实现这一点,但由于程序非常复杂,有很多变量,而且......这样做很难。 Matlab 是否支持这样的要求?

【问题讨论】:

  • 不,您必须定期保存结果并设计您的代码以在简历中读取以前的结果。

标签: matlab


【解决方案1】:

你可以save your workspace在你想要的点:

% Some code
...
% Save the workspace variables in a .mat file
save myVariables.mat

这样做,您的所有变量都将存储在myVariables.mat 文件中。请注意,您的文件大小可能很重要。

然后您可以轻松加载工作区:

% Load the saved variables
load myVariables.mat

但是,您必须修改代码以处理中断。一种方法是添加一个变量来检查上次保存的状态,并仅在尚未保存时运行该步骤。

例如:

% load the workspace, if it exists
if exists('myVariables.mat', 'file') == 2
    load 'myVariables.mat'
else
    % If it does not exist, compute the whole process from the beginning
    stepIdx = 0
end

% Check the stepIdx variable
if stepIdx == 0
    % Process the first step of the process
    ...
    % mark the step as processed
    stepIdx = stepIdx + 1
    % Save your workspace
    save 'myVariables.mat'
end

% Check if the second step hass been processed
if stepIdx <=1
    % Process the step
    ....
    % mark the step as processed
    stepIdx = stepIdx + 1
    % Save your workspace
    save 'myVariables.mat'
end

% Continue for each part of your program

编辑 正如@brainkz 指出的那样,您的工作区肯定会计算大量变量,这除了会导致大型 .mat 文件外,还会使保存指令耗时。 @brainkz 建议通过将相关变量作为参数传递给 save 命令来仅保存相关变量。根据您的代码,使用字符串可以更轻松地处理并在此过程中完成此变量。例如:

% ---- One step of your program
strVariables = ''
x = ... % some calculation
y = ... % more calculation
strVariables = [strVariables, 'x y ']; % note that you can directly write strVariables = ' x y'
z = ... % even more calculation
strVariables = [strVariables, 'z '];
% Save the variables
save('myVariables.mat', strVariables )

对于其他步骤,如果您不再需要它的包含或保留它,您可以清除strVariables

【讨论】:

  • 我认为他正在寻找其他方式。他已经在问题中提到保存变量对他来说很难。
  • 是的,但他说他使用了复杂的代码来做到这一点,我提出了一种在一行中执行此操作的方法。 .mat 文件的大小可能很重要。
  • 不错的答案。我要补充一点,由于 OP 的代码很复杂,保存整个工作区可能会很耗时,最好只保留相关变量。
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 2018-02-27
  • 2014-12-21
  • 2020-01-27
  • 2010-12-05
  • 1970-01-01
  • 2019-04-19
  • 2013-04-25
相关资源
最近更新 更多