%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MATLAB Code for %
% %
% Non-dominated Sorting Genetic Algorithm II (NSGA-II) %
% Version 1.0 - April 2010 %
% %
% Programmed By: S. Mostapha Kalami Heris %
% %
% e-Mail: sm.kalami@gmail.com %
% kalami@ee.kntu.ac.ir %
% %
% Homepage: http://www.kalami.ir %
% %
% nsga2.m : main file of the program %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc;
clear;
close all;
CostFunction=@Cost;
npop=50; % main population size
nvar=3; % number of unknown variables
nobj=numel(CostFunction(zeros(1,nvar))); % number of objective functions
maxit=100; % maximum number of iterations
VarMin=-5; % lower bound of unknown variables
VarMax= 5; % upper bound of unknown variables
VarRange=[VarMin VarMax]; % range of unknown variables
pc=0.8; % crossover ratio
nc=round(pc*npop/2)*2; % number of parents (also offsprings)
pm=0.3; % mutation ratio
nm=round(pm*npop); % number of mutants
% initialization
pop=CreateEmptyIndividuals(npop);
for i=1:numel(pop)
pop(i).Position=unifrnd(VarMin,VarMax,[1 nvar]);
pop(i).Cost=CostFunction(pop(i).Position);
end
% main loop
for it=1:maxit
[pop F]=NonDominatedSorting(pop);
pop=CalcCrowdingDistance(pop,F);
disp(['Iteration ' num2str(it) ': Number of 1st Front Individuals = ' num2str(numel(F{1}))]);
if it==maxit
break;
end
pop2=CreateEmptyIndividuals(nc);
for k=1:nc/2
p1=BinaryTournamentSelection(pop);
p2=BinaryTournamentSelection(pop);
ch=Crossover(p1,p2);
ch(1).Cost=CostFunction(ch(1).Position);
ch(2).Cost=CostFunction(ch(2).Position);
pop2(2*k-1)=ch(1);
pop2(2*k)=ch(2);
end
pop3=CreateEmptyIndividuals(nm);
for k=1:nm
p=BinaryTournamentSelection(pop);
q=Mutate(p,VarRange);
q.Cost=CostFunction(q.Position);
pop3(k)=q;
end
pop=[pop
pop2
pop3];
[pop F]=NonDominatedSorting(pop);
pop=CalcCrowdingDistance(pop,F);
pop=SortPopulation(pop);
pop=pop(1:npop);
end
PlotFronts(pop,F);
评论1