📄 ga.asv
字号:
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(['适应度曲线 ' '终止代数=' num2str(maxgen)]);
xlabel('进化代数');ylabel('适应度');
legend('平均适应度','最佳适应度');
disp('适应度 变量');
x=Decode(lenchrom,bound,bestchrom,fcode);
% show in command window
disp([bestfitness x]);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -