# Genetic Algorithm 'bitstring' not accepting constrains

2 Ansichten (letzte 30 Tage)
Mohamed am 7 Feb. 2023
Kommentiert: Mohamed am 7 Feb. 2023
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 ?
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

Stephan am 7 Feb. 2023
Bearbeitet: Stephan am 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 KommentarKeine anzeigenKeine ausblenden
Mohamed am 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 ?

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Genetic Algorithm in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!