蚁群优化算法matlab实现
主函数:
clear
clc
m=5;%种群规模
[pop,pheromone]=initialization(m)%分别求出初始矩阵与信息素
antfirstcity=firstcity(m)%每只蚂蚁随机选择出发的城市
antcity=lectcity(pop,m,pheromone,antfirstcity)%每只蚂蚁每⼀步选择的城市
newpheromone=newpheromones(m,antcity,pop,pheromone)%更新信息素
函数initialization:
function[pop,pheromone]=initialization(m)
pop=[inf,3,1,2;3,inf,5,4;1,5,inf,2;2,4,2,inf];
newpop=pop;
f=ones(1,5);
c=0;
n=2;
i=1;
whilen<5
[min_newpop,index]=min(newpop,[],2);
j=index(i);
c=c+min_newpop(i);
f(n)=j;
newpop(i,:)=inf;
newpop(:,i)=inf;
i=j;
n=n+1;
end
c=c+pop(i,1);
pheromone=m/c;
pheromone=ones(4,4)*pheromone;
函数firstcity:
functionantfirstcity=firstcity(m)
city=['A','B','C','D'];
antfirstcity=char(zeros(1,m));
fori=1:m
ran=rand();
ifran<0.25
antfirstcity(i)=city(1);
elifran<0.5
antfirstcity(i)=city(2);
elifran<0.75
antfirstcity(i)=city(3);
el
antfirstcity(i)=city(4);
end
end
函数lectcity:
functionantcity=lectcity(pop,m,pheromone,antfirstcity)
antcity=char(zeros(m,5));
antcity(:,1)=antfirstcity;
antcity(:,5)=antfirstcity;
fori=1:m
city=['A','B','C','D'];
newcity=city;
forj=2:4
forn=1:6-j
ifnewcity(n)==antfirstcity(i)
newcity(n)=[];
break
end
end
x=antfirstcity(i)-'A'+1;
y(1:5-j)=newcity(1:5-j)-'A'+1;
p1=zeros(1,5-j);
forv=1:5-j
p1(v)=pheromone(x,y(v))*(1/pop(x,y(v)))^2;
end
p=p1/sum(p1);
q=rand();
ifj==2
ifq
antcity(i,2)=newcity(1);
antfirstcity(i)=newcity(1);
elifq
antcity(i,2)=newcity(2);
antfirstcity(i)=newcity(2);
el
antcity(i,2)=newcity(3);
antfirstcity(i)=newcity(3);
end
elifj==3
ifq
antcity(i,3)=newcity(1);
antfirstcity(i)=newcity(1);
el
antcity(i,3)=newcity(2);
antfirstcity(i)=newcity(2);
end
el
antcity(i,4)=newcity(1);
antfirstcity(i)=newcity(1);
end
end
end
函数newpheromones:
functionnewpheromone=newpheromones(m,antcity,pop,pheromone)
num=zeros(m,5);
num(:)=antcity(:)-'A'+1;
c=zeros(m,1);
forr=1:m
fort=1:4
c(r)=c(r)+pop(num(r,t),num(r,t+1));
end
end
formm=1:4
fornn=1:4
sumnum=0;
fori=1:m
forj=1:4
ifnum(i,j)==mm
ifnum(i,j+1)-num(i,j)==nn-mm;
sumnum=sumnum+1/c(i);
end
end
end
end
newpheromone(mm,nn)=0.5*pheromone(mm,nn)+sumnum;
end
end
本文发布于:2022-12-27 20:17:28,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/90/42411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |