⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 erjinzhiga1.m

📁 这是初学算法时收集和整理的几个比较有参考价值的ga程序,望对大家有帮助
💻 M
字号:
%遗传算法求Rosenbrock函数的极大值,函数信息如下:1)f(x(1),x(2))=100(x(1)^2-x(2)^2)^2+(1-x(1)^2;
%2)-2.048<=x(i)<=2.048,(i=1,2)
%该函数有两个局部极大点,分别为f(2.048,-2.048)=3897.7342和f(-2.048,-2.048)=3905.9262,后者为全局
%最大点
%二进制编码遗传算法求该函数极大值程序如下
%*****************************************
clear all;
close all;
%set parameters
Size=80;%群体大小
G=100;%进化终止代数 
CodeL=10;
umax=2.048;
umin=-2.048;
E=round(rand(Size,2*CodeL));%initial code
%main program
for k=1:1:G
    time(k)=k;
    
    for s=1:1:Size
        m=E(s,:);
        Y1=0;
        Y2=0;
%uncoding
m1=m(1:1:CodeL);
for i=1:1:CodeL
    Y1=Y1+m1(i)*2^(i-1);
end
x1=(umax-umin)*Y1/1023+umin;
m2=m(CodeL+1:1:2*CodeL);
for i=1:1:CodeL
    Y2=Y2+m2(i)*2^(i-1);
end
x2=(umax-umin)*Y2/1023+umin;
F(s)=100*(x1^2-x2)^2+(1-x1)^2;
end
Ji=1./F;
%***********Step 1:Evaluate BestJ****************
BestJ(k)=min(Ji);
fi=F;%fitness function
[Oderfi,Indexfi]=sort(fi);%Arranging fi small to bigger
Bestfi=Oderfi(Size);%let Bestfi=max(fi)
BestS=E(Indexfi(Size),:);%let BestS=E(m),m is the Indexfi belong to max(fi)
bfi(k)=Bestfi;
%******************step2: select and reproduct operation**********
fi_sum=sum(fi);
fi_Size=(Oderfi/fi_sum)*Size;
fi_S=floor(fi_Size);%selecting bigger fi value
kk=1;
for i=1:1:Size
    for j=1:1:fi_S(i)%select and reproduce
        TempE(kk,:)=E(Indexfi(i),:);
        kk=kk+1;%kk is used to reproduce
    end 
end
%*****************step 3: crossover operation*****************888
pc=0.60;
n=ceil(20*rand);
for i=1:2:(Size-1)
    temp=rand;
    if pc>temp%crossover condition
        for j=n:1:20
            TempE(i,j)=E(i+1,j);
            TempE(i+1,j)=E(i,j);
        end
    end
end
TempE(Size,:)=BestS;
E=TempE;
%****************88888STEP 4:MUTATION OPRRATION******************
%pm=0.001;
%pm=0.001-[1:1:Size]*(0.001)/Size;%bigger fi ,smaller pm
%pm=0.0;%no mutation
pm=0.1%big mutation
for i=1;1:Size
    for j=1:1:2*CodeL
        temp=rand;
        if pm>temp%mutation condion
            if TempE(i,j)==0
                TempE(i,j)=1;
            else
                TempE(i,j)=0;
            end
        end
    end
end
%guarantee temppop(30,:) is the code belong to the best individual(max(fi))
TempE(Size,:)=BestS;
E=TempE;
end
Max_Value=Bestfi
BestS
x1
x2
figure(1);
plot(time,BestJ);
xlabel('times');
ylabel('Best J');
figure(2);
plot(time,bfi);
xlabel('times');
ylabel('Best F');

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -