www.gusucode.com > globaloptim 案例源码程序 matlab代码 > globaloptim/gaplotshowpopulation2.m
function state = gaplotshowpopulation2(~,state,flag,fcn) %gaplotshowpopulation2 Plots the population and linear constraints in 2-d. % STATE = gaplotshowpopulation2(OPTIONS,STATE,FLAG) plots the population % in two dimensions. % % Example: % fun = @lincontest6; % options = gaoptimset('PlotFcn',{{@gaplotshowpopulation2,fun}}); % [x,fval,exitflag] = ga(fun,2,A,b,[],[],lb,[],[],options); % This plot function works in 2-d only if size(state.Population,2) > 2 return; end if nargin < 4 fcn = []; end % Dimensions to plot dimensionsToPlot = [1 2]; switch flag % Plot initialization case 'init' pop = state.Population(:,dimensionsToPlot); plotHandle = plot(pop(:,1),pop(:,2),'*'); set(plotHandle,'Tag','gaplotshowpopulation2') title('Population plot in two dimension','interp','none') xlabelStr = sprintf('%s %s','Variable ', num2str(dimensionsToPlot(1))); ylabelStr = sprintf('%s %s','Variable ', num2str(dimensionsToPlot(2))); xlabel(xlabelStr,'interp','none'); ylabel(ylabelStr,'interp','none'); hold on; % plot the inequalities plot([0 1.5],[2 0.5],'m-.') % x1 + x2 <= 2 plot([0 1.5],[1 3.5/2],'m-.'); % -x1 + 2*x2 <= 2 plot([0 1.5],[3 0],'m-.'); % 2*x1 + x2 <= 3 % plot lower bounds plot([0 0], [0 2],'m-.'); % lb = [ 0 0]; plot([0 1.5], [0 0],'m-.'); % lb = [ 0 0]; set(gca,'xlim',[-0.7,2.2]) set(gca,'ylim',[-0.7,2.7]) axx = gcf; % Contour plot the objective function if ~isempty(fcn) range = [-0.5,2;-0.5,2]; pts = 100; span = diff(range')/(pts - 1); x = range(1,1): span(1) : range(1,2); y = range(2,1): span(2) : range(2,2); pop = zeros(pts * pts,2); values = zeros(pts,1); k = 1; for i = 1:pts for j = 1:pts pop(k,:) = [x(i),y(j)]; values(k) = fcn(pop(k,:)); k = k + 1; end end values = reshape(values,pts,pts); contour(x,y,values); colorbar end % Show the initial population ax = gca; fig = figure; copyobj(ax,fig);colorbar % Pause for three seconds to view the initial plot, then resume figure(axx) pause(3); case 'iter' pop = state.Population(:,dimensionsToPlot); plotHandle = findobj(get(gca,'Children'),'Tag','gaplotshowpopulation2'); set(plotHandle,'Xdata',pop(:,1),'Ydata',pop(:,2)); end