%目标曲线
x=1:0.01:2;
y=sin(10*pi*x)./x;
figure
plot(x,y)
hold on
%初始化速度和位移的参数值
c1=1.49445;
c2=1.49445;
maxgen=50;%进化次数
sizepop=10;%种群规模
%速度变化范围
Vmax=0.5;
Vmin=-0.5;
%种群变化范围
popmax=2;
popmin=1;
%1、产生初始种群和速度
for i=1:sizepop %种群规模
%pop(i,1)=(rands(1)+1)/2+1;%范围1-2
%V(i,1)=0.5*rand(1);
pop(i,:)=(rands(1)+1)/2+1;%范围1-2
V(i,:)=0.5*rand(1);
%计算适应度,适应度也是初始值
fitness(i)=fun(pop(i,:));
end
%2、个体极值与群体极值
[bestfitness,bestindex]=max(fitness);
zbest=pop(bestindex,:);
gbest=pop;
fitnessgbest=fitness;%种群适应度函数值
fitnesszbest=bestfitness;%群体最优
%3、迭代寻优过程
for i=1:maxgen
for j=1:sizepop
%V和pop是只有一列数据的矩阵
V(j,:)=V(j,:)+c1*rand*(gbest(j,:)-pop(j,:))+c2*rand*(zbest-pop(j,:));
V(j,find(V(j,:)>Vmax))=Vmax;
V(j,find(V(j,:)<Vmin))=Vmin;
%find 函数能够返回有非零元素的位置,这算是对这一函数的巧妙运用。
pop(j,:)=pop(j,:)+V(j,:);
pop(j,find(pop(j,:)>popmax))=popmax;
pop(j,find(pop(j,:)<popmin))=popmin;
fitness(j)=fun(pop(j,:));
end
for j=1:sizepop
%个体最优更新
if fitness(j)>fitnessgbest(j)
gbest(j,:)=pop(j,:);
fitnessgbest(j)=fitness(j);
end
%群体最优更新
if fitness(j)>fitnesszbest
zbest=pop(j,:);
fitnesszbest=fitness(j);
end
end
%本代寻找到的最佳的适应度函数值
yy(i)=fitnesszbest;
end
%最优结果
[zbest fitnesszbest]
plot(zbest,fitnesszbest,'r*');
figure
plot(yy)
title('最优个体适应度','fontsize',12);
xlabel('进化代数','fontsize',12);
ylabel('适应度','fontsize',12);