h1s2j3 发表于 2013-6-26 17:06:48

新手编写遗传算法程序有误,求指导

是利用遗传算法求解函数最大值的程序,运行时总出错,求指导
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%执行转盘式选择操作
      ifwh(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,:)=;
          newpopu(i+1,:)=;
      else
          newpopu(i,:)=popu(i,:);
          newpopu(i+1,:)=popu(i+1,:);
      end   
end
popu=newpopu;
for i=1:popusize%执行变异操作
      ifrand<pm
          mpoint=round(rand*chromlength);
          if mpoint<=0;
            mpoint=1;
          end
            newpopu(i,:)=popu(i,:);
          ifnewpopu(i,mpoint)==0
            newpopu(i,mpoint)=1;
          else
             newpopu(i,mpoint)=0;
         end   
      else
          newpopu(i,:)=popu(i,:);
      end
end   
=max(yvalue);%求出群体中适应值最大的个体及其适应值
bestindividual=newpopu(index,:);
   py=chromlength;
for i=1:py %进行二进制转换成十进制的解码操作
bestindividual(1,i)=2.^(py-1).*bestindividual(:,i)
   py=py-1;
end
r(j)=a+sum(bestindividual,2)*(b-a)/(2^l-1);
   popu=newpopu;j=j+1;% 重新赋值并返回
end
fplot('2*x.^2.*cos(3*x)+x.*sin(5*x)+8',);
hold on;plot(r,y,'r*');hold off
xlabel('x');ylabel('y')
=max(y);%计算最大值及其位置
result=;% 返回优化结果

h1s2j3 发表于 2013-6-27 16:29:57

自己已解决
页: [1]
查看完整版本: 新手编写遗传算法程序有误,求指导