版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangguangdblu/article/details/78837245
%%%%%免疫算法TSP问题%%%%
%%%%%初始化参数%%%%%
clear all; %清除所有变量
close all; %清图
clc; %清屏
C=[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(C,1); %城市数目,基因数目
D=zeros(N); %任意两个城市距离矩阵
NP=100; %免疫个体数目
G=1000; %最大免疫代数
Pc=0.1; %交叉率
f=zeros(N,NP); %中间变量
len=zeros(NP,1);
%%%%%求间距%%%%%
for i=1:N
for j=1:N
D(i,j)=((C(i,1)-C(j,1))^2+(C(i,2)-C(j,2))^2)^0.5;
end
end
%%%%%随机生成第一代%%%%%
for i=1:NP
f(:,i)=randperm(N);
end
%%%%%计算路径长度%%%%%
for i=1:NP
len(i)=func3(D,f(:,i),N);
end
[Sortlen,Index]=sort(len);
Sortf=f(:,Index);
Ncl=10; %克隆个数
%%%%%遗传算法循环%%%%%
for gen=1:G
for i=1:NP/2
%%%%%选择操作%%%%%
a=Sortf(:,i);
Ca=repmat(a,1,Ncl);
for j=1:Ncl
p1=floor(1+N*rand());
p2=floor(1+N*rand());
while p1==p2
p1=floor(1+N*rand());
p2=floor(1+N*rand());
end
tmp=Ca(p1,j);
Ca(p1,j)=Ca(p2,j);
Ca(p2,j)=tmp;
end
Ca(:,1)=Sortf(:,i);
%%%%%克隆抑制%%%%%
for j=1:Ncl
Calen(j)=func3(D,Ca(:,j),N);
end
[SortCalen,Index]=sort(Calen);
SortCa=Ca(:,Index);
af(:,i)=SortCa(:,1);
alen(i)=SortCalen(1);
end
%%%%%种群刷新%%%%%
for i=1:NP/2
bf(:,i)=randperm(N);
blen(i)=func3(D,bf(:,i),N);
end
%%%%%免疫种群与新种群合并%%%%%
f=[af,bf];
len=[alen,blen];
[Sortlen,Index]=sort(len);
Sortf=f(:,Index);
trace(gen)=Sortlen(1);
end
%%%%%输出最优化结果%%%%%
fBest=Sortf(:,1);
Bestlen=trace(end);
figure
for i=1:N-1
plot([C(fBest(i),1),C(fBest(i+1),1)],[C(fBest(i),2),C(fBest(i+1),2)],'bo-')
hold on
end
plot([C(fBest(N),1),C(fBest(1),1)],[C(fBest(N),2),C(fBest(1),2)],'bo-')
title(['最优化距离',num2str(Bestlen)]);
figure
plot(trace)
xlabel('迭代次数')
ylabel('目标函数值')
title('亲和度进化曲线')
%%%%%计算路径总长度的函数%%%%%
function len=func3(D,f,N)
len=D(f(N),f(1));
for i=1:(N-1)
len=len+D(f(i),f(i+1));
end
end