function z = PSO (x,y)
z= (4-2.1*x^2+(x^4)/3)*x^2 + x*y + (-4+4*y^2)*y^2;
end
clc;
clear;
close all;
CostFunction = @(x,y) PSO(x,y);
nvar =2
VarSize = [1 nVar];
VarMin = -10;
VarMax = 10;
MaxIt = 50;
nPop = 25;
w = 1;
wdamp = params.wdamp;
c1 = 2;
c2 = 2;
empty_particle.Position = [];
empty_particle.Velocity = [];
empty_particle.Cost = [];
empty_particle.Best.Position = [];
empty_particle.Best.Cost = [];
particle = repmat(empty_particle, nPop, 1);
GlobalBest.Cost = inf;
for i=1:nPop
particle(i).Position = unifrnd(VarMin, VarMax, VarSize);
particle(i).Velocity = zeros(VarSize);
particle(i).Cost = CostFunction(particle(i).Position);
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
BestCosts = zeros(MaxIt, 1);
for it=1:MaxIt
for i=1:nPop
particle(i).Velocity = w*particle(i).Velocity ...
+ c1*rand(VarSize).*(particle(i).Best.Position - particle(i).Position) ...
+ c2*rand(VarSize).*(GlobalBest.Position - particle(i).Position);
particle(i).Velocity = max(particle(i).Velocity, MinVelocity);
particle(i).Velocity = min(particle(i).Velocity, MaxVelocity);
particle(i).Position = particle(i).Position + particle(i).Velocity;
particle(i).Position = max(particle(i).Position, VarMin);
particle(i).Position = min(particle(i).Position, VarMax);
particle(i).Cost = CostFunction(particle(i).Position);
if particle(i).Cost < particle(i).Best.Cost
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
end
BestCosts(it) = GlobalBest.Cost;
if ShowIterInfo
disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCosts(it))]);
end
w = w * wdamp;
end
out.pop = particle;
out.BestSol = GlobalBest;
out.BestCosts = BestCosts;
end