Dear all,
I am currently working in a project for which I would like to create an equivalent of function handles for scripts. To be more precise: I have a code at the beginning of which the user sets a few options before an algorithm with a large number of repetitions runs. Depending on the options chosen at the beginning of the code, one script will be selected among several (say for instance among script1 and script2), and this script will then be run at every repetition of the algorithm.
So of course one option is to use an "if" statement within the algorithm: at every iteration the "if" statement selects the desired script and executes it. But I am afraid that the "if" statement repeated at every iteration might slow down the code (I may have a few millions of repetitions). Ideally, I would like to create some command that assign a handle to the correct script at the beginning of the code, before the algorithm starts. For instance, if the options select script 1, assign myscript=@script1. If conversely the options select script2, then assign myscript=@script2. In both cases, the algorithm only has to call for myscript, without further if statement.
I tried to use the handle @ on my scripts but it fails: handles defined this way seem to be only calling for functions. It seems also that replacing my scripts with functions to use regular handles is not an option: the scripts (turned into functions) would call for different arguments, and different numbers of arguments. So I would again have to use "if" statements at each iteration to vary the list of arguments. I cannot either use functions without inputs nor outputs since the commands implemented by the scripts have to update variables in the global space.
So at the moment I am stuck. I did not imagine that I would struggle with something as simple as assigning a handle to a script, but it seems that Matlab really can't do that. Anyone has a solution for this? Or is the "if" statement the best solution in the end?
Thanks a lot
edit: simple worked example
% script1.m
x=x+y*z; % script2.m
x=x-w; % code.m
x=1; % options: choice of script (1 for script1, 2 for script2)
choice=1; % variables generated by the choice
if choice==1 y=1; z=2; elseif choice==2 w=0.5; end % algorithm
for i=1:10000000 % if statement
if choice==1 script1 elseif choice==2 script2 end end
Ideally replace with:
% script1.m x=x+y*z; % script2.m x=x-w; % code.m x=1; % options: choice of script (1 for script1, 2 for script2) choice=1; % variables generated by the choice if choice==1 y=1; z=2; myscript=@script1 elseif choice==2 w=0.5; myscript=@script2 end % algorithm for i=1:10000000 myscript end
Best Answer