Matlab - Power operator in objective function
Awaiting user inputHi community,
For this simple example problem, I'm getting an error that says "Undefined operator '^' for input arguments of type 'optim.problemdef.OptimizationExpression'."
prob = optimproblem('ObjectiveSense','maximize');
x = optimvar('x');
y = optimvar('y', 'LowerBound', 1);
z = optimvar('z', 'LowerBound', 0);
prob.Objective = test_fun([x y z]);
prob.Constraints.cons1 = x + 2* y + 3 * z <= 4;
prob.Constraints.cons2 = x + y >= 1;
options = optimoptions('linprog');
sol = solve(prob, options);
function sol = test_fun(b)
x = b(1);
y = b(2);
z = b(3);
sol = x + y + 2 ^ z;
end
I'm using the Matlab's interface for Gurobi. How can I have design variable as an exponent in my objective function?
Thanks!
-
Hi Livia,
To model the \(2^z\) function, you have to use Gurobi general constraint interface. In your particular case, you have to use the genconexpa struct array. There is no example showing exactly this function but the gc_pwl_func.m example shows the usage of the genconexp struct array, which works analogously.
Best regards,
Jaromił0 -
Hi Jaromil,
Thanks for your reply! I'm trying to adapt my problem to the example you sent. But in my case, the objective function is not a linear combination of the design variables, it is a rather complex nonlinear function.
In the example you sent me (simplified below), how can I change m.obj to be a function that has the design variables as arguments?
% Four nonneg. variables x, y, u, v, one linear constraint u + 4*v <= 9
m.varnames = {'x', 'y', 'u', 'v'};
m.lb = zeros(4, 1);
m.ub = +inf(4, 1);
m.A = sparse([0, 0, 1, 4]);
m.rhs = 9;
% Objective
m.modelsense = 'max';
m.obj = [2; 1; 0; 0];
% Set u \approx exp(x)
m.genconexp.xvar = 1;
m.genconexp.yvar = 3;
m.genconexp.name = 'gcf1';
% Set v \approx sqrt(y) = y^0.5
m.genconpow.xvar = 2;
m.genconpow.yvar = 4;
m.genconpow.a = 0.5;
m.genconpow.name = 'gcf2';
% Parameters for discretization: use equal piece length with length = 1e-3
params.FuncPieces = 1;
params.FuncPieceLength = 1e-3;
% Solve and print solution
result = gurobi(m, params);
printsol(result.objval, result.x(1), result.x(2), result.x(3), result.x(4));Thanks again!
0 -
Hi Livia,
I am not sure whether I understand your question. Your general constraints define the constraints \(u = \exp(x)\) and \(v = \sqrt{y}\). You can now use variables \(u\) and \(v\) to, e.g., add \(\exp(x)\) and \(\sqrt{y}\) in the objective by
m.obj = [0; 0; 1; 1];
Does this answer your question?
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
3 comments