%人工鱼群算法
format long
Visual=2.5;
Step=0.3;
delta=0.618;
N=50;
Try_number=50;
a1=-10;%控制左区间1
b1=10;%控制右区间1
a2=-10;%控制左区间2
b2=10;%控制右区间2
d=[];
U=[];
h=1e-1;
Friend_number=50;
k=1;
m=51;
X1=rand(N,1)*(b1-a1)+a1;
X2=rand(N,1)*(b2-a2)+a2;
X=[X1 X2];%人工鱼数量
for i=1:N
wwww=[X(i,1),X(i,2)];
d(i)=maxf(wwww); %将d的值依次列出来
end
[w,i]=max(d); %w为d的最大值,i为最大值对应的下标即第几条鱼
maxX=[X(i,1),X(i,2)];%初始公告板记录 ,将最大值对应的X赋给maxX
maxY=w;%初始公告板记录
figurex=[];
figurey=[];
figurez=[];
figurex(numel(figurex)+1)=maxX(1);
figurey(numel(figurey)+1)=maxX(2);
figurez(numel(figurez)+1)=maxY;
%plot3(X1,X2,d) %绘制整体图象
hold on;
kkk=0;
while(k<m)
for i=1:N
XX=[X(i,1),X(i,2)];%人工鱼当前状态Xi
nf=0;%领域内鱼个数
Xc=0; %中心位置
for j=1:N %聚群行为开始
XXX=[X(j,1),X(j,2)];
if(norm(XXX-XX)<Visual)%矩阵或向量范数,2阶,元素绝对值的的平方求和,再开方
nf=nf+1;
Xc=Xc+XXX;
end
end
Xc=Xc/nf;%更新中心位置
if((maxf(Xc))>delta*maxf(XX))
XXnext1=XX+rand*Step*(Xc-XX)/norm(Xc-XX);
if(XXnext1(1)>b1)
XXnext1(1)=b1;
end
if(XXnext1(1)<a1)
XXnext1(1)=a1;
end
if(XXnext1(2)>b2)
XXnext1(2)=b2;
end
if(XXnext1(2)<a2)
XXnext1(2)=a2;
end
else
XXnext1=gmjprey(XX,Try_number,Visual,Step);%捕食行为
if(XXnext1(1)>b1)
XXnext1(1)=b1;
end
if(XXnext1(1)<a1)
XXnext1(1)=a1;
end
if(XXnext1(2)>b2)
XXnext1(2)=b2;
end
if(XXnext1(2)<a2)
XXnext1(2)=a2;
end
end%聚群行为结束
%maxX=XX;%追尾行为开始
%maxY=maxf(XX);
for j=1:Friend_number
XXX=[X(j,1),X(j,2)];
if(norm(XXX-XX)<Visual & maxf(XXX)>delta*maxY)
maxX=XXX;
maxY=maxf(XXX);
end
end
if((maxY)>maxf(XX))
XXnext2=XX+rand*Step*(maxX-XX)/norm(maxX-XX);
if(XXnext2(1)>b1)
XXnext2(1)=b1;
end
if(XXnext2(1)<a1)
XXnext2(1)=a1;
end
if(XXnext2(2)>b2)
XXnext2(2)=b2;
end
if(XXnext2(2)<a2)
XXnext2(2)=a2;
end
else
XXnext2 =gmjprey(XX,Try_number,Visual,Step);
if(XXnext2(1)>b1)
XXnext2(1)=b1;
end
if(XXnext2(1)<a1)
XXnext2(1)=a1;
end
if(XXnext2(2)>b2)
XXnext2(2)=b2;
end
if(XXnext2(2)<a2)
XXnext2(2)=a2;
end
end%追尾行为结束
if(maxf(XXnext1)>maxf(XXnext2))
X(i,1)=XXnext1(1);
X(i,2)=XXnext1(2);
else
X(i,1)=XXnext2(1);
X(i,2)=XXnext2(2);
end
end %一次迭代结束
for i=1:N
XXXX=[X(i,1),X(i,2)];
if maxf(XXXX)>maxY
maxY=maxf(XXXX);
maxX=XXXX;
figurex(numel(figurex)+1)=maxX(1);
figurey(numel(figurey)+1)=maxX(2);
figurez(numel(figurez)+1)=maxY;
end
end
U(k)=maxY;
k=k+1; %进入下一次迭代
end
maxX
maxY
figurex
%plot3(figurex,figurey,figurez);
plot(1:m-1,U);
hold on
%plot(figurex,figurey,'r*');
%hold off