首页 > 解决方案 > 如何保存matlab运行代码并稍后恢复

问题描述

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

标签: matlab

解决方案


您可以将工作区保存在您想要的位置:

% 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是否不再需要它的包含或保留它。


推荐阅读