Defining Objective Function in Genetic Algorithm

Trying to optimize the following function using Genetic Algorithm (A,B are arrays of length 10000 attached)
y= [x] * [A-B]
such that
  • x is binary
  • -B'*x <= blimit - sum(B)
load ('A_B_Arrays');
nvars = numel(A);
blimit = 1165.208;
Aineq = -B';
bineq = blimit - sum(B);
Aeq = [];
beq = [];
lb = zeros(1,N);
ub = ones(1,N);
nonlcon=[];
intcon = 1:nvars;
tic
x = ga(fun,nvars,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,IntCon)
toc
MATLAB Documentation says that objective function should accept "a row vector of length nvars and return a scalar value". The length of vector x, in this case, depends on the length of [A-B]. How do I define the objective function with so many input variables?
function y = fun(x(1),x(2),x(3),...,x(nvars))
y=[x(1) x(2) ... x(nvars)] * [A-B];
end

More Answers (1)

Neeraj - your fitness function would be simply
function y = fun(x)
y = x * [A-B];
end
where x is an array of variables being optimized.

1 Comment

Okay, I understand. But the following error pops up, "Failure in user-supplied fitness function evaluation. GA cannot continue". Rechecked the definitions of input arguments but couldn't trace the issue.
load ('A_B_Arrays');
M=A-B;
nvars = numel(A);
blimit = 1165.208;
fun=@optfun;
Aineq = -B';
bineq = blimit - sum(B);
Aeq = [];
beq = [];
lb = zeros(nvars,1);
ub = ones(nvars,1);
nonlcon=[];
IntCon = 1:nvars;
tic
x = ga(fun,nvars,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,IntCon)
toc
function y = optfun(x)
y = x * M;
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!