初始化
function pop=initpop(popsize,chromlength)
pop=round(rand(popsize,chromlength));
end
目标函数值
function pop2=decodebinary(pop)
[px,py]=size(pop);
for i=1:py
pop1(:,i)=2.^(py-i).*pop(:,i);
end
pop2=sum(pop1,2);
end
function pop2=decodechrom(pop,spoint,length)
pop1=pop(:,spoint:spoint+length-1);
pop2=decodebinary(pop1);
end
function [objvalue]=calobjvalue(pop)
temp1=decodechrom(pop,1,10);
x=temp1*10/1023;
% 目标函数
objvalue=10*sin(5*x)+7*cos(4*x);
end
个体适应值
function fitvalue=calfitvalue(objvalue)
global Cmin;
Cmin=0;
[px,py]=size(objvalue);
for i=1:px
if objvalue(i)+Cmin>0
temp=Cmin+objvalue(i);
else
temp=0.0;
end
fitvalue(i)=temp;
end
fitvalue=fitvalue';
选择
function [newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue);
fitvalue=fitvalue/totalfit;
fitvalue=cumsum(fitvalue);
[px,py]=size(pop);
ms=sort(rand(px,1));
fitin=1;
newin=1;
while newin<=px
if(ms(newin))<fitvalue(fitin)
newpop(newin)=pop(fitin);
newin=newin+1;
else
fitin=fitin+1;
end
end
交叉
function [newpop]=crossover(pop,pc)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:2:px-1
if(rand<pc)
cpoint=round(rand*py);
newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)];
newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)];
else
newpop(i,:)=pop(i);
newpop(i+1,:)=pop(i+1);
end
end
变异
function [newpop]=mutation(pop,pm)
[px,py]=size(pop);
newpop=zeros(px,py);
for i=1:px
if(rand<pm)
mpoint=round(rand*py);
if mpoint<=0
mpoint=1;
end
newpop(i,:)=pop(i,:);
if any(newpop(i,mpoint))
newpop(i,mpoint)=0;
else
newpop(i,mpoint)=1;
end
else
newpop(i)=pop(i);
end
end
最大适应值
function [bestindividual,bestfit]=best(pop,fitvalue)
[px,py]=size(pop);
bestindividual=pop(1,:);
bestfit=fitvalue(1);
for i=2:px
if fitvalue(i)>bestfit
bestindividual=pop(i,:);
bestfit=fitvalue(i);
end
end
主程序
popsize=20;
chromlength=10;
pc=0.7;
pm=0.005;
pop=initpop(popsize,chromlength);
for i=1:20
[objvalue]=calobjvalue(pop);
fitvalue=calfitvalue(objvalue);
[newpop]=selection(pop,fitvalue);
[newpop]=crossover(pop,pc);
[newpop]=mutation(pop,pc);
[bestindividual,bestfit]=best(pop,fitvalue);
y(i)=max(bestfit);
n(i)=i;
pop5=bestindividual;
x(i)=decodechrom(pop5,1,chromlength)*10/1023;
pop=newpop;
end
fplot(@(x)9.*sin(5.*x)+8.*cos(4.*x),[0 15])
hold on
plot(x,y,'r*')
hold off
参考资料:《MATLAB R2016a 完全自学一本通》