Saving function variables without evil eval
显示 更早的评论
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, ....)
.
.
.
%Temporary store results to workspace
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, ....)
% load temporary stored results to m-file
if nargin == 1
insurance = var1;
names = fieldnames(insurance);
for ii = 1:length(names)
feval(@()assignin('caller',names{ii},insurance.(names{ii})))
end
end
回答(3 个)
dpb
2016-11-29
Just save then load will do all automagically...see
doc save % for details
2 个评论
Remco1988
2016-11-29
Why? What do you need eval for if you just save and restore the variables as they were? Don't see the issue, sorry...
function YourRescueFunction(insurance)
load insurance
results=TheOriginalFunction(variablesFromInsuranceReloaded);
Actually, if you were to wrap the above around the initial and make it a nested function within the recovery routine, then everything in it is also local within the original and you don't even have an issue of workspace at all it would seem...
Jan
2016-11-29
1 个投票
Use a function and not scripts, which pollute the base workspace with variables. Then you can use save to store all current variables, but not any other stuff of the base workspace. But even if you use save in scripts: There is no need for eval at all.
Alexandra Harkai
2016-11-29
编辑:Alexandra Harkai
2016-11-29
How about having all these state variables in a struct in the first place? Then you can save them to a mat file, for example:
var_struct.var1 = <some_value>;
var_struct.var2 = <some_other_value>;
...
fname = [datestr(now,'yymmdd_HHMMSS'), '.mat'];
save(fname, '-struct', 'var_struct', '-v7.3');
1 个评论
类别
在 帮助中心 和 File Exchange 中查找有关 Variables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!