clc;
clear;
close all;
CostFunction = @(x) Sphere(x);
nVar = 5;
VarSize = [1 nVar];
VarMin = -10;
VarMax = 10;
MaxIt = 100;
nPop = 50;
wdamp = 0.99;
w = 1;
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).Postion = particle(i).Position + particle(i).Velocity;
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;
disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCosts(it))]);
w = w * wdamp;
end
figure;
plot(BestCosts, 'LineWidth', 2);
xlabel('Iteration');
ylabel('Best Cost');
grid on;