I'm trying to minimize afunction in matlab like this:
function [c, ceq] = const_slot( x )
c = [];
% Nonlinear equality constraints
ceq = [sum(x)-1];
end
[x,fval] = fmincon(@func_slot, x0,[],[],[],[],lb,ub,@const_slot,options)
But, I need to value fval
that was within the specified value, or the positive. How can I do that?
As I understand your question you want to put constraints on your function @func_slot
(which I assume is non-linear).
In the Matlab help for fmincon we find:
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)
Non-linear constraints can be set using the nonlcon
parameter (in the question you use @const_slot
). These constraints should be defined as:
function [c,ceq] = mycon(x)
c = ... % # Compute nonlinear inequalities at x.
ceq = ... % # Compute nonlinear equalities at x.
So for example, when you want your function @func_slot
to be greater than zero, you can define the inequality constraint c
in @const_slot
as the negative of your function.
Edit
If I understand you correctly, you need the function value to be greater than zero but less than a specified limit. In that case you could try this.
function [c, ceq] = const_slot( x )
% # Nonlinear inequality constraints
upperLimit = 10;
c = [-func_slot(x);
-upperLimit + func_slot(x)];
% # Nonlinear equality constraints
ceq = [sum(x)-1];
end