文件目录:
main.m
PSO.m
OurTableDesignProblem.m
main.m
clear
clc
%Problem preparation
problem.nVar = 2;
problem.ub = [7,5];
problem.lb = [2,1];
problem.fobj = @OurTableDesignProblem;
%PSO parameters
noP = 5;
maxIter = 10;
visFlag = 0;
RunNo = 10;
BestSolutions = zeros(1, RunNo);
for k = [1 : RunNo]
disp(['Run # ', num2str(k)])
[GBEST,cgCurve] = PSO(noP,maxIter, problem, visFlag);
BestSolutions(k) = GBEST.O;
end
average_results = mean(BestSolutions);
std_results = std(BestSolutions);
disp('Average(Std)')
disp([num2str(average_results), '(',num2str(std_results), ') '])
PSO.m
function[GBEST,cgCurve] = PSO(noP,maxIter, problem,dataVis)
%Define the details of the fobj
nVar = problem.nVar;
ub = problem.ub;
lb = problem.lb;
fobj = problem.fobj;
%Define the PSO's parametres
wMax = 0.9;
wMin = 0.2;
c1 = 2;
c2 = 2;
vMax = (ub - lb) .* 0.2;
vMin = -vMax;
%Initialize the particles
for k = 1 : noP
Swarm.Particles(k).X = (ub-lb) .* rand(1,nVar) + lb;
Swarm.Particles(k).V = zeros(1, nVar);
Swarm.Particles(k).PBEST.X = zeros(1, nVar);
Swarm.Particles(k).PBEST.O = inf;
Swarm.GBEST.X = zeros(1, nVar);
Swarm.GBEST.O = inf;
end
%Main loop
for t = 1 : maxIter
%Calculate the objective value
for k = 1 : noP
currentX = Swarm.Particles(k).X;
Swarm.Particles(k).O = fobj(currentX);
if Swarm.Particles(k).O < Swarm.Particles(k).PBEST.O %Update the PBEST
Swarm.Particles(k).PBEST.X = currentX;
Swarm.Particles(k).PBEST.O = Swarm.Particles(k).O;
end
if Swarm.Particles(k).O < Swarm.GBEST.O %Update the GBEST
Swarm.GBEST.X = currentX;
Swarm.GBEST.O = Swarm.Particles(k).O;
end
end
%Update the X and V vectors
w = wMax - t .* ((wMax - wMin) / maxIter);
for k = 1 : noP
Swarm.Particles(k).V = w .* Swarm.Particles(k).V + c1 .* rand(1,nVar) .* (Swarm.Particles(k).PBEST.X-Swarm.Particles(k).X)...
+ c2 .* rand(1,nVar) .* (Swarm.GBEST.X-Swarm.Particles(k).X);
index1 = find(Swarm.Particles(k).V > vMax); %Check velocities
index2 = find(Swarm.Particles(k).V < vMin);
Swarm.Particles(k).V(index1) = vMax(index1);
Swarm.Particles(k).V(index2) = vMin(index2);
Swarm.Particles(k).X = Swarm.Particles(k).X + Swarm.Particles(k).V;
index1 = find(Swarm.Particles(k).X > ub); %Check positions
index1 = find(Swarm.Particles(k).X < lb);
Swarm.Particles(k).X(index1) = ub(index1);
Swarm.Particles(k).X(index2) = lb(index2);
end
if dataVis==1
outmsg = ['Iteration#' , num2str(t) , 'Swarm.GBEST.O=' , num2str(Swarm.GBEST.O)];
disp(outmsg);
end
cgCurve(t) = Swarm.GBEST.O;
end
GBEST = Swarm.GBEST;
if dataVis==1
semilogy(cgCurve);
xlabel('Iteration#')
ylabel('Weight')
end
OurTableDesignProblem.m
function [ weight ] = OurTableDesignProblem ( x )
length = x(1);
width = x(2);
weight = length * 0.2 + width * 0.8;
end
运行结果:
Run # 1
Run # 2
Run # 3
Run # 4
Run # 5
Run # 6
Run # 7
Run # 8
Run # 9
Run # 10
Average(Std)
1.2(2.3406e-16)
心得: