www.gusucode.com > globaloptim 案例源码程序 matlab代码 > globaloptim/CustomOutputFunctionForGeneticAlgorithmExample.m

    %% Custom Output Function for Genetic Algorithm
% This example shows the use of a custom output function in the genetic
% algorithm solver |ga|. The custom output function performs the following
% tasks:
%
% * Plot the range of the first two components of the population as a
% rectangle. The left and lower sides of the rectangle are at the minima of
% |x(1)| and |x(2)| respectively, and the right and upper sides are at the
% respective maxima.
% * Halt the iterations when the best function value drops below |0.1| (the
% minimum value of the objective function is |0|).
% * Record the entire population in a variable named |gapopulationhistory|
% in your MATLAB(R) workspace every 10 generations.
% * Modify the initial crossover fraction to the custom value |0.2|, and
% then update it back to the default |0.8| after 25 generations. The
% initial setting of |0.2| causes the first several iterations to search
% primarily at random via mutation. The later setting of |0.8| causes the
% following iterations to search primarily via combinations of existing
% population members.
%% Objective Function
% The objective function is for four-dimensional |x| whose first two
% components are integer-valued.
%
% <include>gaintobj.m</include>
%
%% Output Function
% The custom output function sets up the plot during initialization, and
% maintains the plot during iterations. The output function also pauses the
% iterations for |0.1s| so you can see the plot as it develops.
%
% <include>gaoutfun.m</include>
%
%% Problem Setup and Solution
% Set the lower and upper bounds.
lb = [1 1 -30 -30];
ub = [20 20 70 70];
%%
% Set the integer variables and number of variables.
IntCon = [1 2];
nvar = 4;
%%
% Set options to call the custom output function, and to initially have
% little crossover.
options = optimoptions('ga','OutputFcn',@gaoutfun,'CrossoverFraction',0.2);
%%
% For reproducibility, set the random number generator.
rng(10)
%%
% Set the objective function and call the solver.
fun = @gaintobj;
[x,fval] = ga(fun,nvar,[],[],[],[],lb,ub,[],IntCon,options)
%%
% The output function halted the solver.
%
% View the size of the recorded history.
disp(size(gapopulationhistory))
%%
% There are seven records of the 40-by-4 population matrix (40 individuals,
% each a 4-element row vector).