Assigning a script to a variable

Hello,
I have a program that uses input data generated by a script file. There are several different script files that I can use. I want to assign the script to a variable so I can call it in my program.
A simplified version of what I have right now is:
system=input('Which data set is being used?\n');
if system==1
DTSsys_Ieee_rvc;
elseif system==2
Pf4busHw_Ieeerv;
end
This works, but I end up calling these scripts several times in my program, and I have more than 2 systems. So I have these long if-else statements several times in my program whenever I want to reinitialize my input data. Is it possible to shorten my code with something like:
system=input('Which data set is being used?\n');
if system==1
inputData=DTSsys_Ieee_rvc;
elseif system==2
inputData=Pf4busHw_Ieeerv;
end
So that I can just call 'inputData' whenever I need to reinitialize my inputData?
Thanks for the help

 采纳的回答

This actually appears to be a reasonable use of eval. Generally it is to be avoided but here your complexity is well controlled to a single level.
doc eval

4 个评论

[David commented]
I tried that out in a little test script.
system=1;
if system==1
inputData=eval(DTSsys_Ieee_rvc);
elseif system==2
inputData=eval(Pf4busHw_Ieeerv);
end
Attempt to execute SCRIPT DTSsys_Ieee_rvc as a function:
Error in tester (line 108)
inputData=eval(DTSsys_Ieee_rvc);
It appears eval doesn't work for evaluating a script.
My mistake, your answer was correct. I didn't fully understand the syntax. It worked with:
system=2;
if system==1
inputData='DTSsys_Ieee_rvc';
elseif system==2
inputData='Pf4busHw_Ieeerv';
end
eval(inputData);
David, if you want to add a comment, click on [comment on this answer]
Can eliminate the selection if to be more nearly like what you're looking for methinks...
slist={'DTSsys_Ieee_rvc';'Pf4busHw_Ieeerv'}; % populate a list of scripts
[func,ok]=listdlg('PromptString','Select script to run:', ...
'liststring',slist, ...
'selectionmode','single',
'listsize',[160 20*length(slist)]);
if ok, eval(slist{func}), end
Salt to suit...

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Get Started with MATLAB 的更多信息

提问:

2013-11-10

评论:

dpb
2013-11-10

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by