close all;
% PopNum Number of Population
% Maxstep the max step of generate
a = rand; u = rand;
pop_bound = [-5 5];% the boundary of population
dim = 2;
% init of population
pop = pop_bound(1)+rand(PopNum,dim)*(pop_bound(2)-pop_bound(1));
% calculate the fitness_value of Pop
pbest = pop;
gbest = zeros(1,dim);
data1 = zeros(Maxstep,PopNum,dim);
data2 = zeros(Maxstep,PopNum);
for i = 1:PopNum
fit(i) = fitness(pop(i,1),pop(i,2));
f_pbest(i) = fit(i);
end
g = min(find(f_pbest == min(f_pbest(1:PopNum))));
gbest = pbest(g,:);
f_gbest = f_pbest(g);
figure;
x=-5:.1:5;[xx,yy]=meshgrid(x,x);
fit_draw = fitness(xx,yy);
mesh(xx,yy,fit_draw);
hold on;
%-------- in the loop -------------
for step = 1:Maxstep
mbest =sum(pbest(:))/PopNum;
% linear weigh factor
b = 1-step/Maxstep*0.5;
data1(step,:,:) = pop;
data2(step,:) = fit;
for i = 1:PopNum
a = rand(1,dim); u = rand(1,dim);
p = a.*pbest(i,:)+(1-a).*gbest;
pop(i,:) = p + b*abs(mbest-pop(i,:)).*...
log(1./u).*(1-2*(u >= 0.5));
% boundary detection
pop(i,:) = pop(i,:)+(-5-pop(i,:)).*(pop(i,:)<-5)...
+(5-pop(i,:)).*(pop(i,:)>5);
fit(i) = fitness(pop(i,1),pop(i,2));
if fit(i) < f_pbest(i)
pbest(i,:) = pop(i,:);
f_pbest(i) = fit(i);
end
if f_pbest(i) < f_gbest
gbest = pbest(i,:);
f_gbest = f_pbest(i);
end
end
end
gbest(1),gbest(2)
fit=fitness(gbest(1),gbest(2))
% -------- plot_draw -----------
for i=1
plot3(data1(:,i,1),data1(:,i,2),data2(:,i),'*');
hold on;
end
hold off
end
function fit=fitness(x,y)
%yout=-sin(x).*(sin(x.^2/pi)).^20-sin(y).*(sin(2*y.^2/pi)).^20;
fit=0.5+(sin(sqrt(x.^2+y.^2)).^2-0.5)./(1+0.001*(x.^2+y.^2)).^2;
end