www.gusucode.com > globaloptim 案例源码程序 matlab代码 > globaloptim/CustomPlotFunctionAndLinearConstraintsInGaExample.m
%% Custom Plot Function and Linear Constraints in |ga| % This example shows how |@gacreationlinearfeasible|, the default creation % function for linearly constrained problems, creates a population for % |ga|. The population is well-dispersed, and is biased to lie on the % constraint boundaries. The example uses a custom plot function. %% Fitness Function % The fitness function is |lincontest6|, included with your software. This % is a quadratic function of two variables: % % $$f(x) = \frac{x_1^2}{2} + x_2^2 - x_1 x_2 - 2x_1 - 6x_2.$$ % %% Custom Plot Function % Save the following code to a file on your MATLAB(R) path named % |gaplotshowpopulation2|. % % <include>gaplotshowpopulation2.m</include> % % The custom plot function plots the lines representing the linear % inequalities and bound constraints, plots level curves of the fitness % function, and plots the population as it evolves. This plot function % expects to have not only the usual inputs |(options,state,flag)|, but % also a function handle to the fitness function, |@lincontest6| in this % example. To generate level curves, the custom plot function needs the % fitness function. %% Problem Constraints % Include bounds and linear constraints. A = [1,1;-1,2;2,1]; b = [2;2;3]; lb = zeros(2,1); %% Options to Include Plot Function % Set options to include the plot function when |ga| runs. options = optimoptions('ga','PlotFcns',... {{@gaplotshowpopulation2,@lincontest6}}); %% Run Problem and Observe Population % The initial population, in the first plot, has many members on the linear % constraint boundaries. The population is reasonably well-dispersed. rng default % for reproducibility [x,fval] = ga(@lincontest6,2,A,b,[],[],lb,[],[],options); %% % |ga| converges quickly to a single point, the solution.