How to convert string to optimization variable?
13 次查看(过去 30 天)
显示 更早的评论
I'm doing constrained optimization problems using the "problem based optimization workflow". I'm using a set of equations which have been constructed through string concatenation as the optimizaton variables. I now need to convert these strings to optimvars. It's simple to convert these strings to symbolic variables (just use str2sym), but I can't find anything anologous for optimvars. Any ideas on how to do this?
回答(2 个)
Matt J
2023-9-15
编辑:Matt J
2023-9-15
I ended up using "eval" function to solve this issue, but I know "eval" is not recommended.
If you have many optimvars, then piecing your optimization expressions together through string concatenation is probably already a bad idea, even without eval. If you have a small number of optimvars, then avoiding eval probably doesn't gain you very much.
In any case, one way to avoid eval is to use str2func, e.g.
str='z.^2+z'; %string representing optimization expression
f=str2func("@(z)"+str);
x=optimvar('x');
expr=f(x)
0 个评论
Nihal
2023-9-15
Hi Ephraim,
I understand that you would like to create ‘optimvars' from string equations without using eval function.
There is an alternative method to create 'optimvar' objects from strings without using 'eval’. You can use a dynamic struct to store the optimization variables. Here's an example:
% Example strings representing optimization variables
varString1 = 'x';
varString2 = 'y';
% Create a struct to store the optimization variables
optimVars = struct();
% Create optimvar objects and store them in the struct
optimVars.(varString1) = optimvar(varString1, 1);
optimVars.(varString2) = optimvar(varString2, 1);
% Access the optimvar objects
disp(optimVars.x);
disp(optimVars.y);
In this code, a struct named ‘optimVars’ is created to store the optimization variables. The ‘(varString)' syntax is used to dynamically create fields in the struct using the strings as field names.
The 'optimvar' function is called to create the 'optimvar’ objects, and they are stored in the struct using dynamic field names.
You can then access and use the ‘optimvar' objects by referencing the fields of the struct.
Using a dynamic struct to store the optimization variables provides a safer alternative to ‘eval' since it avoids executing arbitrary code. It also allows for more flexibility in managing and accessing the optimization variables.
I suggest you refer the following documentation to know more about ‘optimvars' from MATLAB documentation: https://www.mathworks.com/help/optim/ug/problem-based-workflow.html
I hope this alternative method helps you create ‘optimvar' objects from strings in the problem-based optimization workflow. Let me know if you have any further questions!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Programming and Mixed-Integer Linear Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!