% 主程序
%遗传算法主程序
%Name:genmain.m
%author:郑伟 国防科技大学三院六队
%hotflying@126.com
clear
clf
%%初始化
popsize=50; %群体大小,需要修改
chromlength=115; %字符串长度(个体长度),自抗扰参数太多应该取得更长
pc=0.6; %交叉概率
pm=0.001; %变异概率
% pop=initpop(popsize,chromlength); %随机产生初始群体,随即种群,各种参数都随机得到
%%开始迭代
N=200; %N为迭代次数
for i=1:N
% time_output=1 %设置好仿真时间
% open_system('PI20110527position');
% set_param('PI20110527position','MaxStep','0.01');%设置一些必要的参数,这里以最大步长为例
% [T1 X Y1 Y2]=sim('PI20110527position',time_output,[],[]);%执行仿真给出out1的结果,T是时间,Y是值
for j=1:popsize
pop =initpop(1,chromlength); %随机产生初始群体,随即种群,各种参数都随机得到
temp1=decodechrom(pop ,1,10); %将pop每行转化成十进制数
temp2=decodechrom(pop ,11,10);
temp3=decodechrom(pop ,21,10);
temp4=decodechrom(pop ,31,15);
temp5=decodechrom(pop ,46,20);
temp6=decodechrom(pop ,66,10);
temp7=decodechrom(pop ,76,10);
temp8=decodechrom(pop ,86,10);
temp9=decodechrom(pop ,96,10);
temp10=decodechrom(pop ,106,10);
r=temp1*1024/2047; %将二值域中的数转化为变量域的数
T=temp2/2047;
beta01=temp3*1000/2047;
beta02=temp4*1000/32767;
beta03=temp5*1000/2097151;
alpha1=temp6*100/2047;
alpha2=temp7*100/2047;
beta1=temp8*100/2047;
beta2=temp9*100/2047;
b=temp10*1000/2047;
c=1/b;
[objvalue]=calobjvalue(pop); %计算目标函数
end
fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度,目标函数值的倒数(误差越小,适应度值越小,越适用)
[newpop]=selection(pop,fitvalue); %复制
[newpop]=crossover(pop,pc); %交叉
[newpop]=mutation(pop,pm); %变异
[bestindividual,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值
y(i)=max(bestfit); %储存最优个体适应值
n(i)=i;
pop5=bestindividual; %储存最优个体
%解码
% x1(i)=-1+decodechrom(pop5,1,chromlength/2)*3/32767;
% % x2(i)=-100+decodechrom(pop5,chromlength/2+1,chromlength/2)*200/32767;
pop=newpop; %将新产生的种群作为当前种群
end
%%绘图
figure(1) %最优点变化趋势图
i=1:N
plot(y(i),'-r*')
xlabel('迭代次数');
ylabel('最优个体适应值');
title('最优点变化趋势');
legend('最优点');
grid on
figure(2) %最优点变化趋势图
i=1:N
z(i)=2+x1(i).*sin(10*pi*x1(i));
plot(x1(i),z(i),'-b*','Linewidth',2)
xlabel('迭代最大值所得点x(i)');
ylabel('迭代所得对应函数最值');
title('最优点变化趋势');
legend('最优点');
grid on
[ymax index]=max(y); %计算最大值及其位置
xmax=[x1(index)] %计算最大值对应的x值
ymax
- 1
- 2
- 3
- 4
- 5
- 6
前往页