tulun2.m
a= [ 0,50,inf,40,25,10;
50,0,15,20,inf,25;
inf,15,0,10,20,inf;
40,20,10,0,10,25;
25,inf,20,10,0,55;
10,25,inf,25,55,0];
[D, path]=floyd(a)
floyd.m
function [D,path,min1,path1]=floyd(a,start,terminal)
D=a;n=size(D,1);path=zeros(n,n);
for i=1:n
for j=1:n
if D(i,j)~=inf
path(i,j)=j;
end,
end,
end
for k=1:n
for i=1:n
for j=1:n
if D(i,k)+D(k,j)<D(i,j)
D(i,j)=D(i,k)+D(k,j);
path(i,j)=path(i,k);
end,
end,
end,
end
if nargin==3
min1=D(start,terminal);
m(1)=start;
i=1;
path1=[ ];
while path(m(i),terminal)~=terminal
k=i+1;
m(k)=path(m(i),terminal);
i=i+1;
end
m(i+1)=terminal;
path1=m;
end
5. 模拟退火算法
swap.m
function [ newpath , position ]=swap( oldpath , number )% 对 oldpath 进 行 互 换 操 作
% number 为 产 生 的 新 路 径 的 个 数
% position 为 对 应 newpath 互 换 的 位 置
m =length( oldpath );% 城 市 的 个 数
newpath =zeros( number , m );
position =sort(randi( m , number ,2),2);% 随 机 产 生 交 换 的 位 置
for i =1: number
newpath( i ,:)= oldpath ;% 交 换 路 径 中 选 中 的 城 市
newpath( i ,position( i ,1))=oldpath(position( i ,2));newpath( i ,position( i ,2))=oldpath(position( i ,1));
end
pathfare.m
function [ objval ]=pathfare( fare , path )% 计 算 路 径 path 的 代 价 objval
% path 为 1 到 n 的 排 列 ,代 表 城 市 的 访 问 顺 序 ;
% fare 为 代 价 矩 阵 , 且 为 方 阵 。
[ m , n ]=size( path );
objval =zeros(1, m );for i =1: m
for j =2: n
objval( i )=objval( i )+fare(path( i , j -1),path( i , j ));
end
objval( i )=objval( i )+fare(path( i , n ),path( i ,1));
end
distance.m
function [ fare ]=distance( coord )% 根 据 各 城 市 的 距 离 坐 标 求 相 互 之 间 的 距 离
% fare 为 各 城 市 的 距 离 , coord 为 各 城 市 的 坐 标
[ v , m ]=size( coord );% m 为 城 市 的 个 数
fare =zeros( m );for i =1: m % 外 层 为 行
for j = i : m % 内 层 为 列
fare( i , j )=(sum((coord(:, i )-coord(:, j )).^2))^0.5;fare( j , i )=fare( i , j );% 距 离 矩 阵 对 称
end
end
myplot.m
function []=myplot( path , coord , pathfar )% 做 出 路 径 的 图 形
% path 为 要 做 图 的 路 径 ,coord 为 各 个 城 市 的 坐 标
% pathfar 为 路 径 path 对 应 的 费 用
len =length( path );
clf ;
hold on ;title(['近似最短路径如下,路程为',num2str( pathfar )]);plot(coord(1,:),coord(2,:),'ok');pause(0.4);for ii =2: len
plot(coord(1,path([ ii -1, ii ])),coord(2,path([ ii -1, ii ])),'-b');
x =sum(coord(1,path([ ii -1, ii ])))/2;
y =sum(coord(2,path([ ii -1, ii ])))/2;text( x , y ,['(',num2str( ii -1),')']);pause(0.4);
end
plot(coord(1,path([1, len