create.m

来自「本文以著名的旅行商问题(TSP)为例说明如何利用MATLAB语言实现模拟退火算法」· M 代码 · 共 57 行

M
57
字号
%状态产生函数

solution_temp=solution;     %复制临时解路径


if rand<0.5
    %=====================================================
    %解路径反转
    for i=1:round(city_n/2)
        temp=solution(i);
        solution(i)=solution(city_n-i+1);
        solution(city_n-i+1)=temp;
    end
else
    %=====================================================
    %局部路径调整
    pos_a=round(26*rand)+2;
    pos_b=round(26*rand)+2;
    
    left=min(pos_a,pos_b);
    right=max(pos_a,pos_b);

    for i=left:right
        temp=solution_temp(i);
        solution_temp(i)=solution_temp(city_n-i+1);
        solution_temp(city_n-i+1)=temp;
    end
end



%=====================================================
%最近邻调整
for j=1:2:(city_n-1)
    near_pos=round(2*rand)+1;   %随机选择最近邻表中的某一城市序号
    near_city=neighbor_table(solution_temp(j),near_pos);   %选择最近邻表中的某一城市
    for h=1:city_n
        if solution_temp(h)==near_city
            temp=solution_temp(h);
            solution_temp(h)=solution_temp(j+1);
            solution_temp(j+1)=temp;
            break;
        end
    end
end


clear i;
clear j;
clear h;
clear temp;
clear near_pos;
clear near_city;
clear pos_a;
clear pos_b;
clear left;
clear right;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?