[fmincon] How should I write an objective function which links to other functions rather than directly using "x"

1 view (last 30 days)
Hello,
I have a problem about writing an objective function. How should I write the objective function that links to other functions of which x is expressed in order to pass the decision variable x to fmincon ? Below is an example
%Objective File
function TotCost=objfuntion(x)
global CapCost FuCost Demand % CapCost FuCost and Demand will be reused in constraint file
x0=100*ones(12,1);
x=x0;
%MW and CF are real decision variables
MW=reshape(x(1:6,1),[3,2]);%convert a part of vector x to the matrix of variable "MW" dimension 3x2
CF=reshape(x(7:12,1),[3,2]);%convert the rest of vector x to the matrix of variable "CF" dimension 3x2
U=[2 3 4];
V=[3.5; 2.5; 1.5];
W=repmat(V,1,2);
S=[1 3 5];
CapCost=sum(U*(MW.^W));
FuCost=sum(S*(MW.*CF/100));
Demand=sum(sum(MW.*CF/100,1));
TotCost = CapCost+FuCost; %objective function
lb=zeros(12,1);
MWMax = [200; 300; 400];
CFMax = [85; 75; 45];
ub=[MWMax; MWMax; CFMax; CFMax];
options=optimset('MaxFunEvals',Inf,'MaxIter',5000,'Algorithm','interior-point');
[x,fval,exitflag,output]=fmincon(@objfuntion,x0,[],[],[],[],lb,ub,@confuntion,options)
%Constraint File
function [c,ceq]=confuntion(x)
global CapCost FuCost Demand
c=[500-Demand; CapCost-20000000; FuCost-1500];
ceq=[];
TotCost is the objective function which I want to minimize.
By coding like this, I got an error saying "Failure in initial user-supplied objective function evaluation. FMINCON cannot continue"
Any comment is appreciated !!
Thank you

Accepted Answer

Alan Weiss
Alan Weiss on 17 Feb 2015
x should represent your decision variables. If you have a 3-by-2 matrix of values MW, and a 3-by-2 set of values CF, then these values should all be in x. Your initial few lines of code implement this in a way that overwrites the passed value of x:
function TotCost=objfuntion(x)
global CapCost FuCost Demand % CapCost FuCost and Demand will be reused in constraint file
x0=100*ones(12,1);
x=x0;
The line x = x0 overwrites x and ensures that your optimization fails.
Instead of using global variables, I suggest that you use a nested function to keep variables in scope without polluting your code or workspace with globals.
And you forgot to include the global declaration in your nonlinear constraint file, reinforcing the point that globals are usually not a good idea.
Alan Weiss
MATLAB mathematical toolbox documentation
  1 Comment
Siwanon Thampibul
Siwanon Thampibul on 18 Feb 2015
Thank you for you suggestion Alan. It seems I have to rewrite most of the equations again to support decision vector x rather than declaring the matrix MW and CF.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!