?? ga.asv
字號(hào):
function Ret=GA(GAPara)
% This is simple genetic algorithm(SGA)
% In this function ,it fulfils genetic algorithm
%*****************************************************
Individuals=struct('Fitness',zeros(1,GAPara.SizePop),...%'value',zeros(1,GAPara.SizePop),...
'Chrom',[]); % structure of population
AvgFitness=[]; % average fitness of population
BestFitness=[]; % best fitness of population
BestChrom=[]; % chromosome of best fitness
% inivitialization
for i=1:GAPara.SizePop
% produce new population at random
Individuals.Chrom(i,:)=Code(GAPara.LenChrom,GAPara.CodeFcn,GAPara.Bound);
x=Decode(GAPara.LenChrom,GAPara.Bound,Individuals.Chrom(i,:),GAPara.CodeFcn);
% caculate fitness
Individuals.Fitness(i)=feval(GAPara.Fcn);
end
% find maximum value which is best
[BestFitness BestIndex]=max(Individuals.Fitness);
BestChrom=Individuals.Chrom(BestIndex,:);
AvgFitness=sum(Individuals.Fitness)/GAPara.SizePop;
% record average and best fitness of every generation
Trace=[AvgFitness BestFitness];
% evolution begin
for i=1:GAPara.MaxGen
% selection
Individuals=Select(Individuals,GAPara.SizePop,GAPara.SelectFcn);
% crossover
Individuals.Chrom=Cross(GAPara.PCross,GAPara.LenChrom,Individuals,...
GAPara.SizePop,GAPara.CrossFcn,[i GAPara.MaxGen]);
% mutation
Individuals.Chrom=Mutation(GAPara.PMutation,GAPara.LenChrom,Individuals,...
GAPara.SizePop,GAPara.MutationFcn,GAPara.Bound,[i GAPara.MaxGen]);
% calculate fitness
for j=1:GAPara.SizePop
x=Decode(GAPara.LenChrom,GAPara.Bound,Individuals.Chrom(j,:),GAPara.CodeFcn);
Individuals.Fitness(j)=feval(GAPara.AinFcn);
end
% substitute chromosome of worest fitness
% find maximum value which is best
[NewBestFitness,NewBestIndex]=max(Individuals.Fitness);
[WorestFitness,WorestIndex]=min(Individuals.Fitness);
% substitute chromosome of worest fitness
if BestFitness<NewBestFitness
BestFitness=NewBestFitness;
BestChrom=Individuals.Chrom(NewBestIndex,:);
end
Individuals.Chrom(WorestIndex,:)=BestChrom;
Individuals.Fitness(WorestIndex)=BestFitness;
AvgFitness=sum(Individuals.Fitness)/GAPara.SizePop;
Trace=[Trace;AvgFitness BestFitness];
if BestFitness<=Para.Goal
break;
end
end
% draw fitness of every generation
HFig=findobj('Tag','Trace');
% See if it is open
if ishandle(HFig)
figure(HFig);
else
HFig=figure('Tag','Trace');
end
figure(HFig);
[r c]=size(Trace);
plot([1:r]',Trace(:,1),'r-',[1:r]',Trace(:,2),'b--');
title(['適應(yīng)度曲線 ' '終止代數(shù)=' num2str(maxgen)]);
xlabel('進(jìn)化代數(shù)');ylabel('適應(yīng)度');
legend('平均適應(yīng)度','最佳適應(yīng)度');
disp('適應(yīng)度 變量');
x=Decode(lenchrom,bound,bestchrom,fcode);
% show in command window
disp([bestfitness x]);
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -