# 仿真过程

基本粒子群算法的进化进程如下

# matlab源码

以下给出的粒子群算法代码使用了给定惯性权重

%该脚本要命名为func1.m
%%%%%%%%%%%%%%%%%%%适应度函数%%%%%%%%%%%%%%%%%%%%
function result=func1(x)
summ=sum(x.^2);
result=summ;

%20201012lu注：该matlab代码成功在matlabR2019a运行
%%%%%%%%%%%%%%%%%粒子群算法求函数极值%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%初始化%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;              %清除所有变量
close all;              %清图
clc;                    %清屏
N=100;                  %群体粒子个数
D=10;                   %粒子维数
T=200;                  %最大迭代次数
c1=1.5;                 %学习因子1
c2=1.5;                 %学习因子2
w=0.8;                  %惯性权重
Xmax=20;                %位置最大值
Xmin=-20;               %位置最小值
Vmax=10;                %速度最大值
Vmin=-10;               %速度最小值
%%%%%%%%%%%%%%%%初始化种群个体（限定位置和速度）%%%%%%%%%%%%%%%%
x=rand(N,D) * (Xmax-Xmin)+Xmin;
v=rand(N,D) * (Vmax-Vmin)+Vmin;
%%%%%%%%%%%%%%%%%%初始化个体最优位置和最优值%%%%%%%%%%%%%%%%%%%
p=x;
pbest=ones(N,1);
for i=1:N
pbest(i)=func1(x(i,:));
end
%%%%%%%%%%%%%%%%%%%初始化全局最优位置和最优值%%%%%%%%%%%%%%%%%%
g=ones(1,D);
gbest=inf;
for i=1:N
if(pbest(i)<gbest)
g=p(i,:);
gbest=pbest(i);
end
end
gb=ones(1,T);
%%%%%%%%%%%按照公式依次迭代直到满足精度或者迭代次数%%%%%%%%%%%%%
for i=1:T
for j=1:N
%%%%%%%%%%%%%%更新个体最优位置和最优值%%%%%%%%%%%%%%%%%
if (func1(x(j,:))<pbest(j))
p(j,:)=x(j,:);
pbest(j)=func1(x(j,:));
end
%%%%%%%%%%%%%%%%更新全局最优位置和最优值%%%%%%%%%%%%%%%
if(pbest(j)<gbest)
g=p(j,:);
gbest=pbest(j);
end
%%%%%%%%%%%%%%%%%跟新位置和速度值%%%%%%%%%%%%%%%%%%%%%
v(j,:)=w*v(j,:)+c1*rand*(p(j,:)-x(j,:))...
+c2*rand*(g-x(j,:));
x(j,:)=x(j,:)+v(j,:);
%%%%%%%%%%%%%%%%%%%%边界条件处理%%%%%%%%%%%%%%%%%%%%%%
for ii=1:D
if (v(j,ii)>Vmax)  |  (v(j,ii)< Vmin)
v(j,ii)=rand * (Vmax-Vmin)+Vmin;
end
if (x(j,ii)>Xmax)  |  (x(j,ii)< Xmin)
x(j,ii)=rand * (Xmax-Xmin)+Xmin;
end
end
end
%%%%%%%%%%%%%%%%%%%%记录历代全局最优值%%%%%%%%%%%%%%%%%%%%%
gb(i)=gbest;
end
g                         %最优个体
gb(end)                   %最优值
figure
plot(gb)
xlabel('迭代次数');
ylabel('适应度值');
title('适应度进化曲线')


g =

Columns 1 through 4

1.454674225060714e-05    -1.920170265055473e-05    -9.944694959561888e-05    -7.525095070385998e-05

Columns 5 through 8

-3.683040347134757e-05    -5.060594403886991e-05     3.386418794948892e-05     9.034293625667981e-05

Columns 9 through 10

-8.605516305674458e-05     1.453785400805862e-04

ans =

5.789919501406406e-08


04-22

06-14
08-03 2万+
04-22 852
08-16 933
05-20 139
05-08
09-26
11-07 6万+
09-29 2万+
10-26 2261
07-27 1万+