📄 u.m
字号:
%函数定义行
function [fxmin, xmin, Swarm, history] = pso()
%全局变量的初始化:
av=0; %平均值
ub=600; %函数的上界
lb = 300;%函数的下界
SwarmSize = 40; %种群大小
Dim=10; %微粒的维数
c1=2;
c2=2;
Vmax=100; %微粒的最大速度
GM = 0; %全局最小值,是停止判断标准
ErrGoal = 1e-10; %期望标准值
Iterations=1500-1;
success=0;
iter = 0;
step=0;
fevals = 0; %功能评价值
%惯性权重权重的初始化以及迭代变化的规则
W1 = 0.9; % 惯性权重权重的开始值
w2 = 0.4; %惯性权重权重的最后值
w_varyfor = floor(0.7*Iterations);% 惯性权重在整个迭代中的变化步长
w_now = W1;
inertdec = (W1-w2)/w_varyfor; %惯性权重在每次迭代中的时的递减率
% Initialize Swarm and Velocity
Swarm = rand(SwarmSize, Dim)*(ub-lb) +lb; %微粒位置随机初始化:
VStep = rand(SwarmSize, Dim); %微粒速度随机初始化:
%测试函数:Griewank函数
indices=repmat(1:Dim,SwarmSize,1);
fSwarm=sum(((Swarm.^2) / 4000)')' - prod(cos(Swarm ./ sqrt(indices))')' + 1;
fevals = fevals + SwarmSize;
%初始化后最好微粒的相关数据
PBest = Swarm;
fPBest = fSwarm;
%找到初始微粒群体的最好微粒
[fGBest, g] = min(fSwarm);
lastbpf = fGBest;
Best = Swarm(g,:); %用于保存最优值
fBest = fGBest;
history = [0, fGBest];
disp(sprintf('Iterations\t\tfGBest\t\t\tfevals'));
%循环
iiter=0;
while( ((success==0)&iter <= Iterations))
iter = iter+1;
% 更新惯性权重的值
if (iter<=w_varyfor) & (iter > 1)
w_now = w_now - inertdec;
end
A= repmat(Swarm(g,:), SwarmSize, 1);
%生成随机数
R1 = rand(SwarmSize, Dim);
R2 = rand(SwarmSize, Dim);
%利用速度进化方程进行进化
VStep = w_now*VStep + c1*R1.*(PBest-Swarm) + c2*R2.*(A-Swarm);
%对进化后速度大于最大速度的微粒进行处理
changeRows = VStep > Vmax;
VStep(find(changeRows)) =Vmax;
%对进化后速度小于最小速度的微粒进行处理
changeRows = VStep < -Vmax;
VStep(find(changeRows)) = -Vmax;
%微粒位置进行更新
Swarm = Swarm + 1.0 * VStep;
indices=repmat(1:Dim,SwarmSize,1);
fSwarm=sum(((Swarm.^2) / 4000)')' - prod(cos(Swarm ./ sqrt(indices))')' + 1;
fevals = fevals + SwarmSize;
% 更新每个微粒的最好位置
changeRows = fSwarm < fPBest;
fPBest(find(changeRows)) = fSwarm(find(changeRows));%适应值跟换
PBest(find(changeRows), :) = Swarm(find(changeRows), :);%粒子位置跟换
lastbpart = PBest(g, :);%保存最好位置
[fGBest, g] = min(fPBest); % 保存最好适应值
if fGBest < lastbpf %如果本次适应值好于上次则保存
[fBest, b] = min(fPBest);%最好适应值为fBest
Best = PBest(b,:);%最好位置为Best
end
thesum(gg,iter)=fBest;
disp(sprintf('%4d\t\t\t%.5g\t\t\t%5d', iter, fGBest, fevals));
iiter=iiter+1;
x(iiter)=iiter;
% y(iiter)=fGBest;
y(iiter)=fBest;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -