PSO(粒子群)求解TSP(旅行商问题)

PSO(粒子群)求解TSP(旅行商问题)

  PSO求解TSP代码可以参考之前的博客PSO求解TSP。
  但是有时候可能会加一些限制,例如某个城市需要先被访问。这里以城市8要第一个访问,其实只需要每次做完位置更新后,将城市8更换至第一个访问城市即可。

修改

  只需修改初始化和每次更新位置的函数,initpos.mupdatepos.m 文件。

function [ pos ] = initpos( pasize,padim )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% initpos()初始化粒子群
% pasize粒子群大小 padim维度
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    pos =zeros(pasize,padim);         %初始化
    for i = 1:pasize
        t = 2:padim+1;                %生成初始访问
        ranorder = randperm(padim);   %乱序排列
        pos(i,:)=t(ranorder);         %生成粒子
    end

    % change city to the first city
    for i = 1:pasize
        t = find(pos(i,:)==8);    % index of city 8 
        temp = pos(i,t);     % city 8
        pos(i,t) = pos(i,1);
        pos(i,1) = temp;   
    end
    
end
function [ pos ] = updatepos( pos,v )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% updatepos( pos,v )对粒子的位置更新
% pos:位置    v:速度
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[vx,vy] = size(v);     %粒子群维度和大小
for i = 1:vx           %循环每个粒子
    for j =1:vy/2      %对每个交换子运算
        tt = pos(i,v(i,2*j-1)); 
        pos(i,v(i,2*j-1)) = pos(i,v(i,2*j));
        pos(i,v(i,2*j))=tt;  %更新位置
    end
end

    for i = 1:vx
        t = find(pos(i,:)==8);    % index of city 8 
        temp = pos(i,t);     % city 8
        pos(i,t) = pos(i,1);
        pos(i,1) = temp;   
    end 
end

结果

PSO(粒子群)求解TSP(旅行商问题)_第1张图片

"Routing:
     1     8     4     5     6     3     2     7    10     9     1"

源码

    GitHub传送门!!!

你可能感兴趣的:(#,▶,智能算法,PSO,TSP,tsp)