Code Generation: What's the Best Practice?

조회 수: 1(최근 30일)
sjhstone 2020년 9월 5일
편집: sjhstone 2020년 9월 5일
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?


Mario Malic
Mario Malic 2020년 9월 5일
편집: Mario Malic 2020년 9월 5일
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
sjhstone 2020년 9월 5일
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.

댓글을 달려면 로그인하십시오.




Community Treasure Hunt

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

Start Hunting!

Translated by