與GA算法比較
%粒子羣優化
clc,clear all;
x=[0:0.01:4];
y=hanshu(x);
figure; plot(x,y); hold on
W=1; %慣性因子
c1 = 2; c2 = 2;
maxgen=30; %迭代次數
sizepop=5; %粒子個數
Vmax=1; Vmin=-1; %速度限制
popmax=4; popmin=0; %位置限制
pop=[0.5 ,3.5,2,1,0.9] ; %產生初始粒子和速度 % pop=[2 4]
for i=1:sizepop
V(i)=(2*rand(1,1)-1); %初始化速度
fitness(i)=hanshu(pop(i)); %計算適應度
end
% stem(pop(1),fitness(1),'r') ;
% stem(pop(2),fitness(2));
% hold on ;
[bestfitness ,bestindex]=max(fitness);
zbest=pop(bestindex); %全局最佳
gbest=pop; %個體最佳
fitnessgbest=fitness; %個體最佳適應度值
fitnesszbest=bestfitness; %全局最佳適應度值
%% 迭代尋優
for i=1:maxgen
for j=1:sizepop %速度更新
V(j) =W*V(j) + c1*rand*(gbest(j) - pop(j)) + c2*rand*(zbest - pop(j));
if V(j)>Vmax
V(j)=Vmax;
end
if V(j)<Vmin
V(j)=Vmin;
end %種羣更新
pop(j)=pop(j)+V(j);
if pop(j)>popmax
pop(j)=popmax;
end
if pop(j)<popmin
pop(j)=popmin;
end
%自適應變異(避免粒子羣算法陷入局部最優)
fitness(j)=hanshu(pop(j)); %個體最優更新
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
i
V
% stem(pop(1),fitness(1),'r') ;
% stem(pop(2),fitness(2)) ;hold on
% pause(0.1) ;
yy(i)=fitnesszbest;
end
figure ; plot(yy); title(['適應度曲線 ' '終止代數=' num2str(maxgen)]); xlabel('迭代代數'); ylabel('適應度');
max(yy)
function y=hanshu(x)
y=1-exp(-x).*cos(3*x);
end