Search code examples
matlabgenetic-algorithm

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


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


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.