📄 pso.m
字号:
% A SIMPLE IMPLEMENTATION OF THE
% Particle Swarm Optimization IN MATLAB
function [xmin, fxmin, iter] = PSO()
% Initializing variables
success = 0; % Success flag
PopSize = 30; % Size of the swarm
MaxIt = 400; % Maximum number of iterations
iter = 0; % Iterations’counter
fevals = 0; % Function evaluations’ counter
c1 = 2; % PSO parameter C1
c2 = 2; % PSO parameter C2
w = 0.6; % inertia weight
% Objective Function
f = 'DeJong';
dim = 2; % Dimension of the problem
upbnd = 50; % Upper bound for init. of the swarm
lwbnd = -50; % Lower bound for init. of the swarm
GM = 0; % Global minimum (used in the stopping criterion)
ErrGoal = 0.001; % Desired accuracy
% Initializing swarm and velocities
popul = rand(dim, PopSize)*(upbnd-lwbnd) + lwbnd;
vel = rand(dim, PopSize);
for i = 1:PopSize,
fpopul(i) = feval(f, popul(:,i));
fevals = fevals + 1;
end
bestpos = popul;
fbestpos = fpopul;
% Finding best particle in initial population
[fbestpart,g] = min(fpopul);
lastbpf = fbestpart;
while (success == 0) & (iter < MaxIt),
iter = iter + 1;
% VELOCITY UPDATE
for i=1:PopSize,
A(:,i) = bestpos(:,g);
end
R1 = rand(dim, PopSize);
R2 = rand(dim, PopSize);
vel = w*vel + c1*R1.*(bestpos-popul) + c2*R2.*(A-popul);
% SWARMUPDATE
popul = popul + vel;
% Evaluate the new swarm
for i = 1:PopSize,
fpopul(i) = feval(f,popul(:, i));
fevals = fevals + 1;
end
% Updating the best position for each particle
changeColumns = fpopul < fbestpos;
fbestpos = fbestpos.*( 1-changeColumns) + fpopul.*changeColumns;
bestpos(:, find(changeColumns)) = popul(:, find(changeColumns));
% Updating index g
[fbestpart, g] = min(fbestpos);
if abs(fbestpart-GM) <= ErrGoal
success = 1;
else
lastbpf = fbestpart;
end
end
% Output arguments
xmin = popul(:,g);
fxmin = fbestpos(g);
fprintf(' The best vector is : n');
fprintf('--- %g ',xmin);
iter
fxmin
xmin
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -