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!