matlab GA解决TSP问题
借鉴 智能优化算法及其MATLAB实例(第2版),纯手敲怕大家麻烦,并且将其选择过程实时可视化。
代码如下:
clc;clear
city=[1304 2312;3639 1315;4177 2244;3712 1399;3488 1535;3326 1556;...
3238 1229;4196 1044;4312 790;4386 570;3007 1970;2562 1756;...
2788 1491;2381 1676;1332 695;3715 1678;3918 2179;4061 2370;...
3780 2212;3676 2578;4029 2838;4263 2931;3429 1908;3507 2376;...
3394 2643;3439 3201;2935 3240;3140 3550;2545 2357;2778 2826;2370 2975];
N=size(city,1);%获取有多少个城市
Distance=zeros(N);%距离矩阵
%%%%%%%%%%%%%%%%%%%%%%%%求任意两城市之间的距离%%%%%%%%%%%%
for i=1:N
for j=1:N
Distance(i,j)=((city(i,1)-city(j,1))^2+(city(i,2)-city(j,2))^2)^0.5;
end
end
NP=200;%种群大小
G=2000;%遗传代数
L=N;%编码长度
f=zeros(NP,L);%建立种群
F=[];
for i=1:NP
f(i,:)=randperm(L);
end
R=f(1,:);%储存最优种群
len=zeros(NP,1);%存储每个走法的路径长度
fitness=zeros(NP,1);%储存归一化适应度值
for gen=1:G
for i=1:NP
len(i,1)=Distance(f(i,N),f(i,1));%计算序列中最后一个城市到第一个城市的路劲长度
for j=1:(L-1)
len(i,1)=len(i,1)+Distance(f(i,j),f(i,j+1));
end
end
max_len=max(len);%最长路径
min_len=min(len);%最短路径
rr=find(len==min_len);%获取最短路径的索引
R=f(rr(1,1),:);%保存最优个体
%%%%%%%%%%%%%%%%%%%%%%%%%%%归一化适应度值%%%%%%%%%%%%%%%%%%%%%
for i=1:length(len)
fitness(i,1)=(1-((len(i,1)-min_len)/(max_len-min_len+0.001)));%极小型用1-(n-min)/(max-min)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%选择个体%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nn=0;
for i=1:NP
if fitness(i,1)>=rand
nn=nn+1;
F(nn,:)=f(i,:);%此时将个体赋值给中间种群
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%交叉%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[aa,bb]=size(F);
while aa<NP%aa小于种群时执行交叉(保证种群数不超过NP)
nnper=randperm(nn);%可以让个体之间随机交叉
%%%%每次取序列前两个进行交叉%%
A=F(nnper(1),:);
B=F(nnper(2),:);
%%%%%进行交叉%%%%%%%%%%%%
w=ceil(L/10);%%交叉点个数%%%%
p=unidrnd(N-w+1);%随机选择交叉范围p 到 p+w-1
for i=1:w
x=find(A==B(p+i-1));
y=find(B==A(p+i-1));
temp=A(p+i-1);
A(p+i-1)=B(p+i-1);
B(p+i-1)=temp;
temp=A(x);
A(x)=B(y);
B(y)=temp;
end
%%%%%%%%%%%%%%%%%%%%%%%%变异操作%%%%%%%%%%%%%%%%%%%%%%%%
p1=floor(1+N*rand());
p2=floor(1+N*rand());
while p1==p2
p1=floor(1+N*rand());
p2=floor(1+N*rand());
end
temp=A(p1);
A(p1)=A(p2);
A(p2)=temp;
tmp=B(p1);
B(p1)=B(p2);
B(p2)=tmp;
F=[F;A;B];%将交叉变异个体加入新种群
[aa,bb]=size(F);%上一步种群进行了更新
end
% for i = 1:NP
% index = floor(rand*NP);
% if index == 0
% index = 1;
% end
% NewF(i,:) = F(index,:);
% end
if aa>NP
F=F(1:NP,:);
end
f=F;
f(1,:)=R;
disp(gen)
clear F;
Rlength(gen)=min_len;
%% Draw
subplot(1,2,1);
for i=1:N-1
plot([city(R(i),1),city(R(i+1),1)],[city(R(i),2),city(R(i+1),2)],'bo-');
hold on
end
plot([city(R(N),1),city(R(1),1)],[city(R(N),2),city(R(1),2)],'ro-');
title(['优化最短距离:',num2str(min_len)]);
hold off;
subplot(1,2,2);
plot(Rlength)
xlabel('迭代次数');
ylabel('目标函数值');
title('适应度进化曲线')
pause(0.001);
end
随便截取了运行时的画面