我有一个优化问题,其中有一个简单的objectif函数和一组约束,如下所示:
% set some variables for example
params.nbMaxLong = 2;
params.nbMaxShort = 2;
s = [-0.2,0.1,0.5,-0.4,0.2,-0.1];
n = numel(s);
% Objectif function
fun = @(x) -(s * x);
% Initial condition
x0 = ones(n,1)./n .* sign(s)';
% Linear equality constraints
temp = ones(0,n);
temp(s >= 0) = -1;
temp(s < 0) = 1;
% (b) and (c)
% Ax <= b
A = diag(temp);
b = zeros(n,1);
% Linear Inequality constraints
Aeq = [];
beq = [];
% bound
lb = -ones(n,1)/n;
ub = ones(n,1)/n;
% Non-Linar Constraints
function [c,ceq] = maxBasketConst(x,params)
% Non-linear equality constraints
ceq = [sum(x > 0) - params.nbMaxLong;
sum(x <0) - params.nbMaxShort];
% Non-linear inequality constraints
c = [];
end
nonlcon = @(x)maxBasketConst(x,params);
% Optimization
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon);
我的问题来自非线性约束,我试图在解决方案中对正值和负值的数量设置约束。基本上,我希望该解决方案包含正2个正值和2个负值,其余应为零。
很明显,我设置约束的方式没有给出预期的结果。关于如何定义这种约束的任何建议。它不必是非线性的。