Constraining the Genetic Algorithm in MATLAB so that the solutions are all between 2 and 20, and are integers

StackOverflow https://stackoverflow.com/questions/22546412

  •  18-06-2023
  •  | 
  •  

Question

How can I constrain the Genetic Algorithm in MATLAB so that the solutions are all between 2 and 20, and are integers?

I am using the function:

x = ga(@myFitnessfcn,nvars,A,b,[],[],LB,UB,nonlcon,IntCon)

Where myFitnessfcn takes two inputs and returns a scalar output.

However myFitnessfcn can only take integer inputs that are between 2 and 20.

How would I implement this?

My best attempt so far is:

A = [1, 1; -1, -1]
b = [20; -2]
IntCon = [1, 2]
LB = 2
UB = 20
nonlcon = []

But this just tried to evaluate myFitnessfcn with [4, 1872]

Here is the MATLAB page on ga

Was it helpful?

Solution

see InitialPopulation and PopInitRange in options of gaoptimset. you can initialize a sequence of integers in the range 2 to 20 as your initial population.

then you might use IntCon.

OR

as a first statement in your myFitnessfcn

model=round(model);
if model > 20 || model < 2
   fitness=1e20;
else
   % evaluate the original fitness function
end

this way model parameters fed to your fitness function are always integers. and since any model with values less than 2 or more than 20 will be assigned really bad value of fitness (1e20 for example), this is essentially what Simon said, such models will be automatically removed from the population after 2-3 generations.

OTHER TIPS

I am sorry I don't know Matlab, but in general in a GA, you can set a low or 0 fitness when the solution is outside that range, and some higher number when it is within the range.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top