📄 shishubianmaga2.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=500;%swarm size
CodeL=2;
MaxX(1)=2.048;
MinX(1)=-2.048;
MaxX(2)=2.048;
MinX(2)=-2.048;
E(:,1)=MinX(1)+(MaxX(1)-MinX(1))*rand(Size,1);%initial code
E(:,2)=MinX(2)+(MaxX(2)-MinX(2))*rand(Size,1);%initial code
G=200;%inite size
BsJ=0;
%**********************start running*****************
for kg=1:1:G
time(kg)=kg
%******************step1:evaluation BestJ***********
for i=1:1:Size
xi=E(i,:);
x1=xi(1);
x2=xi(2);
F(i)=100*(x1^2-x2)^2+(1-x1)^2;
Ji=1./F;
BsJi(i)=min(Ji);
end
[OderJi,IndexJi]=sort(BsJi);
BestJ(kg)=OderJi(1);
BJ=BestJ(kg);
Ji=BsJi+1e-10%avoiding deviding zero
fi=F;
[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(kg)=Bestfi;
kg
BestS
%***********STEP 2: Select and reproduct**********
fi_sum=sum(fi);
fi_Size=(Oderfi/fi_sum)*Size;
fi_S=floor(fi_Size);%selecting bigger fi value
r=Size-sum(fi_S);
Rest=fi_Size-fi_S;
[RestValue,Index]=sort(Rest);
for i=Size:-1:Size-r+1;%adding rest to equal Size
fi_S(Index(i))=fi_S(Index(i))+1;%adding rest to equal size
end
k=1;
for i=Size:-1:1
for j=1:1:fi_S(i)
TempE(k,:)=E(Indexfi(i),:);%select and reproduce
k=k+1;%k is used to reproduce
end
end
%***********************step 3: crossover operation***********
pc=0.90;
for i=1:2:(Size-1)
temp=rand;
if pc>temp%crossover condition
alfa=rand;
TempE(i,:)=alfa*E(i+1,:)+(1-alfa)*E(i,:);
TempE(i+1,:)=alfa*E(i,:)+(1-alfa)*E(i+1,:);
end
end
TempE(Size,:)=BestS;
E=TempE;
%******************STEP4:MUTATION OPERATION**************
pm=0.10-[1:1:Size]*(0.01)/Size;%bigge fi,smaller pm自适应变异概率
pm_rand=rand(Size,CodeL);
Mean=(MaxX+MinX)/2;
Dif=(MaxX-MinX);
for i=1:1:Size
for j=1;1:CodeL
if pm(i)>pm_rand(i,j)%MUTATION CONDITION
TempE(i,j)=Mean(j)+Dif(j)*(rand-0.5);
end
end
end
%Guarantee TempE(Size,:)belong to the best individual
TempE(Size,:)=BestS;
E=TempE;
end
BestS
Bestfi
figure(1);
plot(time,BestJ,'r');
grid;
xlabel('time-迭代次数');
ylabel('BestJ');
figure(2);
plot(time,bfi,'g');
grid;
xlabel('time迭代次数');
ylabel('BestF');
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -