用MATLAB实现中国旅行商问题的求解

合集下载

旅行商问题matlab源代码

旅行商问题matlab源代码

function [pTS,fmin]=grTravSale(C)% Function [pTS,fmin]=grTravSale(C) solve the nonsymmetrical% traveling salesman problem.% Input parameter:% C(n,n) - matrix of distances between cities,% maybe, nonsymmetrical;% n - number of cities.% Output parameters:% pTS(n) - the order of cities;% fmin - length of way.% Uses the reduction to integer LP-problem:% Look: Miller C.E., Tucker A. W., Zemlin R. A.% Integer Programming Formulation of Traveling Salesman Problems. % J.ACM, 1960, Vol.7, p. 326-329.% Needed other products: MIQP.M.% This software may be free downloaded from site:% http://control.ee.ethz.ch/~hybrid/miqp/% Author: Sergiy Iglin% e-mail: siglin@yandex.ru% personal page: http://iglin.exponenta.ru% ============= Input data validation ==================if nargin<1,error('There are no input data!')endif ~isnumeric(C),error('The array C must be numeric!')endif ~isreal(C),error('The array C must be real!')ends=size(C); % size of array Cif length(s)~=2,error('The array C must be 2D!')endif s(1)~=s(2),error('Matrix C must be square!')endif s(1)<3,error('Must be not less than 3 cities!')end% ============ Size of problem ====================n=s(1); % number of vertexesm=n*(n-1); % number of arrows% ============ Parameters of integer LP problem ========Aeq=[]; % for the matrix of the boundary equationsfor k1=1:n,z1=zeros(n);z1(k1,:)=1;z2=[z1;eye(n)];Aeq=[Aeq z2([1:2*n-1],setdiff([1:n],k1))];endAeq=[Aeq zeros(2*n-1,n-1)];A=[]; % for the matrix of the boundary inequationsfor k1=2:n,z1=[];for k2=1:n,z2=eye(n)*(n-1)*(k2==k1);z1=[z1 z2(setdiff([2:n],k1),setdiff([1:n],k2))];endz2=-eye(n);z2(:,k1)=z2(:,k1)+1;A=[A;[z1 z2(setdiff([2:n],k1),2:n)]];endbeq=ones(2*n-1,1); % the right parts of the boundary equations b=ones((n-1)*(n-2),1)*(n-2); % the right parts of the boundary inequationsC1=C'+diag(ones(1,n)*NaN);C2=C1(:);c=[C2(~isnan(C2));zeros(n-1,1)]; % the factors for objective functionvlb=[zeros(m,1);-inf*ones(n-1,1)]; % the lower boundsvub=[ones(m,1);inf*ones(n-1,1)]; % the upper boundsH=zeros(n^2-1); % Hessian% ============= We solve the MIQP problem ========== [xmin,fmin]=MIQP(H,c,A,b,Aeq,beq,[1:m],vlb,vub);% ============= We return the results ==============eik=round(xmin(1:m)); % the arrows of the waye1=[zeros(1,n-1);reshape(eik,n,n-1)];e2=[e1(:);0]; % we add zero to a diagonale3=(reshape(e2,n,n))'; % the matrix of the waypTS=[1 find(e3(1,:))]; % we build the waywhile pTS(end)>1, % we add the city to the waypTS=[pTS find(e3(pTS(end),:))];endreturn。

多旅行商问题的matlab程序

多旅行商问题的matlab程序

多旅行商问题的m a t l a b程序Document serial number【NL89WT-NY98YT-NC8CB-NNUUT-NUT108】%多旅行商问题的m a t l a b程序function varargout =mtspf_ga(xy,dmat,salesmen,min_tour,pop_size,num_iter,show_prog,show_r es)% MTSPF_GA Fixed Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA)% Finds a (near) optimal solution to a variation of the M-TSP by setting% up a GA to search for the shortest route (least distance needed for% each salesman to travel from the start location to individual cities% and back to the original starting place)%% Summary:% 1. Each salesman starts at the first point, and ends at thefirst% point, but travels to a unique set of cities in between% 2. Except for the first, each city is visited by exactly one salesman%% Note: The Fixed Start/End location is taken to be the first XY point%% Input:% XY (float) is an Nx2 matrix of city locations, where N is the number of cities% DMAT (float) is an NxN matrix of city-to-city distances or costs% SALESMEN (scalar integer) is the number of salesmen to visit the cities% MIN_TOUR (scalar integer) is the minimum tour length for any of the% salesmen, NOT including the start/end point% POP_SIZE (scalar integer) is the size of the population (should be divisible by 8)% NUM_ITER (scalar integer) is the number of desired iterations for the algorithm to run% SHOW_PROG (scalar logical) shows the GA progress if true% SHOW_RES (scalar logical) shows the GA results if true%% Output:% OPT_RTE (integer array) is the best route found by the algorithm% OPT_BRK (integer array) is the list of route break points (these specify the indices% into the route used to obtain the individual salesman routes)% MIN_DIST (scalar float) is the total distance traveled by the salesmen%% Route/Breakpoint Details:% If there are 10 cities and 3 salesmen, a possible route/break% combination might be: rte = [5 6 9 4 2 8 10 3 7], brks = [3 7] % Taken together, these represent the solution [1 5 6 9 1][1 4 2 8 1][1 10 3 7 1],% which designates the routes for the 3 salesmen as follows:% . Salesman 1 travels from city 1 to 5 to 6 to 9 and back to 1% . Salesman 2 travels from city 1 to 4 to 2 to 8 and back to 1% . Salesman 3 travels from city 1 to 10 to 3 to 7 and back to 1%% 2D Example:% n = 35;% xy = 10*rand(n,2);% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid(1:n);% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);% [opt_rte,opt_brk,min_dist] =mtspf_ga(xy,dmat,salesmen,min_tour, ...% pop_size,num_iter,1,1);%% 3D Example:% n = 35;% xyz = 10*rand(n,3);% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid(1:n);% dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);% [opt_rte,opt_brk,min_dist] =mtspf_ga(xyz,dmat,salesmen,min_tour, ...% pop_size,num_iter,1,1);%% See also: mtsp_ga, mtspo_ga, mtspof_ga, mtspofs_ga, mtspv_ga, distmat%% Author: Joseph Kirk% Email% Release:% Release Date: 6/2/09% Process Inputs and Initialize Defaultsnargs = 8;for k = nargin:nargs-1switch kcase 0xy = 10*rand(40,2);case 1N = size(xy,1);a = meshgrid(1:N);dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N); case 2salesmen = 5;case 3min_tour = 2;case 4pop_size = 80;case 5num_iter = 5e3;case 6show_prog = 1;case 7show_res = 1;otherwiseendend% Verify Inputs[N,dims] = size(xy);[nr,nc] = size(dmat);if N ~= nr || N ~= ncerror('Invalid XY or DMAT inputs!')endn = N - 1; % Separate Start/End City% Sanity Checkssalesmen = max(1,min(n,round(real(salesmen(1)))));min_tour = max(1,min(floor(n/salesmen),round(real(min_tour(1))))); pop_size = max(8,8*ceil(pop_size(1)/8));num_iter = max(1,round(real(num_iter(1))));show_prog = logical(show_prog(1));show_res = logical(show_res(1));% Initializations for Route Break Point Selectionnum_brks = salesmen-1;dof = n - min_tour*salesmen; % degrees of freedomaddto = ones(1,dof+1);for k = 2:num_brksaddto = cumsum(addto);endcum_prob = cumsum(addto)/sum(addto);% Initialize the Populationspop_rte = zeros(pop_size,n); % population of routespop_brk = zeros(pop_size,num_brks); % population of breaksfor k = 1:pop_sizepop_rte(k,:) = randperm(n)+1;pop_brk(k,:) = randbreaks();end% Select the Colors for the Plotted Routesclr = [1 0 0; 0 0 1; 0 1; 0 1 0; 1 0];if salesmen > 5clr = hsv(salesmen);end% Run the GAglobal_min = Inf;total_dist = zeros(1,pop_size);dist_history = zeros(1,num_iter);tmp_pop_rte = zeros(8,n);tmp_pop_brk = zeros(8,num_brks);new_pop_rte = zeros(pop_size,n);new_pop_brk = zeros(pop_size,num_brks);if show_progpfig = figure('Name','MTSPF_GA | Current BestSolution','Numbertitle','off');endfor iter = 1:num_iter% Evaluate Members of the Populationfor p = 1:pop_sized = 0;p_rte = pop_rte(p,:);p_brk = pop_brk(p,:);rng = [[1 p_brk+1];[p_brk n]]';for s = 1:salesmend = d + dmat(1,p_rte(rng(s,1))); % Add Start Distancefor k = rng(s,1):rng(s,2)-1d = d + dmat(p_rte(k),p_rte(k+1));endd = d + dmat(p_rte(rng(s,2)),1); % Add End Distanceendtotal_dist(p) = d;end% Find the Best Route in the Population[min_dist,index] = min(total_dist);dist_history(iter) = min_dist;if min_dist < global_minglobal_min = min_dist;opt_rte = pop_rte(index,:);opt_brk = pop_brk(index,:);rng = [[1 opt_brk+1];[opt_brk n]]';if show_prog% Plot the Best Routefigure(pfig);for s = 1:salesmenrte = [1 opt_rte(rng(s,1):rng(s,2)) 1];if dims == 3, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); endtitle(sprintf('Total Distance = %, Iteration= %d',min_dist,iter));hold onendif dims == 3, plot3(xy(1,1),xy(1,2),xy(1,3),'ko');else plot(xy(1,1),xy(1,2),'ko'); endhold offendend% Genetic Algorithm Operatorsrand_grouping = randperm(pop_size);for p = 8:8:pop_sizertes = pop_rte(rand_grouping(p-7:p),:);brks = pop_brk(rand_grouping(p-7:p),:);dists = total_dist(rand_grouping(p-7:p));[ignore,idx] = min(dists);best_of_8_rte = rtes(idx,:);best_of_8_brk = brks(idx,:);rte_ins_pts = sort(ceil(n*rand(1,2)));I = rte_ins_pts(1);J = rte_ins_pts(2);for k = 1:8 % Generate New Solutionstmp_pop_rte(k,:) = best_of_8_rte;tmp_pop_brk(k,:) = best_of_8_brk;switch kcase 2 % Fliptmp_pop_rte(k,I:J) = fliplr(tmp_pop_rte(k,I:J)); case 3 % Swaptmp_pop_rte(k,[I J]) = tmp_pop_rte(k,[J I]);case 4 % Slidetmp_pop_rte(k,I:J) = tmp_pop_rte(k,[I+1:J I]); case 5 % Modify Breakstmp_pop_brk(k,:) = randbreaks();case 6 % Flip, Modify Breakstmp_pop_rte(k,I:J) = fliplr(tmp_pop_rte(k,I:J)); tmp_pop_brk(k,:) = randbreaks();case 7 % Swap, Modify Breakstmp_pop_rte(k,[I J]) = tmp_pop_rte(k,[J I]);tmp_pop_brk(k,:) = randbreaks();case 8 % Slide, Modify Breakstmp_pop_rte(k,I:J) = tmp_pop_rte(k,[I+1:J I]); tmp_pop_brk(k,:) = randbreaks();otherwise % Do Nothingendendnew_pop_rte(p-7:p,:) = tmp_pop_rte;new_pop_brk(p-7:p,:) = tmp_pop_brk;endpop_rte = new_pop_rte;pop_brk = new_pop_brk;endif show_res% Plotsfigure('Name','MTSPF_GA | Results','Numbertitle','off');subplot(2,2,1);if dims == 3, plot3(xy(:,1),xy(:,2),xy(:,3),'k.');else plot(xy(:,1),xy(:,2),'k.'); endtitle('City Locations');subplot(2,2,2);imagesc(dmat([1 opt_rte],[1 opt_rte]));title('Distance Matrix');subplot(2,2,3);rng = [[1 opt_brk+1];[opt_brk n]]';for s = 1:salesmenrte = [1 opt_rte(rng(s,1):rng(s,2)) 1];if dims == 3, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); endtitle(sprintf('Total Distance = %',min_dist));hold on;endif dims == 3, plot3(xy(1,1),xy(1,2),xy(1,3),'ko');else plot(xy(1,1),xy(1,2),'ko'); endsubplot(2,2,4);plot(dist_history,'b','LineWidth',2);title('Best Solution History');set(gca,'XLim',[0 num_iter+1],'YLim',[0 *max([1 dist_history])]); end% Return Outputsif nargoutvarargout{1} = opt_rte;varargout{2} = opt_brk;varargout{3} = min_dist;end% Generate Random Set of Break Pointsfunction breaks = randbreaks()if min_tour == 1 % No Constraints on Breakstmp_brks = randperm(n-1);breaks = sort(tmp_brks(1:num_brks));else % Force Breaks to be at Least the Minimum Tour Lengthnum_adjust = find(rand < cum_prob,1)-1;spaces = ceil(num_brks*rand(1,num_adjust));adjust = zeros(1,num_brks);for kk = 1:num_brksadjust(kk) = sum(spaces == kk);endbreaks = min_tour*(1:num_brks) + cumsum(adjust); endendend。

基于MATLAB的蚁群算法求解旅行商问题

基于MATLAB的蚁群算法求解旅行商问题

好行程 的选择机会。 这种改进型算法 能够以更快的速度获得更
好 的解 , 是该算法 会较早的收敛于局 部次优 解, 但 导致搜 索的
过 早停 滞 。 针对 A 中暴 露 出 的问题 , a b r e l L M D r g M S G m a d la , o io ”
提 出了蚁群系统 (n oo y s s e ,A S 。 A t c ln y tm C ) 该文作者较早提
w 啦
( 4 )
r =l 其 中, o e {,, n 1_a u 表 示 蚂 蚁 k a lw d =O1…,一 }t b 下一 步允 许 式中的排 序加 权处 理确 定, 其中 =i, ( - m 每 次 选 择 的城 市 , 实 际 蚁 群 不 同 , 工 蚁 群 系 统 具 有 记 忆 功 能 , l n 为 e : 与 人
op mi ati i bui t f s vi t t ti z on s l or ol ng he rav i s e ma p el ng al s n rob e l m bas on ed MAT AB a fi L , nd nal thr gh t y ou he si mul i n at o to bt n he o ai t bes s ut o whi h s he t ol i n c i t be t s on c e urr t y en l .
K wor ey ds: n o o y O t m z t o A t C l n p i i a i n;T a e i g S l s a r b e r v l n a e m n P o l m;M T A ALB
1 意 义和 目标
息素被表 达为一个函数 , 该函数反映了相应 的行程 质量 。 过 通

TSP旅行商问题matlab代码

TSP旅行商问题matlab代码
end
if n==50
city50=[31 32;32 39;40 30;37 69;27 68;37 52;38 46;31 62;30 48;21 47;25 55;16 57;
17 63;42 41;17 33;25 32;5 64;8 52;12 42;7 38;5 25; 10 77;45 35;42 57;32 22;
end
s=smnew; %产生了新的种群
[f,p]=objf(s,dislist); %计算新种群的适应度
%记录当前代最好和平均的适应度
[fmax,nmax]=max(f);
ymean(gn)=1000/mean(f);
ymax(gn)=1000/fmax;
end
seln(i)=j; %选中个体的序号
if i==2&&j==seln(i-1) %%若相同就再选一次
r=rand; %产生一个随机数
prand=p-r;
j=1;
while prand(j)<0
j=j+1;
ymean=zeros(gn,1);
ymax=zeros(gn,1);
xmax=zeros(inn,CityNum);
scnew=zeros(inn,CityNum);
smnew=zeros(inn,CityNum);
while gn<gnmax+1
for j=1:2:inn
seln=sel(p); %选择操作
zhi=logical(scro(1,1:chb2)==scro(1,i));
y=scro(2,zhi);
scro(1,i)=y;

基于遗传算法解决旅行商问题的MATLAB程序

基于遗传算法解决旅行商问题的MATLAB程序

问题:已知n个城市之间的相互距离,现有一个推销员必须遍访这n个城市,并且每个城市只能访问一次,最后又必须返回出发城市。

如何安排他对这些城市的访问次序,可使其旅行路线的总长度最短?分析:用离散数学或图论的术语来说,假设有一个图g=(v,e),其中v是顶点集,e 是边集,设d=(dij)是由顶点i和顶点j之间的距离所组成的距离矩阵,旅行商问题就是求出一条通过所有顶点且每个顶点只通过一次的具有最短距离的回路。

这个问题可分为对称旅行商问题(dij=dji,,任意i,j=1,2,3,…,n)和非对称旅行商问题(dij≠dji,,任意i,j=1,2,3,…,n)。

若对于城市v={v1,v2,v3,…,vn}的一个访问顺序为t=(t1,t2,t3,…,ti,…,tn),其中ti∈v(i=1,2,3,…,n),且记tn+1= t1,则旅行商问题的数学模型为:min l=σd(t(i),t(i+1)) (i=1,…,n)旅行商问题是一个典型的组合优化问题,并且是一个np难问题,其可能的路径数目与城市数目n是成指数型增长的,所以一般很难精确地求出其最优解,本文采用遗传算法求其近似解。

遗传算法:初始化过程:用v1,v2,v3,…,vn代表所选n个城市。

定义整数pop-size作为染色体的个数,并且随机产生pop-size个初始染色体,每个染色体为1到18的整数组成的随机序列。

适应度f的计算:对种群中的每个染色体vi,计算其适应度,f=σd(t(i),t(i+1)).评价函数eval(vi):用来对种群中的每个染色体vi设定一个概率,以使该染色体被选中的可能性与其种群中其它染色体的适应性成比例,既通过轮盘赌,适应性强的染色体被选择产生后台的机会要大,设alpha∈(0,1),本文定义基于序的评价函数为eval(vi)=alpha*(1-alpha).^(i-1) 。

[随机规划与模糊规划]选择过程:选择过程是以旋转赌轮pop-size次为基础,每次旋转都为新的种群选择一个染色体。

MATLAB多旅行商问题源代码

MATLAB多旅行商问题源代码

M A T L A B多旅行商问题源代码Company Document number:WTUT-WT88Y-W8BBGB-BWYTT-19998MATLAB多旅行商问题源代码function varargout =mtspf_ga(xy,dmat,salesmen,min_tour,pop_size,num_iter,show_prog,show_res)% MTSPF_GA Fixed Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA)% Finds a (near) optimal solution to a variation of the M-TSP by setting% up a GA to search for the shortest route (least distance needed for% each salesman to travel from the start location to individual cities% and back to the original starting place)%% Summary:% 1. Each salesman starts at the first point, and ends at the first% point, but travels to a unique set of cities in between% 2. Except for the first, each city is visited by exactly one salesman%% Note: The Fixed Start/End location is taken to be the first XY point%% Input:% XY (float) is an Nx2 matrix of city locations, where N is the number of cities% DMAT (float) is an NxN matrix of city-to-city distances or costs% SALESMEN (scalar integer) is the number of salesmen to visit the cities% MIN_TOUR (scalar integer) is the minimum tour length for any of the% salesmen, NOT including the start/end point% POP_SIZE (scalar integer) is the size of the population (should be divisible by 8) % NUM_ITER (scalar integer) is the number of desired iterations for the algorithm to run% SHOW_PROG (scalar logical) shows the GA progress if true% SHOW_RES (scalar logical) shows the GA results if true%% Output:% OPT_RTE (integer array) is the best route found by the algorithm% OPT_BRK (integer array) is the list of route break points (these specify the indices% into the route used to obtain the individual salesman routes)% MIN_DIST (scalar float) is the total distance traveled by the salesmen%% Route/Breakpoint Details:% If there are 10 cities and 3 salesmen, a possible route/break% combination might be: rte = [5 6 9 4 2 8 10 3 7], brks = [3 7]% Taken together, these represent the solution [1 5 6 9 1][1 4 2 8 1][1 10 3 7 1],% which designates the routes for the 3 salesmen as follows:% . Salesman 1 travels from city 1 to 5 to 6 to 9 and back to 1% . Salesman 2 travels from city 1 to 4 to 2 to 8 and back to 1% . Salesman 3 travels from city 1 to 10 to 3 to 7 and back to 1%% 2D Example:% n = 35;% xy = 10*rand(n,2);% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid(1:n);% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);% [opt_rte,opt_brk,min_dist] = mtspf_ga(xy,dmat,salesmen,min_tour, ... % pop_size,num_iter,1,1);%% 3D Example:% n = 35;% xyz = 10*rand(n,3);% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid(1:n);% dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);% [opt_rte,opt_brk,min_dist] = mtspf_ga(xyz,dmat,salesmen,min_tour, ... % pop_size,num_iter,1,1);%% See also: mtsp_ga, mtspo_ga, mtspof_ga, mtspofs_ga, mtspv_ga, distmat %% Author: Joseph Kirk% Release:% Release Date: 6/2/09% Process Inputs and Initialize Defaultsnargs = 8;for k = nargin:nargs-1switch kcase 0xy = 10*rand(40,2);case 1N = size(xy,1);a = meshgrid(1:N);dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N);case 2salesmen = 5;case 3min_tour = 2;case 4pop_size = 80;case 5num_iter = 5e3;case 6show_prog = 1;case 7show_res = 1;otherwiseendend% Verify Inputs[N,dims] = size(xy);[nr,nc] = size(dmat);if N ~= nr || N ~= ncerror('Invalid XY or DMAT inputs!')endn = N - 1; % Separate Start/End City% Sanity Checkssalesmen = max(1,min(n,round(real(salesmen(1)))));min_tour = max(1,min(floor(n/salesmen),round(real(min_tour(1))))); pop_size = max(8,8*ceil(pop_size(1)/8));num_iter = max(1,round(real(num_iter(1))));show_prog = logical(show_prog(1));show_res = logical(show_res(1));% Initializations for Route Break Point Selectionnum_brks = salesmen-1;dof = n - min_tour*salesmen; % degrees of freedomaddto = ones(1,dof+1);for k = 2:num_brksaddto = cumsum(addto);endcum_prob = cumsum(addto)/sum(addto);% Initialize the Populationspop_rte = zeros(pop_size,n); % population of routespop_brk = zeros(pop_size,num_brks); % population of breaksfor k = 1:pop_sizepop_rte(k,:) = randperm(n)+1;pop_brk(k,:) = randbreaks();end% Select the Colors for the Plotted Routesclr = [1 0 0; 0 0 1; 0 1; 0 1 0; 1 0];if salesmen > 5clr = hsv(salesmen);end% Run the GAglobal_min = Inf;total_dist = zeros(1,pop_size);dist_history = zeros(1,num_iter);tmp_pop_rte = zeros(8,n);tmp_pop_brk = zeros(8,num_brks);new_pop_rte = zeros(pop_size,n);new_pop_brk = zeros(pop_size,num_brks);if show_progpfig = figure('Name','MTSPF_GA | Current Best Solution','Numbertitle','off'); endfor iter = 1:num_iter% Evaluate Members of the Populationfor p = 1:pop_sized = 0;p_rte = pop_rte(p,:);p_brk = pop_brk(p,:);rng = [[1 p_brk+1];[p_brk n]]';for s = 1:salesmend = d + dmat(1,p_rte(rng(s,1))); % Add Start Distancefor k = rng(s,1):rng(s,2)-1d = d + dmat(p_rte(k),p_rte(k+1));endd = d + dmat(p_rte(rng(s,2)),1); % Add End Distanceendtotal_dist(p) = d;end% Find the Best Route in the Population[min_dist,index] = min(total_dist);dist_history(iter) = min_dist;if min_dist < global_minglobal_min = min_dist;opt_rte = pop_rte(index,:);opt_brk = pop_brk(index,:);rng = [[1 opt_brk+1];[opt_brk n]]';if show_prog% Plot the Best Routefigure(pfig);for s = 1:salesmenrte = [1 opt_rte(rng(s,1):rng(s,2)) 1];if dims == 3, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:)); else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); endtitle(sprintf('Total Distance = %, Iteration = %d',min_dist,iter)); hold onendif dims == 3, plot3(xy(1,1),xy(1,2),xy(1,3),'ko');else plot(xy(1,1),xy(1,2),'ko'); endhold offendend% Genetic Algorithm Operatorsrand_grouping = randperm(pop_size);for p = 8:8:pop_sizertes = pop_rte(rand_grouping(p-7:p),:);brks = pop_brk(rand_grouping(p-7:p),:);dists = total_dist(rand_grouping(p-7:p));[ignore,idx] = min(dists);best_of_8_rte = rtes(idx,:);best_of_8_brk = brks(idx,:);rte_ins_pts = sort(ceil(n*rand(1,2)));I = rte_ins_pts(1);J = rte_ins_pts(2);for k = 1:8 % Generate New Solutionstmp_pop_rte(k,:) = best_of_8_rte;tmp_pop_brk(k,:) = best_of_8_brk;switch kcase 2 % Fliptmp_pop_rte(k,I:J) = fliplr(tmp_pop_rte(k,I:J));case 3 % Swaptmp_pop_rte(k,[I J]) = tmp_pop_rte(k,[J I]);case 4 % Slidetmp_pop_rte(k,I:J) = tmp_pop_rte(k,[I+1:J I]);case 5 % Modify Breakstmp_pop_brk(k,:) = randbreaks();case 6 % Flip, Modify Breakstmp_pop_rte(k,I:J) = fliplr(tmp_pop_rte(k,I:J));tmp_pop_brk(k,:) = randbreaks();case 7 % Swap, Modify Breakstmp_pop_rte(k,[I J]) = tmp_pop_rte(k,[J I]);tmp_pop_brk(k,:) = randbreaks();case 8 % Slide, Modify Breakstmp_pop_rte(k,I:J) = tmp_pop_rte(k,[I+1:J I]);tmp_pop_brk(k,:) = randbreaks();otherwise % Do Nothingendendnew_pop_rte(p-7:p,:) = tmp_pop_rte;new_pop_brk(p-7:p,:) = tmp_pop_brk;endpop_rte = new_pop_rte;pop_brk = new_pop_brk;endif show_res% Plotsfigure('Name','MTSPF_GA | Results','Numbertitle','off');subplot(2,2,1);if dims == 3, plot3(xy(:,1),xy(:,2),xy(:,3),'k.');else plot(xy(:,1),xy(:,2),'k.'); endtitle('City Locations');subplot(2,2,2);imagesc(dmat([1 opt_rte],[1 opt_rte]));title('Distance Matrix');subplot(2,2,3);rng = [[1 opt_brk+1];[opt_brk n]]';for s = 1:salesmenrte = [1 opt_rte(rng(s,1):rng(s,2)) 1];if dims == 3, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:)); else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); endtitle(sprintf('Total Distance = %',min_dist));hold on;endif dims == 3, plot3(xy(1,1),xy(1,2),xy(1,3),'ko');else plot(xy(1,1),xy(1,2),'ko'); endsubplot(2,2,4);plot(dist_history,'b','LineWidth',2);title('Best Solution History');set(gca,'XLim',[0 num_iter+1],'YLim',[0 *max([1 dist_history])]); end% Return Outputsif nargoutvarargout{1} = opt_rte;varargout{2} = opt_brk;varargout{3} = min_dist;end% Generate Random Set of Break Pointsfunction breaks = randbreaks()if min_tour == 1 % No Constraints on Breakstmp_brks = randperm(n-1);breaks = sort(tmp_brks(1:num_brks));else % Force Breaks to be at Least the Minimum Tour Length num_adjust = find(rand < cum_prob,1)-1;spaces = ceil(num_brks*rand(1,num_adjust));adjust = zeros(1,num_brks);for kk = 1:num_brksadjust(kk) = sum(spaces == kk);endbreaks = min_tour*(1:num_brks) + cumsum(adjust);endendend。

基于MATLAB的蚁群算法解决旅行商问题(附带源程序、仿真).doc

基于MATLAB的蚁群算法解决旅行商问题(附带源程序、仿真).doc

基于MATLAB的蚁群算法解决旅行商问题(附带源程序、仿真) ..摘要:旅行商问题的传统求解方法是遗传算法,但此算法收敛速度慢,并不能获得问题的最优化解。

蚁群算法是受自然界中蚁群搜索食物行为启发而提出的一种智能优化算法,通过介绍蚁群觅食过程中基于信息素的最短路径的搜索策略,给出基于MATLAB的蚁群算法在旅行商问题中的应用,对问题求解进行局部优化。

经过计算机仿真结果表明,这种蚁群算法对求解旅行商问题有较好的改进效果。

关键词:蚁群算法;旅行商问题;MATLAB;优化一、意义和目标旅行商问题是物流领域中的典型问题,它的求解具有十分重要的理论和现实意义。

采用一定的物流配送方式,可以大大节省人力物力,完善整个物流系统。

已被广泛采用的遗传算法是旅行商问题的传统求解方法,但遗传算法收敛速度慢,具有一定的缺陷。

本文采用蚁群算法,充分利用蚁群算法的智能性,求解旅行商问题,并进行实例仿真。

进行仿真计算的目标是,该算法能够获得旅行商问题的优化结果,平均距离和最短距离。

二、国内外研究现状仿生学出现于XXXX年代中期,人们从生物进化机理中受到启发,提出了遗传算法、进化规划、进化策略等许多用以解决复杂优化问题的新方法。

这些以生物特性为基础的演化算法的发展及对生物群落行为的发现引导研究人员进一步开展了对生物社会性的研究,从而出现了基于群智能理论的蚁群算法,并掀起了一股研究的热潮。

XXXX年代意大利科学家M.Dorigo M最早提出了蚁群优化算法——蚂蚁系统(Ant system, AS),在求解二次分配、图着色问题、车辆调度、集成电路设计以及通信网络负载问题的处理中都取得了较好的结果。

旅行商问题(TSP, Traveling Salesman Problem)被认为是一个基本问题,是在1859年由威廉·汉密尔顿爵士首次提出的。

所谓TSP问题是指:有N个城市,要求旅行商到达每个城市各一次,且仅一次,并回到起点,且要求旅行路线最短。

基于MATLAB的蚁族算法求解旅行商问题

基于MATLAB的蚁族算法求解旅行商问题

基于MATLAB的蚁族算法求解旅行商问题作者:李艳平来源:《计算机光盘软件与应用》2013年第14期摘要:目前求解旅行商问题效果最好的混合算法是最大最小蚂蚁算法和局部搜索算法,本文对蚁群算法的仿真学原理进行概要介绍,蚁群算法是受自然界中蚁群搜索食物行为启发而提出的一种智能多目标优化算法,通过蚁群觅食过程中最短路径的搜索策略,给出基于MATLAB的蚁群算法在旅行商问题中的应用,并通过实例仿真结果表明,此算法有一定优越性。

关键词:蚁群算法;旅行商问题;仿真;多目标优化中图分类号:TP301.6旅行商问题(TSP)是一个经典的组合优化问题。

TSP可以描述为:一个商品推销员要去若干个城市推销商品,该推销员从一个城市出发,需要经过所有城市后,回到出发地。

应如何选择行进路线,以使总的行程最短。

从图论的角度来看,该问题实质是在一个带权完全无向图中,找一个权值最小的Hamilton回路。

由于该问题的可行解是所有顶点的全排列,随着顶点数的增加,会产生组合爆炸,它是一个N P完全问题。

随着问题规模的增大,人们对复杂事物和复杂系统建立数学模型并进行求解的能力是有限的,目标函数和约束条件往往不能以明确的函数关系表达,或因函数带有随机参、变量,导致基于数学模型的优化方法在应用于实际生产时,有其局限性甚至不适用。

基于仿真的优化(Simulation Based Optimization,SBO)方法正是在这样的背景下发展起来的。

近年来应用蚁群算法求解旅行商问题,由于其并行性与分布性,特别适用于大规模启发式搜索,实验结果表明这种研究方法是可行的。

1 蚁群算法的仿生学原理蚁群算法最早是由意大利学者M.Dorigo提出来的,它的灵感来源于蚂蚁在寻找食物过程中发现路径的行为,蚂蚁集体寻找路径时,利用称为“外激素”的生物信息激素选择后继行为的智能过程。

蚂蚁是一种群居昆虫,在觅食等活动中,彼此依赖、相互协作共同完成特定的任务。

蚁群的行为是整体协作,相互分工,以一个整体去解决一些对单个蚂蚁来说不可能完成的任务。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档