clc;
clear;
c1=1.5;
c2=1.5;
maxgen=500;%进化代数
sizepop=100;%种群规模
Vmax=1;%最大最小速度
Vmin=-1;
popmax=100;%最大最小位置
popmin=-100;
%初始化种群、速度、适应度
for i=1:sizepop
pop(i,:)=3*rands(1,2);
v(i,:)=rands(1,2);
fitness(i)=func(pop(i,:));
end
[bestfitness bestindex]=min(fitness);
gbest=pop(bestindex,:);%全局最优粒子
zbest=pop;%个体最优粒子
fitnessgbest=bestfitness;%全局最优适应度
fitnesszbest=fitness;%个体最优适应度
for i=1:maxgen
for j=1:sizepop
v(j,:)=v(j,:)+c1*rand*(zbest(j,:)-pop(j,:))+c2*rand*(gbest-pop(j,:));%速度更新
v(j,find(v(j,:)>Vmax))=Vmax;
v(j,find(v(j,:)<Vmin))=Vmin;
pop(j,:)=pop(j,:)+v(j,:);%位置更新
pop(j,find(pop(j,:)>popmax))=popmax;
pop(j,find(pop(j,:)<popmin))=popmin;
fitness(j)=func(pop(j,:));%适应度更新
end
for j=1:sizepop
if fitness(j)<fitnesszbest(j)
zbest(j,:)=pop(j,:);%个体最优位置更新
fitnesszbest(j)=fitness(j);%个体最优适应度更新
end
if fitness(j)<fitnessgbest
gbest=pop(j,:);%全局最优位置更新
fitnessgbest=fitness(j);%全局最优适应度更新
end
end
yy(i)=fitnessgbest;%全局最优适应度就是我们要的最终收敛值
end
plot(yy);%做出适应度曲线
title('\bf最优个体适应度','fontname','华文行楷','fontsize',12);
xlabel('\bf\it进化代数','fontsize',12);
ylabel('\bf\it适应度','fontsize',12);
grid on;
disp(['The best fitness of the function is:',num2str(yy(500))]);%打印出全局最优解以及此时X1,X2的值。
disp([',when x1、x2 are:',num2str(gbest)]);