Alternative to using EVAL
이전 댓글 표시
Hi All,
I need to call a function whose name is decided dynamically at runtime. Is there an alternative to using the eval function?
My requirement is this: I have a Matlab application with a non-linear optimisation model as the core solver for this application. I need the user to have the option to "plug and play" different models without needing to rewrite the code.
Currently I have solved this requirement by having a string array containing the name of the model function (e.g. LoadModelPkg = 'myModel'). The user can change this using a dialog box.
My application then calls this function using the following lines of code:
LoadModelPkg = 'myModel' % name of the function to call.
LoadModelPkgCall = ['[jfit, estParams, graphData] = ', LoadModelPkg, '(tr, Pr, Qr, Avr, powerfactor, WarmStartIdx, graphDataStruct);']; % create the function call
eval(LoadModelPkgCall)
This works, but the Matlab debugger warns that the variables in the above LoadModelPkgCall string are unused. Is there an alternative to using the eval function?
Thanks for the help.
Andrew
채택된 답변
추가 답변 (1개)
Azzi Abdelmalek
2013년 3월 3일
If your goal is to use different functions
f=@myModel
[jfit, estParams, graphData] = f(tr, Pr, Qr, Avr, powerfactor, WarmStartIdx, graphDataStruct);
댓글 수: 1
Azzi Abdelmalek
2013년 3월 4일
편집: Azzi Abdelmalek
2013년 3월 4일
You can create a function where you will past a handle function, You will need also to use str2func as suggested by Cedric.
Example
function y=fcn(f,data,choice)
% y and data are cell array
% f is you function
if choice==1
[a,b]=f(data{1},data{2})
y={a,b}
elseif choice==2
y=f(data{1}
else
[a,b,c}=f(data{1},data{2},data{3})
y={a,b,c}
end
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!