旅行商問題,即TSP問題(Travelling Salesman Problem)又譯為旅行推銷員問題、貨郎擔問題,是數學領域中著名問題之一。假設有一個旅行商人要拜訪n個城市,他必須選擇所要走的路徑,路徑的限制是每個城市只能拜訪一次,而且最後要回到原來出發的城市。路徑的選擇目標是要求得的路徑路程為所有路徑之中的最小值。來自百度百科解釋這裡寫連結內容
先寫上模擬退火演算法主幹:

function [SA,mincity]=TPS_SA(T,delta,city0,eps)
% 退火演算法,T為初始溫度,delta為衰減因子,x0為初始值,eps為精度對應於溫度下限,
i=1;
while (T>eps)
       for j=1:100
        city1=Exchange(city0);
        dE=Distance(city1)-Distance(city0);
        if (dE<0)
            city0=city1;%移動後得到優解
        else
            if(exp(dE/T)<rand(1))%以一定概率移動。
                city0=city1;
            end
        end
      end
   T=T*delta;
   i=i+1;
end
SA=Distance(city0);
mincity=city0;
line(mincity(1,:),mincity(2,:),'color','red');

計算城市距離的函式

function distance=Distance(city)
%city=[x1 x2 x3;y1 y2 y3]的對應的城市座標
NumberCity=length(city);
city1=city';
distance=0;
for i=1:NumberCity-1
    distance=distance+pdist(city1(i:i+1,:));
end
if NumberCity>=3
    distance=distance+pdist([city1(1,:);city1(NumberCity,:)]);
end

交換路線0的程式碼:

function city1=Exchange(city0)
NumberCity=length(city0);
n=round((NumberCity-2)*rand(1)+2);%產生(2-NumberCity之間的數)
m=round((NumberCity-2)*rand(1)+2);%產生(2-NumberCity之間的數)
city2=city0(:,m);
city0(:,m)=city0(:,n);
city0(:,n)=city2;
city1=city0;
function main()
T=100;
city0=[0.6606,0.9695,0.5906,0.2124,0.0398,0.1367,0.9536,0.6091,0.8767,0.8148,0.3876,0.7041,0.0213,0.3429,0.7471,0.4606,0.7695,0.5006,0.3124,0.0098,0.3637,0.5336,0.2091,0.4767,0.4148,0.5876,0.6041,0.3213,0.6429,0.7471;     0.9500,0.6740,0.5029,0.8274,0.9697,0.5979,0.2184,0.7148,0.2395,0.2867,0.8200,0.3296,0.1649,0.3025,0.8192,0.6500,0.7420,0.0229,0.7274,0.4697,0.0979,0.2684,0.7948,0.4395,0.8867,0.3200,0.5296,0.3649,0.7025,0.9192];
delta=0.99;
eps=1e-6;
[d,city1]=TPS_SA(T,delta,city0,eps);
d
plot(city1(1,:),city1(2,:),'*');
hold on;
line(city1(1,:),city1(2,:),'color','red');

當然模擬退火演算法不是一定就可以找到最優解,只是近似最優解。計算多次會出現多次值,
如distance=5.8600
此時的這裡寫圖片描述
改變引數也可以改進distance的值,如detal,eps等等。或者利用遺傳演算法與模擬退火演算法結合,求得最優解。