Clear Filters
Clear Filters

Genetic Algorithm 'bitstring' not accepting constrains

4 views (last 30 days)
i use the following code to generate binary values using genetic algorith:
options = optimoptions(@ga, 'PopulationType', 'bitstring', 'Generations', 100, 'Display', 'iter', 'StallGenLimit', 10);
[x, fval, exitflag, output] = ga(SAIDI, n1, [], [], [], [], lb, ub, @nonlcon, options);
but i get a waring that : 'bitstring' ignore all constrain,
i want only 20 values of x to be 1 and the rest is 0 , i tried this constrain but it failed
function [c, ceq] = nonlcon(x)
c = [];
ceq = sum(x) - 20;
end
is there is way to achive my constrain without changing my fitness function ?

Answers (1)

Stephan
Stephan on 7 Feb 2023
Edited: Stephan on 7 Feb 2023
Considering this hint in the documentation, you should use the integer condition for the corresponding variables and set the limits for these variables with lb=[0...0] and ub=[1...1]. Then you have avoided the problem.
  1 Comment
Mohamed
Mohamed on 7 Feb 2023
I've just used a different techique , as follow :
lb = zeros(1,nvars);
ub = ones(1,nvars);
% Define anonymous function for constraint
constraint = @(x) constraintFunction(x);
% Call the ga function with the constraint
options = optimoptions(@ga, 'PopulationType', 'doubleVector', 'Generations', 100, 'Display', 'iter', 'StallGenLimit', 10);
[x, fval, exitflag, output] = ga(FitnessFunction, n1, [], [], [], [], lb, ub, @nonlcon, options);
and this is my constrain function :
function [c, ceq] = nonlcon(x)
c = [];
count = sum(x > 0.5);
ceq = count - 20;
end
but then i only get 2 genrations and then optimaization is terminated , so is that normal , or the constrain function need to be modified ?

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!