clear all;clc;close all
%模擬退火算法求解旅行商問題
%{
日期:
20190912_ZD
%}
t0 = clock;%計時
Inter = 1;%迭代次數初始化
a = 0.99;%溫度衰減係數
Ts = 120;%初始溫度
Te = 1;%截止溫度
T = Ts;
Markov = 1000;%Markov鏈長度
C = [1,2;70,90;80,60;10,100;800,200;800,100;90,80;200,600;230,4;500,90];
N = size(C,1);
D = zeros(N,N);
%計算各個城市之間的距離
for i = 1:N
for j = 1:N
D(i,j) = sqrt( sum((C(i,:) - C(j,:) ).^2));
end
end
%隨機生成路徑
Route = randperm(N);
Route_new = [];
BestLength = inf;
BestRoute = [];
Length = inf;
%模擬退火過程
while T>= Te
for j = 1:Markov
%產生新路徑
ind1 = (ceil(rand*10));
ind2 = (ceil(rand*10));
%交換兩個索引位置的城市座標
tmp = Route(ind1);
Route(ind1) = Route(ind2);
Route(ind2) = tmp;
Route_new = Route;
%計算路徑距離
Length_new = 0;
Route_new1 = [Route_new,Route_new(1)];
for i = 1:N
Length_new = Length_new + D(Route_new1(i),Route_new1(i+1));
end
%判斷路徑長度
if Length_new < Length
Route = Route_new;
Length = Length_new;
if Length < BestLength
BestLength = Length;
BestRoute = Route;
Inter = Inter + 1;
end
else
%一定概率選擇較差的解
if rand < exp(-(Length_new - Length) / T)
Route = Route_new;
Length = Length_new;
end
end
end
T = T*a;
end
%顯示結果
time = etime(clock,t0);
disp('計算時間爲:')
disp(time)
RouteFinal = [BestRoute,BestRoute(1)];
plot([C(RouteFinal,1)],[C(RouteFinal,2)],'Linewidth',3,'Marker','o','MarkerSize',10);
disp('最優路徑爲:')
disp(BestRoute)
disp('最短路徑爲:')
disp(BestLength)
for i = 1:N
text(C(i,1),C(i,2),[' ',num2str(i)]);
end
xlabel('城市位置橫座標')
ylabel('城市位置縱座標')
title(['模擬退火算法(最短距離):' num2str(BestLength) ''])
運行結果: