from Resume a long, looped simulation by Guzman
Called from within a function, it stores/retrives the workspace of the latter, allowing resuming.

ManageLongSimulation.m
function ManageLongSimulation

%MANAGELONGSIMULATION stores and retrives data for resuming long simulations
%
% The resume data is stored in the variable 'resume<name of main file>.mat'.
% For starting from scratch, the variable 'resumeData.mat' mus be manually
% deleted from the working folder.
% The FOR loops will not be resumed, because Matlab does not permit
% updating the loop index from within the loop. Thus, the call to the
% manager should be conducted outside FOR loops; or alternativelly 
% employ WHILE loops. 
%
% SYNTAX:
%   clear ManageLongSimulation, at the beginning of the calling function, 
%                               to delete the persistent variable 'firstCall'.
%   ManageLongSimulation,       just after the beginning of a long loop where 
%                               the state preservation is desired. Ideally, the
%                               most inner loop should be endowed with the
%                               call.
%
% EXAMPLE:
%   In the following example, the manager will create the variable
%   'resumeMyFun.mat' every time it is called, storing all the internal
%   workspace variables. When the function MyFun is broken (CTRL-C) and 
%   restarted again, the first call to the manager will restore the last saved 
%   internal workspace.
%
%         function MyFun(varargin)
%         clear ManageLongSimulation
%         % hereafter, some things to do
%         % ...
%         while condition
%             ManageLongSimulation
%             % hereafter, lots of things to do
%             % ...
%         end
%
%
%
% Other m-files required: none
% Subfunctions: none
% MAT-files required: none
%
%
% Author:       Guzmn Daz
% email:        guzman.at.uniovi.es
% Matlab ver.:  2012a
% Date:         12-Mar-2013


%% Initialize
% Define the flag that will inform whether to resume or to save
persistent firstCall

% Name of the calling function
stackData = dbstack(1);                         % get stack data from caller function
resumeName = ['resume', stackData.name];        % obtain the name of the caller function
assignin('caller', 'resumeName', resumeName)    % make the name visible in the caller


%% Load/save resume data 
if isempty(firstCall)                           % check whether it is the first time
    if exist([resumeName, '.mat'], 'file')
        evalin('caller', 'load(resumeName)')    % this time, loads resume if available
        fprintf('Resume loaded \n');
    else
        fprintf('No resume data available \n');
    end
    firstCall = false;                          % next time, save data
else
    evalin('caller', 'save(resumeName)')        % saves internal workspace
end

Contact us