MATLAB: GA: How to get a full population set for one Generation

Global Optimization Toolbox

Currently, I have a genetic algorithm defined by the following lines of code:
>> opts = optimoptions(@ga,'PopulationSize', PopulationSize,...
  'MaxGenerations', MaxGenerations,'EliteCount', 1,...
  'OutputFcns', @my_view,'PlotFcn', @gaplotbestindiv);
>> [x, fval,output] = ga(@Costfunction,9,[], [], [], [],...
  lb, ub, @Constraints, [1:5], opts)
In my ConstraintFunction, I want to run an external simulation. For better performance of the external simulation, it would be nice to get the full set of one generation first. Therefore, I would like to obtain a full population set for the first generation of my genetic algorithm to be used in an external simulation. 

Best Answer

1) One way this could be achieved is by defining an output function as the 'OutputFcn' property for the genetic algorithm which would return the population for each iteration of the algorithm. More information on the 'OutputFcn' property and state structure inputs to the output function can be found in the documentation links below.
2) Another way this could be achieved is by running the genetic algorithm with the 'MaxGenerations' property set to 1. By running the genetic algorithm for one generation by setting 'MaxGenerations' to 1, you will be able to obtain a population set for the first generation via the fifth output argument of the genetic algorithm. The output arguments would be [x, fval, ~, output, population].
From here, the population set can seed another call to the genetic algorithm via the 'InitialPopulationMatrix' option and can be passed to your constraint function as a parameter. Your list of options for the second genetic algorithm call would look something like this:
>> opts = optimoptions(@ga, 'PopulationSize', PopulationSize,...
  'MaxGenerations', MaxGenerations,'EliteCount', 1,...
  'OutputFcns', @my_view,'PlotFcn', @gaplotbestindiv,...
  'InitialPopulationMatrix', population);
If you were to utilize only the 'OutputFcn' option, you would perform the action on each generation. The above solution will ensure that the only additional processing is a result of the first population set. One thing to note is that the initial population generated by the genetic algorithm is random.