【老生谈算法】标准遗传算法的MATLAB实现源码——遗传算法

标准遗传算法的MATLAB实现

%标准遗传算法
%优化函数为f=-(x-1)^2+4,其中,0<=x<=3
%编码长度为10位,编码精度为0.0029
%种群规模设为40,遗传算子分别为比例选择,单点交叉和单点变异。交叉概率0.7,变异概率0.1
%最大进化代数为200代,保优操作。

main.m

initial;
global G;
for G=1:200
    crossover;
    mutation;
    adapting;
    keepbest;
    selection;
end
result;

%初始化函数,随机形成规模为40初始种群
initial.m

pop(40,10)=0;
best_individual(10)=0;  %最优个体
adapt_ave(200)=0;   %种群平均适应值
 
for i=1:40
    for j=1:10
        if rand>0.5
            pop(i,j)=1;
        else
            pop(i,j)=0;
        end
    end
end
% pop
clear i;
clear j;

%交叉操作,概率为0.7,单点交叉
crossover.m

for i=1:2:39
    cross_P=rand;   %随机产生一个数,以比较交叉概率
    if cross_P<0.9  %交叉概率为0.9
        cross_pos=round(10*rand);   %交叉位置为0~9,若位置为09,则不进行交叉操作
        if or(cross_pos==0,cross_pos==9)
            continue;
        end
    
        for j=cross_pos:10
            temp=pop(i,j);
            pop(i,j)=pop(i+1,j);
            pop(i+1,j)=temp;
        end
    end
end
 
clear i;
clear j;
clear temp;
clear cross_P;
clear cross_pos;

%变异操作,单点变异,变异概率为0.1
mutation.m

for i=1:40
    if rand<0.1 %通过变异概率
        M_pos=round(10*rand);
        if M_pos~=0 %若变异位为0则无意义
            pop(i,M_pos)=1-pop(i,M_pos);
        end
    end
end
 
clear M_pos;
clear i;

%计算适应值
adapting.m

for i=1:40
    adapt(i)=0;
end
 
for i=1:40
    for j=1:10
        if pop(i,j)==1
            adapt(i)=adapt(i)+2^(10-j);
        end
    end
    adapt(i)=adapt(i)*0.0029;
    adapt(i)=-(adapt(i)-1).^2+4;
end
 
global adapt_best;
global best_pos;
adapt_best=0;   %最佳个体
best_pos=0;     %最佳个体在种群中的位置
% adapt_ave=0;
 
for i=1:40
    adapt_ave(G)=adapt_ave(G)+adapt(i);
    if adapt_best<adapt(i)
        adapt_best=adapt(i);
        best_pos=i;
    end
end
 
adapt_ave(G)=adapt_ave(G)/40;
  
clear i;
clear j;

%保优操作
keepbest.m

for i=1:10
    best_individual(i)=pop(best_pos,i);
end


% The select oprator function
selection.m

ada_sum=0;
ada_temp=0;
r=0;
i=0;j=0;
for i=1:40
    ada_sum=ada_sum+adapt(i);
end
 
for i=1:39      %选择39次,最后一个个体留给历代最优解
    r=rand*ada_sum;  %随机产生一个数
    ada_temp=0;      %初始化累加值为0
    j=0;
    while(ada_temp<r)
        j=j+1;
        ada_temp=ada_temp+adapt(j);        
    end
    %退出循环时的j值即为被选择的个体序号
%     if j>40
%         j=40;
%     end
        
    for k=1:10
        new_pop(i,k)=pop(j,k);
    end
 
end
 
% 最优解复制
for i=1:10
    new_pop(40,i)=best_individual(i);
end
 
%将选择产生的新群体复制给pop种群
for i=1:40
    for j=1:10
        pop(i,j)=new_pop(i,j);
    end
end
 
clear i;
clear j;
clear k;
clear r;
clear ada_temp;

%结果统计函数
result.m

plot(adapt_ave);
best=0;
for j=1:10
    if best_individual(j)==1
        best=best+2^(10-j);
    end
end
best=best*0.0029;
'最优个体为'
best
'最优解为'
best=-(best-1).^2+4;
best

猜你喜欢

转载自blog.csdn.net/m0_53407570/article/details/125323196