资源描述:
《蚁群算法求函数最大值的程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、function[maxx,maxy,maxvalue]=antcolony%蚁群算法求函数最大值的程序%%%%%%%%%%%%%%%%%%%%%%%%%%%初始化ant=200;%蚂蚁数量times=50;%蚂蚁移动次数rou=0.8;%信息素挥发系数p0=0.2;%转移概率常数lower_1=-1;%设置搜索范围upper_1=1;%lower_2=-1;%upper_2=1;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%fori=1:antX(i,1)=(lower_1+(upper_1-lower_1)*rand);%随机设置蚂蚁的初值位置X(i,2)=(lower
2、_2+(upper_2-lower_2)*rand);tau(i)=F(X(i,1),X(i,2));endstep=0.05;f='-(x.^2+2*y.^2-0.3*cos(3*pi*x)-0.4*cos(4*pi*y)+0.7)';[x,y]=meshgrid(lower_1:step:upper_1,lower_2:step:upper_2);z=eval(f);figure(1);mesh(x,y,z);holdon;plot3(X(:,1),X(:,2),tau,'k*')holdon;text(0.1,0.8,-0.1,'蚂蚁的初始分部位置')xlabel('x');yl
3、abel('y');zlabel('f(x,y)');fort=1:timeslamda=1/t;[tau_best(t),bestindex]=max(tau);fori=1:antp(t,i)=(tau(bestindex)-tau(i))/tau(bestindex);%计算状态转移概率endfori=1:antifp(t,i)4、,2)+(upper_2-lower_2)*(rand-0.5);end%%%%%%%%%%%%%%%%%%%%%%越界处理iftemp1upper_1temp1=upper_1;endiftemp2upper_2temp2=upper_2;end%%%%%%%%%%%%%%%%%%%%%%%ifF(temp1,temp2)>F(X(i,1),X(i,2))%判断蚂蚁是否移动X(i,1)=temp1;X(i,2)=temp2;endendfori=1:an
5、ttau(i)=(1-rou)*tau(i)+F(X(i,1),X(i,2));%更新信息量endendfigure(2);mesh(x,y,z);holdon;x=X(:,1);y=X(:,2);plot3(x,y,eval(f),'k*')holdon;text(0.1,0.8,-0.1,'蚂蚁的最终分布位置')xlabel('x');ylabel('y'),zlabel('f(x,y)');[max_value,max_index]=max(tau);maxx=X(max_index,1);maxy=X(max_index,2);maxvalue=F(X(max_index,1)
6、,X(max_index,2));function[F]=F(x1,x2)%目标函数F=-(x1.^2+2*x2.^2-0.3*cos(3*pi*x1)-0.4*cos(4*pi*x2)+0.7);