% 粒子群最值算法代码
% 版权所有中国地质大学:李振
% 求z=sin((x.^4+y.^3)*100)-(x.^2+y.^2)/2;最大值在【-pi/2,pi/2】
function JG=pso
format long
close all
clear
clc
x_fw=[-pi/2,pi/2];
y_fw=[-pi/2,pi/2];
w=0.1; %惯性权重
c1=2;c2=2; %加速常数
N=100; %粒子群大小
M=100; %迭代次数
D=2; %问题维数
P=init_PSO(N,x_fw,y_fw);
h=inti_fig(x_fw,y_fw,P.X(:,1),P.X(:,2));
pause(3)
gt=-inf*ones(M,N);
x=[];
Pnd=zeros(N,2);
for i=1:M
Px(i).X=P.X;
x=P_fit(N,P);%当前粒子群的适应度值
gt(i,:)=x;%所有粒子群的适应度函数值,一列为一个粒子
[pbest
a]=max(gt);
for
j=1:N
Pnd(j,:)=Px(a(j)).X(j,:);
end
[gbest
b]=max(pbest);
Pgd=Pnd(b,:);
P=P_gx(w,c1,c2,P,Pnd,Pgd,x_fw,y_fw);%粒子群更新
JG(i).zhi=gbest;
JG(i).LZ=Pnd;
do_plot(h,Pnd(:,1),Pnd(:,2))
pause(0.1)
if
i<30
MM(i);
end
i
gbest
end
function h=inti_fig(x_fw,y_fw,x,y)
xx=x_fw(1):(x_fw(2)-x_fw(1))/500:x_fw(2);
yy=y_fw(1):(y_fw(2)-y_fw(1))/500:y_fw(2);
[X Y]=meshgrid(xx,yy);
Z=sin((X.^4+Y.^3)*100)-(X.^2+Y.^2)/2;
for i=1:length(x)
z(i)=fitness([x(i),y(i)]);
end
figure()
h=plot3(x,y,z,'*');
hold on
mesh(X,Y,Z)
hold off
xlim(x_fw);
ylim(y_fw);
function do_plot(h,x,y)
for i=1:length(x)
z(i)=fitness([x(i),y(i)]);
end
set(h,'xdata',x,'ydata',y,'zdata',z);
function P=init_PSO(N,x_fw,y_fw)
P.X=[rand(N,1)*(max(x_fw)-min(x_fw))+min(x_fw)
rand(N,1)*(max(y_fw)-min(y_fw))+min(y_fw)];
P.V=rand(N,2);
function x=P_fit(N,P)
a=P.X;
for i=1:N
x(i)=fitness(a(i,:));
end
function P=P_gx(w,c1,c2,P,Pnd,Pgd,x_fw,y_fw)
x=P.X(:,:);
v=P.V(:,:);
Pgda=[Pgd(1)*ones(length(x(:,1)),1)
Pgd(2)*ones(length(x(:,1)),1)];
v=w*v+c1*rand(1,1)*(Pnd-x)+c2*rand(1,1)*(Pgda-x);
x=P.X+v;
for i=1:length(x(:,1))
if
x(i,1)>=x_fw(1)&&x(i,1)<=x_fw(2)&&x(i,2)>=y_fw(1)&&x(i,2)<=y_fw(2)
P.V(i,:)=v(i,:);
P.X(i,:)=x(i,:);
else
P.X(i,:)=[rand(1,1)*(max(x_fw)-min(x_fw))+min(x_fw)
rand(1,1)*(max(y_fw)-min(y_fw))+min(y_fw)];
P.V(i,:)=rand(1,2);
end
end
function f=fitness(X)
% f=(sin(X(1)/5)*(X(1)*X(2)*5))+X(1)/10;
f=sin((X(1).^4+X(2).^3)*100)-(X(1).^2+X(2).^2)/2;
% f=subs(func,{'x','y'},X);
function MM(i)
filename = 'cc.gif';
f = getframe(gcf); imind = frame2im(f);
[imind,cm] =
rgb2ind(imind,256);
if
i==1
imwrite(imind,cm,filename,'gif',
'Loopcount',inf,'DelayTime',0.05);%感觉时间太短改这个,但是储存就很卡
else
imwrite(imind,cm,filename,'gif','WriteMode','append','DelayTime',0.1);%感觉时间太短改这个,但是储存就很卡
end