Code Generation: What's the Best Practice?

5 views (last 30 days)
sjhstone on 5 Sep 2020
Edited: sjhstone on 5 Sep 2020
I'm writing a code for comparing multiple numerical optimization algorithms using multiple combination of parameter choices.
The traditional way is to insert tons of "if ... else ..." or "switch ... case ..." statements inside the iterations, but I want my code to generate a new standalone function for each combination of parameter & options.
The traditional way may look like this
option.secondOrder = 'BFGS';
option.tolerance = 1e-8;
result = optimization_algorithm(problem, option);
function r = optimization_algorithm(prob, opt)
% ...
switch opt.secondOrder
case 'ExactHessian'
% ...
case 'BFGS'
% ...
% ...
I want to implement something like this
codeType = 'MATLAB'; % {'MATLAB', 'MEX C', 'Embedded C'}
fnfilename = optimization_algorithm.generate_function(option);
result = feval(fnfilename, problem);
For me, I can think of ways of doing this:
  • construct a cell array containing all lines of codes, and using frprintf to generate a code file (MPT Toolbox use this method)
  • have template code files containing part of code pieces, use string template to replace some of the variable names.
These methods are feasible, however, I want to know if there is a more systematic/organized way of doing this? The thing I want may be keyworded as "string template" or something?
I had some experiences in web development, and I am looking for something PHP-like in MATLAB ecosystem.
Is there anything like this?

Answers (1)

Mario Malic
Mario Malic on 5 Sep 2020
Edited: Mario Malic on 5 Sep 2020
You can use
options = optimoptions('fmincon') % example
this will give you the options used by fmincon algorithm with their default values.
Also, there is
options = optimset
this will give you a structure with empty values.
You can set options by typing in
options.CheckGradients = 0; % example
  1 Comment
sjhstone on 5 Sep 2020
Ah, thank you for your reply, but I'm not using any existing code...
I'm writing my own "fmincon", and I want to know how other people are designing the code structure when facing similar problem.

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!

Translated by