Reza_va
Reza_va

Reputation: 91

how to save matlab running code and resume it later

I am running a Matlab program which requires days to be fulfilled. Due to some problems with the lack of electricity in my country! the program cant keep running for the required period. Accordingly, I want to save the running process at some points so that I will be able to resume the code from where it was last saved prior to any interruption. I can save the variables and write a complex code to achieve this, but as the program is very complex with lots of variables and .... It would be very hard to do so. Does Matlab supports such requirements?

Upvotes: 1

Views: 641

Answers (1)

ractiv
ractiv

Reputation: 752

You can save your workspace at a the points you want:

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

Doing so all your variables will be stored in the myVariables.mat file. Carefull, your file size may be important though.

You can then load the workspace easily:

% Load the saved variables
load myVariables.mat

However, you will have to modify your code to handle interruptions. One way is to add a variable to check the last saved state and to run the step only if it has not been saved.

For example:

% 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

EDIT As @brainkz pointed out, your workspace certainly count a large number of variables, which in addition to lead to a large .mat file will make the saving instruction time consuming. @brainkz suggested to save only relevant variables by passing them as argument to the save command. Depending on your code, it can be easier to handle by using a string and complete this variable during the process. For example :

% ---- 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 )

For other steps, you can clear strVariables if you don't need its containt any more or keep it.

Upvotes: 2

Related Questions