遗传算法matlab程序
function result=sga(n,a,b,pc,pm,e)
%n—群体规模;a—搜索上限;b—搜索下限;
%pc—交叉概率;pm—变异概率;e—计算精度;
for i=1:50 %求出群体的码串最小长度m
if (b-a)/e>2^(i)
m=i+1
else
i=i+1
end
end
popusize=n;chromlength=m;j=1;
popu=round(rand(popusize,chromlength)); %随机产生n行m列的初始群体while j<=30 %设置程序中止条件
py=chromlength;
for i=1:py %进行二进制转换成十进制的解码操作
popu1(:,i)=2.^(py-1).*popu(:,i);
Py=py-1;
end
popu2=sum(popu1,2);
x=a+popu2*(b-a)/(2^l-1);
yvalue=2*x.^2.*cos(3*x)+x.*sin(5*x)+8; %计算群体中每个个体的适应度for i=1:popusize %执行复制操作
if yvalue(i)<0
yvalue(i)=0;
end
end
fitscore=yvalue/sum(yvalue);%个体被选中的概率
fitscore=cumsum(fitscore);% 群体中个体的累积概率
wh=sort(rand(popusize,1));% 从小到大排列
wheel=1;fitone=1;
while wheel<=popusize %执行转盘式选择操作
if wh(wheel)<fitscore(fitone)
newpopu(wheel,:)=popu(fitone,:);
wheel=wheel+1;
else
fitone=fitone+1;
end
end
popu=newpopu;
for i=1:2:popusize-1 %执行交叉操作
if rand<pc
cpoint=round(rand*chromlength);
newpopu(i,:)=[popu(i,1:cpoint) popu(i+1,cpoint+1:chromlength)];
newpopu(i+1,:)=[popu(i+1,1:cpoint) popu(i,cpoint+1:chromlength)];


