MATLAB: How to insert a specific individual into i-th generation in GA

genetic algorithminsert individualoutput function

I'm trying to insert a specific individual (insIndividual) into the 25th generation during the GA evolution. I've tried using the following output function:
function [state,options,optchanged] = Myoutfun(options,state,flag, ...
insIndividual, insFit)
optchanged = false;
switch flag
case 'init'
case 'iter'
if state.Generation == 25
% INSERT AN ARBITRARY INDIVIDUAL
if ~isempty(insIndividual)
n = length(state.Score);
% Avoid best fitness deletion
[~, idx] = min( state.Score );
aux = [1:idx-1, idx+1:n];
idx = randi(n-1);
state.Population(aux(idx),:) = insIndividual;
state.Score(aux(idx)) = insFit;
state.Score = sort(state.Score);
end
end
case 'done'
end
where insFit is the calculated fitness value for the inserted individual.
However, it seems that the algorithm has already chosen the elite individuals and selected the mating pool for the next generation (26 in this example), because my inserted individual, which was supposed to be the best one, does not make its way into generation 26.
So, how can I insert an individual and make sure that it'll be selected as an elite individual for the next generation?

Best Answer

  • I found the problem guys. In the last line I was sorting the scores, but the population order was remaining the same. So, the scores wouldn't correspond to the correct individual. You just have to add this:
    [state.Score, idx2] = sort(state.Score);
    state.Population(:,:) = state.Population(idx2,:);