clc
clear
close all
Npar = 3;
VarLow=[-5.12 -5.12 -5.12];
VarHigh = [5.12 5.12 5.12];
N=100;
MaxIter=100;
XBest = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
FBest=fitnessFunc(XBest);
GB=FBest;
t = cputime;
X = zeros(N, Npar);
F = zeros(N, 1);
for ii = 1:N
X(ii,:) = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
F(ii) = fitnessFunc(X(ii,:));
end
for it=1:MaxIter
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
den=sum(1./F);
Xc=num/den;
for ii=1:N
for jj=1:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
New=limiter(New,VarHigh,VarLow);
newFit=fitnessFunc(New);
if newFit<F(ii)
X(ii,:)=New;
F(ii)=newFit;
if F(ii)<FBest
XBest=X(ii,:);
FBest=F(ii);
end
end
end
GB=[GB FBest];
end
t1=cputime;
fprintf('The time taken is %3.2f seconds \n',t1-t);
fprintf('The best value is :');
XBest
FBest
figure(1)
plot(0:MaxIter,GB, 'linewidth',1.2);
title('Convergence');
xlabel('Iterations');
ylabel('Objective Function (Cost)');
grid('on')
function newP=limiter(P,VarHigh,VarLow)
newP=P;
for i=1:length(P)
if newP(i)>VarHigh(i)
newP(i)=VarHigh(i);
else
if newP(i)<VarLow(i)
newP(i)=VarLow(i);
end
end
function fitness = fitnessFunc(x)
fitness = x(1)^2 - 10*cos(2*pi*x(1)) + 10;
fitness= fitness+ x(2)^2 - 10*cos(2*pi*x(2)) + 10;
fitness= fitness+ x(3)^2 - 10*cos(2*pi*x(3)) + 10;
end