你可以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。