VarMin=-10;
VarMax=10;
Nvar=20;
FunNumber=1;
CostFunction=@(x) FunCost(x,1);
VarSize=[1 Nvar];
MaxIt=100;
k=2;
n=50;
NPop=k*n;
alpha=0.6;
betha=0.4;
W=1;
Q=0.5;
EmptyFarmland.Position=[];
EmptyFarmland.Cost=inf;
pop=repmat(EmptyFarmland,NPop,1);
for i=1:NPop
pop(i).Position=unifrnd(VarMin,VarMax,VarSize);
pop(i).Cost=CostFunction(pop(i).Position);
end
RandIdx=randsample(NPop,NPop);
Section=cell(1,k);
for s=1:k
aj=n*(s-1)+1:n*s;
Section{s}.Pop=pop(RandIdx(aj));
Section{s}.LocalMem=[];
end
BestSol.Cost=inf;
BestSol.Position=[];
BestCost=zeros(MaxIt,1);
for It=1:MaxIt
FitSection=inf(1,k);
for s=1:k
FitSection(s)=mean([Section{s}.Pop.Cost]);
end
t=0.02;
CLocal=round(t*n);
Section=UpdateLocalMem(Section,k,CLocal);
CGlobal=round(t*NPop);
GlobalMem=repmat(EmptyFarmland,CGlobal,1);
[GlobalMem,PopMain,CostMain]=FindGlobalSoultion(Section,Nvar,n,CGlobal,GlobalMem);
[~,idx]=max(FitSection);
for s=1:k
if (s==idx)
for i=1:n
h=alpha*unifrnd(-1,+1,VarSize);
Xij=Section{s}.Pop(i).Position;
XGlobal=GlobalMem(randi([1 CGlobal],1)).Position;
Xnew=h.*(Xij-XGlobal)+Xij;
Xnew=max(Xnew,VarMin);
Xnew=min(Xnew,VarMax);
FitNew=CostFunction(Xnew);
if(FitNew<=Section{s}.Pop(i).Cost)
Section{s}.Pop(i).Position=Xnew;
Section{s}.Pop(i).Cost=FitNew;
end
end
else
for i=1:n
h=betha*unifrnd(-1,1,VarSize);
Xij=Section{s}.Pop(i).Position;
Xuj=PopMain(randi([1 NPop],1),:);
Xnew=h.*(Xij-Xuj)+Xij;
Xnew=max(Xnew,VarMin);
Xnew=min(Xnew,VarMax);
FitNew=CostFunction(Xnew);
if(FitNew<=Section{s}.Pop(i).Cost)
Section{s}.Pop(i).Position=Xnew;
Section{s}.Pop(i).Cost=FitNew;
end
end
end
end
Section=UpdateLocalMem(Section,k,CLocal);
W=W*0.1;
for s=1:k
for i=1:n
if(Q>rand)
Xij=Section{s}.Pop(i).Position;
b=randi([1 CGlobal],1);
XGlobal=GlobalMem(b).Position;
Xnew=unifrnd(-1,+1,VarSize).*(Xij-XGlobal)+Xij;
Xnew=max(Xnew,VarMin);
Xnew=min(Xnew,VarMax);
FitNew=CostFunction(Xnew);
if(FitNew<=Section{s}.Pop(i).Cost)
Section{s}.Pop(i).Position=Xnew;
Section{s}.Pop(i).Cost=FitNew;
end
else
Xij=Section{s}.Pop(i).Position;
b=randi([1 CLocal],1);
idxlocal=Section{s}.LocalMem(b);
XLocal=Section{s}.Pop(idxlocal).Position;
Xnew=unifrnd(-1,+1,VarSize).*(Xij-XLocal)+Xij;
Xnew=max(Xnew,VarMin);
Xnew=min(Xnew,VarMax);
FitNew=CostFunction(Xnew);
if(FitNew<=Section{s}.Pop(i).Cost)
Section{s}.Pop(i).Position=Xnew;
Section{s}.Pop(i).Cost=FitNew;
end
end
end
end
GlobalFind=FindGlobalSoultion(Section,Nvar,n,CGlobal,GlobalMem);
if(GlobalFind(1).Cost<BestSol.Cost)
BestSol.Cost=GlobalFind(1).Cost;
BestSol.Position=GlobalFind(1).Position;
end
BestCost(It)=BestSol.Cost;
disp(['Iteration ' num2str(It) ': Best Cost = ' num2str(BestCost(It))]);
end
minresult=BestCost(end);
if(1)
plot(BestCost,'k-','LineWidth',1);
end