优化算法之模拟退火算法

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) ''])

运行结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章