clear
close all;
for nn=1:1:20
Size=30;
CodeL=150;
G=600;
c1=2;
c2=2;
wmax=0.9;
wmin=0.2;
% fevals = 0;
for i=1:1:CodeL
MinX(i)=-600*ones(1);
MaxX(i)=600*ones(1);
end
% Initializing swarm and velocities
for i=1:1:CodeL
x(:,i)=MinX(i)+(MaxX(i)-MinX(i))*rand(Size,1);
end
vel=rand(Size,CodeL);
for i=1:1:Size
F(i)=0;
F1(i)=0;
F2(i)=1;
for j=1:1:CodeL
F1(i)=F1(i)+(1/4000)*(x(i,j)^2);
end
for j=1:1:CodeL
F2(i)=F2(i)*cos(x(i,j)/sqrt(j));
end
F(i)=F1(i)-F2(i)+1;
end
pbest=x;
F_1=F;
[Bestfi,Indexfi]=min(F); % Bestfi is equal to min(F), Indexfi is the located number
for kg=1:1:G
time(kg)=kg;
for i=1:1:Size
gbest(i,:)=pbest(Indexfi,:);
end
R1=rand(Size,CodeL);
R2=rand(Size,CodeL);
w=wmax-((wmax-wmin)/G)*kg;
vel=w*vel+c1*R1.*(pbest-x)+c2*R2.*(gbest-x);% vel=rand(Size,CodeL);Structure is 30*10,
for i=1:1:Size
for j=1:1:CodeL
if vel(i,j)>0&abs(vel(i,j))>=0.2*(MaxX(j)-MinX(j))
vel(i,j)=0.2*(MaxX(j)-MinX(j));
end
if vel(i,j)<0&abs(vel(i,j))>=0.2*(MaxX(j)-MinX(j))
vel(i,j)=-0.2*(MaxX(j)-MinX(j));
end
end
end
x=x+vel;
for i=1:1:Size
for j=1:1:CodeL
if x(i,j)>=MaxX(j)
x(i,j)=MaxX(j);
end
if x(i,j)<=MinX(j)
x(i,j)=MinX(j);
end
end
end
for i=1:1:Size
F(i)=0;
F1(i)=0;
F2(i)=1;
for j=1:1:CodeL
F1(i)=F1(i)+(1/4000)*(x(i,j)^2);
end
for j=1:1:CodeL
F2(i)=F2(i)*cos(x(i,j)/sqrt(j));
end
F(i)=F1(i)-F2(i)+1;
end
changeColumns=F<F_1; % F_1 is former fittness;F is the new fittness
F_1=F_1.*(1-changeColumns)+F.*changeColumns;% when changeColumns is 1,the F is larger;otherwise...
pbest(find(changeColumns),:)=x(find(changeColumns),:);
[Bestfi,Indexfi]=min(F_1); % Updating index Indexfi
bfi(kg)=Bestfi;
end
BestS=pbest(Indexfi,:);
Bestfi=F_1(Indexfi)
eval(['save data',num2str(nn),'.mat bfi'])
clear
clear
clear
end
clear
run=20;
t=600;
for nn=1:1:run
eval(['open data',num2str(nn),'.mat;'])
eval(['data',num2str(nn),'=ans.bfi;'])
end
data=0;
for nn=1:1:run
data=data+eval(['data',num2str(nn)]);
end
data=data/run;
avg=data(t)
for nn=1:1:run
dt(nn)=eval(['data',num2str(nn),'(t)']);
end
sd=std(dt)
time=1:1:t;
plot(time,data)
xlabel('time')
for nn=1:1:run
eval(['delete data',num2str(nn),'.mat;'])
end