Alternative to using EVAL
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (1)
Azzi Abdelmalek
el 3 de Mzo. de 2013
If your goal is to use different functions
f=@myModel
[jfit, estParams, graphData] = f(tr, Pr, Qr, Avr, powerfactor, WarmStartIdx, graphDataStruct);
1 comentario
Azzi Abdelmalek
el 4 de Mzo. de 2013
Editada: Azzi Abdelmalek
el 4 de Mzo. de 2013
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
Categorías
Más información sobre Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!