一段遗传算法的代码

这段代码展示了如何使用遗传算法来求解函数优化问题。首先绘制目标函数曲线,然后定义遗传算法参数如个体数目、最大代数和精度。接着初始化种群并计算目标函数值。通过选择、重组和变异操作迭代优化,最终找到最优解并在图中显示结果。
摘要由CSDN通过智能技术生成

figure(1);
fplot('variable.*sin(10*pi*variable)+2.0',[-1,2]);   %画出函数曲线
%定义遗传算法参数
NIND=40;        %个体数目(Number of individuals)
MAXGEN=25;      %最大遗传代数(Maximum number of generations)
PRECI=20;       %变量的二进制位数(Precision of variables)
GGAP=0.9;       %代沟(Generation gap)
trace=zeros(2, MAXGEN);                        %寻优结果的初始值
FieldD=[20;-1;2;1;0;1;1];                      %区域描述器(Build field descriptor)
Chrom=crtbp(NIND, PRECI);                      %初始种群
gen=0;                                         %代计数器
variable=bs2rv(Chrom, FieldD);                 %计算初始种群的十进制转换
ObjV=variable.*sin(10*pi*variable)+2.0;        %计算目标函数值
while gen<MAXGEN
   FitnV=ranking(-ObjV);                                  %分配适应度值(Assign fitness values)        
   SelCh=select('sus', Chrom, FitnV, GGAP);               %选择
   SelCh=recombin('xovsp', SelCh, 0.7);                   %重组
   SelCh=mut(SelCh);                                      %变异
   variable=bs2rv(SelCh, FieldD);                         %子代个体的十进制转换
   ObjVSel=variable.*sin(10*pi*variable)+2.0;             %计算子代的目标函数值
   [Chrom ObjV]=reins(Chrom, SelCh, 1, 1, ObjV, ObjVSel); %重插入子代的新种群
   variable=bs2rv(Chrom, FieldD);
   gen=gen+1;                                             %代计数器增加
   %输出最优解及其序号,并在目标函数图像中标出,Y为最优解,I为种群的序号
   [Y, I]=max(ObjV);hold on;
   plot(variable(I), Y, 'bo');
   trace(1, gen)=max(ObjV);                               %遗传算法性能跟踪
   trace(2, gen)=sum(ObjV)/length(ObjV);
end
variable=bs2rv(Chrom, FieldD);                            %最优个体的十进制转换
hold on  grid;
plot(variable,ObjV,'b*');
figure(2);
plot(trace(1,:));
hold on;
plot(trace(2,:),'-.');grid
legend('解的变化','种群均值的变化')

 

 

 

 

CRTBP.m - Create an initial population
 
  This function creates a binary population of given size and structure.
 
  Syntax: [Chrom Lind BaseV] = crtbp(Nind, Lind, Base)
 
  Input Parameters:
 
   Nind - Either a scalar containing the number of individuals
          in the new population or a row vector of length two
          containing the number of individuals and their length.
 
   Lind - A scalar containing the length of the individual
         chromosomes.
 
   Base - A scalar containing the base of the chromosome
          elements or a row vector containing the base(s)
         of the loci of the chromosomes.
 
  Output Parameters:
 
   Chrom - A matrix containing the random valued chromosomes
          row wise.
 
   Lind - A scalar containing the length of the chromosome.
 
   BaseV -

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值