Note: I am aware that using eval is usually not a good practice. However for me it is very difficult to understand when it can be used and when not.
Question: So my question is, is this a proper usage? and if not how should I do it differently?
Background: I have a function that occasionally crashes (not going in to detail in this question) As it is run after 30 minutes of simulation I want to avoid re-running the simulation. So I though of a checkpoint at the start of the function in which all variables are saved, in case it fails.
Code: I start of saving all variables to base workspace (could be a .mat file if thats prefered)
function test(var1, var2, var3, var4, ...
.
.
.
variables = who;
for ii = 1:length(variables);
insurance.(variables{ii}) = eval(variables{ii});
end
assignin('base','insurance',insurance)
For convenience I saved all variables in to a single struct, but even if I saved them seperatly, I cannot think of a way to avoid eval in this situation.
Code part 2: The user now can (try) to re-run by calling the function "test(insurance)", which will restore the saved variables
function test(var1, var2, var3, var4, ...
if nargin == 1
insurance = var1;
names = fieldnames(insurance);
for ii = 1:length(names)
feval(@()assignin('caller',names{ii},insurance.(names{ii})))
end
end