多旅行商问题的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。

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程序代码

运输多染色体遗传的多旅行商问题matlab程序代码篇一:多染色体遗传的多旅行商问题(Multi-迁徙 Problem in Multi-染色体 Gene Expression System)是一个复杂的生物信息学问题,通常需要通过数学建模来解决。

在这个问题中,个体在生殖过程中需要从不同的地区携带不同的基因型进行迁徙,以期望得到最大的基因型多样性。

在多旅行商问题中,每个个体需要在不同的染色体上携带不同的基因型,并且每个染色体上的基因型数量不同。

此外,每个地区需要适应不同的环境,因此每个地区的基因型变异率也有所不同。

因此,每个个体携带的基因型组合必须适应这个地区的环境,并且尽可能地增加个体的基因型多样性。

为了解决这个问题,可以使用数学建模的方法,将多旅行商问题转化为一个优化问题。

在这个优化问题中,个体的基因型多样性可以通过最大化一个函数来确定。

这个函数通常是一个组合优化问题,需要考虑到每个地区适应不同的环境以及每个染色体上的基因型数量的影响。

下面是一个用MATLAB求解多旅行商问题的示例代码,该代码使用了遗传算法来优化基因型多样性:```matlab% 多旅行商问题示例代码% 假设有n个染色体,每个染色体上有多个基因型% 定义基因型组合优化问题的目标函数function z = objective(a, b, c)z = a * (1 - b) * (1 - c) - b * a * c - a * (1 - b) * (1 - c) - c *a *b - b *c * a - c * b * c;end% 定义遗传算法的类classdef Multi迁徙Prob < handleversion 3.0% 定义个体的构造函数function this = Multi迁徙Prob(n, m) this.n = n;this.m = m;% 初始化种群if this.n < 2this.p = [1 1; 1 1];elsethis.p = randperm(this.n);end% 初始化随机变异源this.s = rand(this.n, 1);% 初始化个体this.i = 0;this.j = 0;this.k = 0;% 定义状态转移函数function this.next_state = stateif this.i == this.j && this.k == 0state = this.p;elsestate = rand();endend% 定义适应函数function this.适应 =适应(state)% 计算适应度if this.n == 2适应度 = [0.5 * this.s(1) * this.s(2); 0.5 * this.s(1) * this.s(2)]; else适应度 = [适应度; 0];end% 计算适应度矩阵this.a = [state(1); state(2)];this.b = [适应度; 0];this.c = [适应度; 0];% 计算适应度向量this.a = 适应度 * this.a;this.b = 适应度 * this.b;this.c = 适应度 * this.c;end% 初始化遗传算法的主循环this.m = 1;this.p = this.s;this.i = 0;this.j = 0;this.k = 0;% 计算初始种群中个体的适应度this.a = [this.a; this.b; this.c]; this.p[this.i] = this.a;this.p[this.j] = this.a;this.p[this.k] = this.a;% 迭代种群中的个体for this.l = 1:this.m% 随机选择一个个体this.l = randperm(this.n);% 计算当前个体的适应度this.a = [this.a; this.b; this.c];this.p[this.i + 1] = this.a;this.p[this.j + 1] = this.a;this.p[this.k + 1] = this.a;% 计算当前个体的基因型this.i = this.i + 1;this.j = this.j + 1;this.k = this.k + 1;this.j = j;this.k = k;% 计算当前个体的适应度向量this.b = [适应度; this.s(j) * this.s(k)];this.c = [适应度; this.s(j) * this.s(k)]; end% 计算种群中个体的适应度this.a = [this.a; this.b; this.c];this.p = this.p + this.a;% 计算适应度矩阵this.a = 适应度 * this.a;this.b = 适应度 * this.b;this.c = 适应度 * this.c;% 计算种群中个体的基因型this.i = this.i + 1;this.j = this.j + 1;this.k = this.k + 1;this.j = j;this.k = k;% 计算种群中个体的适应度向量this.a = [适应度; this.s(j) * this.s(k)]; this.p = this.p + this.a;% 输出最终适应度this.a = [适应度; this.s(j) * this.s(k)];% 输出最终基因型多样性z = objective(this.p, this.a, this.b, this.c);endend```该代码使用遗传算法来解决多旅行商问题,通过优化个体的基因型多样性来实现最大的基因型多样性。

蚁群算法TSP(旅行商问题)通用matlab程序

蚁群算法TSP(旅行商问题)通用matlab程序

蚁群算法TSP(旅行商问题)通用matlab程序function [R_best,L_best,L_ave,Shortest_Route,Shortest_Length]=ACAT SP(C,NC_max,m,Alpha,Beta,Rho,Q)%%================================================= ========================%% ACATSP.m%% Ant Colony Algorithm for Traveling Salesman Problem%%shown wang%% Email:mycareer@%%-------------------------------------------------------------------------%% 主要符号说明%% C n个城市的坐标,n×2的矩阵%% NC_max 最大迭代次数%% m 蚂蚁个数%% Alpha 表征信息素重要程度的参数%% Beta 表征启发式因子重要程度的参数%% Rho 信息素蒸发系数%% Q 信息素增加强度系数%% R_best 各代(步)最佳路线%% L_best 各代(步)最佳路线的长度%%================================================= ========================%%第一步:变量初始化n=size(C,1); %n表示问题的规模(城市个数)n个城市Size 矩阵的尺寸D=zeros(n,n); %D表示完全图的赋权邻接矩阵Zeros 零矩阵for i=1:nfor j=1:nif i~=jD(i,j)=((C(i,1)-C(j,1))^2+(C(i,2)-C(j,2))^2)^0.5;elseD(i,j)=eps;Eps 相对浮点精度endD(j,i)=D(i,j);endendEta=1./D; %Eta为启发因子,这里设为距离的倒数Tau=ones(n,n); %Tau为信息素矩阵Ones 全“1”矩阵Tabu=zeros(m,n); %存储并记录路径的生成:用以记录蚂蚁m当前所走过的城市NC=1; %迭代计数器,迭代步数或搜索次数R_best=zeros(NC_max,n); %各代(步)最佳路线L_best=inf.*ones(NC_max,1); %各代(步)最佳路线的长度Inf 无穷大Ones 全“1”矩阵L_ave=zeros(NC_max,1); %各代(步)路线的平均长度while NC<=NC_max %停止条件之一:达到最大迭代次数%%第二步:将m只蚂蚁放到n个城市上Randpos=[ ];for i=1:(ceil(m/n)) %Ceil 朝正无穷大方向取整Randpos=[Randpos,randperm(n)];endTabu(:,1)=(Randpos(1,1:m))';%%第三步:m只蚂蚁按概率函数选择下一座城市,完成各自的周游for j=2:nfor i=1:mvisited=Tabu(i,1:(j-1)); %已访问的城市J=zeros(1,(n-j+1)); %待访问的城市P=J; %待访问城市的选择概率分布Jc=1;for k=1:nif length(find(visited==k))==0J(Jc)=k;Jc=Jc+1;endend%下面计算待选城市的概率分布for k=1:length(J)P(k)=(Tau(visited(end),J(k))^Alpha)*(Eta(visited(end),J(k))^Beta); endP=P/(sum(P));%按概率原则选取下一个城市Pcum=cumsum(P);Select=find(Pcum>=rand);to_visit=J(Select(1));Tabu(i,j)=to_visit;endendif NC>=2Tabu(1,:)=R_best(NC-1,:);end%%第四步:记录本次迭代最佳路线L=zeros(m,1);for i=1:mR=Tabu(i,:);for j=1:(n-1)L(i)=L(i)+D(R(j),R(j+1));endL(i)=L(i)+D(R(1),R(n));endL_best(NC)=min(L);pos=find(L==L_best(NC));R_best(NC,:)=Tabu(pos(1),:);L_ave(NC)=mean(L);NC=NC+1%%第五步:更新信息素Delta_Tau=zeros(n,n);for i=1:mfor j=1:(n-1)Delta_Tau(Tabu(i,j),Tabu(i,j+1))=Delta_Tau(Tabu(i,j),Tabu(i,j+1))+Q/L(i );endDelta_Tau(Tabu(i,n),Tabu(i,1))=Delta_Tau(Tabu(i,n),Tabu(i,1))+Q/L(i); endTau=(1-Rho).*Tau+Delta_Tau;%%第六步:禁忌表清零Tabu=zeros(m,n);end%%第七步:输出结果Pos=find(L_best==min(L_best));Shortest_Route=R_best(Pos(1),:)Shortest_Length=L_best(Pos(1))subplot(1,2,1)DrawRoute(C,Shortest_Route)subplot(1,2,2)plot(L_best)hold onplot(L_ave)function DrawRoute(C,R)%%================================================= ========================%% DrawRoute.m%% 画路线图的子函数%%-------------------------------------------------------------------------%% C Coordinate 节点坐标,由一个N×2的矩阵存储%% R Route 路线%%================================================= ========================N=length(R);scatter(C(:,1),C(:,2));hold onplot([C(R(1),1),C(R(N),1)],[C(R(1),2),C(R(N),2)])hold onfor ii=2:Nplot([C(R(ii-1),1),C(R(ii),1)],[C(R(ii-1),2),C(R(ii),2)]) hold onend设置初始参数如下:m=31;Alpha=1;Beta=5;Rho=0.1;NC_max=200;Q=100; 31城市坐标为:1304 23123639 13154177 22443712 13993488 15353326 15563238 12294196 10044312 7904386 5703007 19702562 17562788 14912381 16761332 6953715 16783918 21794061 23703780 22123676 25784029 28384263 29313429 19083507 23673394 26433439 32012935 32403140 35502545 23572778 28262370 2975运行后得到15602的巡游路径,路线图和收敛曲线如下:。

多旅行商问题遗传算法

多旅行商问题遗传算法

function varargout = mtspf_ga(dmat,salesmen,min_tour,pop_size,num_iter,show_prog,show_res) %dmat 任意两城市间的最短路径矩阵通过floyed算法求得结果。

%salesmen 旅行商个数%min_tour 每个旅行商最少访问的城市数%pop_size 种群个体数%num_iter 迭代的代数%show_prog,show_res 显示的参数设定nargs = 7; %处理输入参数,用来给定一些默认的参数;for k = nargin:nargs-1switch kcase 0dmat = 10*rand(20,20);case 1salesmen = 5;case 2min_tour = 2;case 3pop_size = 80;case 4num_iter = 5e3;case 5show_prog = 1;case 6show_res = 1;otherwiseendend% 检查输入矩阵[nr,nc] = size(dmat);if nr ~= ncerror('Invalid XY or DMA T inputs!')endn = nr - 1; % 除去起始的城市后剩余的城市的数% 输入参数的检查salesmen = 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));% 初始化路线、断点的选择num_brks = salesmen-1;dof = n - min_tour*salesmen; % 可以自由访问的城市数addto = ones(1,dof+1);for k = 2:num_brksaddto = cumsum(addto);endcum_prob = cumsum(addto)/sum(addto);% 初始化种群pop_rte = zeros(pop_size,n); % 路径集合的种群pop_brk = zeros(pop_size,num_brks); % 断点集合的种群for k = 1:pop_sizepop_rte(k,:) = randperm(n)+1;pop_brk(k,:) = randbreaks();end% 选择绘图时的个商人的颜色可删去;clr = [1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0];if salesmen > 5clr = hsv(salesmen);end% 开始运行遗传算法过程global_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% 评价每一代的种群适应情况并作出选择。

基于遗传算法解决旅行商问题的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程序

%多旅行商问题的matlab程序function varargout = mtspf_gaxy,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 11 4 2 8 11 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 = 10randn,2;% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid1:n;% dmat = reshapesqrtsumxya,:-xya',:.^2,2,n,n;% opt_rte,opt_brk,min_dist = mtspf_gaxy,dmat,salesmen,min_tour, ... % pop_size,num_iter,1,1;%% 3D Example:% n = 35;% xyz = 10randn,3;% salesmen = 5;% min_tour = 3;% pop_size = 80;% num_iter = 5e3;% a = meshgrid1:n;% dmat = reshapesqrtsumxyza,:-xyza',:.^2,2,n,n;% opt_rte,opt_brk,min_dist = mtspf_gaxyz,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: jdkirk630gmail% Release: 1.3% Release Date: 6/2/09% Process Inputs and Initialize Defaultsnargs = 8;for k = nargin:nargs-1switch kcase 0xy = 10rand40,2;case 1N = sizexy,1;a = meshgrid1:N;dmat = reshapesqrtsumxya,:-xya',:.^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 InputsN,dims = sizexy;nr,nc = sizedmat;if N ~= nr || N ~= ncerror'Invalid XY or DMAT inputs'endn = N - 1; % Separate Start/End City% Sanity Checkssalesmen = max1,minn,roundrealsalesmen1;min_tour = max1,minfloorn/salesmen,roundrealmin_tour1; pop_size = max8,8ceilpop_size1/8;num_iter = max1,roundrealnum_iter1;show_prog = logicalshow_prog1;show_res = logicalshow_res1;% Initializations for Route Break Point Selectionnum_brks = salesmen-1;dof = n - min_toursalesmen; % degrees of freedom addto = ones1,dof+1;for k = 2:num_brksaddto = cumsumaddto;endcum_prob = cumsumaddto/sumaddto;% Initialize the Populationspop_rte = zerospop_size,n; % population of routes pop_brk = zerospop_size,num_brks; % population of breaks for k = 1:pop_sizepop_rtek,: = randpermn+1;pop_brkk,: = randbreaks;end% Select the Colors for the Plotted Routesclr = 1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0;if salesmen > 5clr = hsvsalesmen;end% Run the GAglobal_min = Inf;total_dist = zeros1,pop_size;dist_history = zeros1,num_iter;tmp_pop_rte = zeros8,n;tmp_pop_brk = zeros8,num_brks;new_pop_rte = zerospop_size,n;new_pop_brk = zerospop_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_rtep,:;p_brk = pop_brkp,:;rng = 1 p_brk+1;p_brk n';for s = 1:salesmend = d + dmat1,p_rterngs,1; % Add Start Distancefor k = rngs,1:rngs,2-1d = d + dmatp_rtek,p_rtek+1;endd = d + dmatp_rterngs,2,1; % Add End Distanceendtotal_distp = d;end% Find the Best Route in the Populationmin_dist,index = mintotal_dist;dist_historyiter = min_dist;if min_dist < global_minglobal_min = min_dist;opt_rte = pop_rteindex,:;opt_brk = pop_brkindex,:;rng = 1 opt_brk+1;opt_brk n';if show_prog% Plot the Best Routefigurepfig;for s = 1:salesmenrte = 1 opt_rterngs,1:rngs,2 1;if dims == 3, plot3xyrte,1,xyrte,2,xyrte,3,'.-','Color',clrs,:;else plotxyrte,1,xyrte,2,'.-','Color',clrs,:; endtitlesprintf'Total Distance = %1.4f, Iteration = %d',min_dist,iter;hold onendif dims == 3, plot3xy1,1,xy1,2,xy1,3,'ko';else plotxy1,1,xy1,2,'ko'; endhold offendend% Genetic Algorithm Operatorsrand_grouping = randpermpop_size;for p = 8:8:pop_sizertes = pop_rterand_groupingp-7:p,:;brks = pop_brkrand_groupingp-7:p,:;dists = total_distrand_groupingp-7:p;ignore,idx = mindists;best_of_8_rte = rtesidx,:;best_of_8_brk = brksidx,:;rte_ins_pts = sortceilnrand1,2;I = rte_ins_pts1;J = rte_ins_pts2;for k = 1:8 % Generate New Solutionstmp_pop_rtek,: = best_of_8_rte;tmp_pop_brkk,: = best_of_8_brk;switch kcase 2 % Fliptmp_pop_rtek,I:J = fliplrtmp_pop_rtek,I:J;case 3 % Swaptmp_pop_rtek,I J = tmp_pop_rtek,J I;case 4 % Slidetmp_pop_rtek,I:J = tmp_pop_rtek,I+1:J I;case 5 % Modify Breakstmp_pop_brkk,: = randbreaks;case 6 % Flip, Modify Breakstmp_pop_rtek,I:J = fliplrtmp_pop_rtek,I:J;tmp_pop_brkk,: = randbreaks;case 7 % Swap, Modify Breakstmp_pop_rtek,I J = tmp_pop_rtek,J I;tmp_pop_brkk,: = randbreaks;case 8 % Slide, Modify Breakstmp_pop_rtek,I:J = tmp_pop_rtek,I+1:J I;tmp_pop_brkk,: = randbreaks;otherwise % Do Nothingendendnew_pop_rtep-7:p,: = tmp_pop_rte;new_pop_brkp-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';subplot2,2,1;if dims == 3, plot3xy:,1,xy:,2,xy:,3,'k.';else plotxy:,1,xy:,2,'k.'; endtitle'City Locations';subplot2,2,2;imagescdmat1 opt_rte,1 opt_rte;title'Distance Matrix';subplot2,2,3;rng = 1 opt_brk+1;opt_brk n';for s = 1:salesmenrte = 1 opt_rterngs,1:rngs,2 1;if dims == 3, plot3xyrte,1,xyrte,2,xyrte,3,'.-','Color',clrs,:;else plotxyrte,1,xyrte,2,'.-','Color',clrs,:; endtitlesprintf'Total Distance = %1.4f',min_dist;hold on;endif dims == 3, plot3xy1,1,xy1,2,xy1,3,'ko';else plotxy1,1,xy1,2,'ko'; endsubplot2,2,4;plotdist_history,'b','LineWidth',2;title'Best Solution History';setgca,'XLim',0 num_iter+1,'YLim',0 1.1max1 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 = randbreaksif min_tour == 1 % No Constraints on Breakstmp_brks = randpermn-1;breaks = sorttmp_brks1:num_brks;else % Force Breaks to be at Least the Minimum Tour Length num_adjust = findrand < cum_prob,1-1;spaces = ceilnum_brksrand1,num_adjust;adjust = zeros1,num_brks;for kk = 1:num_brksadjustkk = sumspaces == kk;endbreaks = min_tour1:num_brks + cumsumadjust;endendend。

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

基于MATLAB的混合型蚁群算法求解旅行商问题
研究与开发
RESEARCH AND DEVELOPMENT
铁路 计 算 机 应 用 RAILWAY COMPUTER APPLICATION
文章编号 1005-8451 2005 09-0004-04
第 14 卷第 9 期 Vol.14 No.9
基于 MATLAB 的混合型蚁群算法求解旅行商问题
[2] 杨肇夏.计算机模拟及其应用[M]. 北京 中国铁道出版社 1999.
[3] 齐 欢 王小平.系统建模与仿真[M]. 北京 清华大学出版 社 2004.
4
2005.9 总第 102 期 RCA
第 14 卷第 9 期
基于 M A T L A B 的混合型蚁群算法求解旅行商问题
研究与开发
被认为是一个基本问题 是在 1859 年由威廉 汉密 尔顿爵士首次提出的 所谓 TSP 问题是指 有 N 个 城市 要求旅行商到达每个城市各一次 且仅一次 并回到起点 且要求旅行路线最短 这是一个典型 的优化问题 对一个具有中等顶点规模的图来说 精确求解也是很复杂的 计算量随着城市个数的增 加而呈指数级增长 即属于所谓的 NP 问题 TSP 在 工程领域有着广泛的应用 并常作为比较算法性能 的标志 如网络通讯 货物运输 电气布线 管道 铺设 加工调度 专家系统 柔性制造系统等方面 都是 T S P 广泛应用的领域 求解算法包括贪婪法
RCA 2005.9 总第 102 期
5
研究与开发
铁 路 计 算 机 应 用
第 14 卷第 9 期式的概率进行选路∑ p ikj
(t
)
=

[τ ij (t)]α [ηij ]β [τ ik (t)]α [ηik ]β
if j ∈allowed k

计算智能课程设计-粒子群优化算法求解旅行商问题-Matlab实现

计算智能课程设计-粒子群优化算法求解旅行商问题-Matlab实现

摘要:TSP 是一个典型的NPC 问题。

本文首先介绍旅行商问题和粒子群优化算法的基本概念。

然后构造一种基于交换子和交换序[1]概念的粒子群优化算法,通过控制学习因子1c 和2c 、最大速度max V ,尝试求解旅行商问题。

本文以中国31个省会城市为例,通过MATLAB 编程实施对旅行商问题的求解,得到了一定优化程度的路径,是粒子群优化算法在TSP问题中运用的一次大胆尝试。

关键字:TSP 问题;粒子群优化算法;MATLAB ;中国31个城市TSP 。

粒子群优化算法求解旅行商问题1.引言1.旅行商问题的概述旅行商问题,即TSP问题(Traveling Salesman Problem)又译为旅行推销员问题货郎担问题,是数学领域中著名问题之一。

假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路径的限制是每个城市只能拜访一次,而且最后要回到原来出发的城市。

路径的选择目标是要求得的路径路程为所有路径之中的最小值。

TSP问题是一个组合优化问题,其描述非常简单,但最优化求解非常困难,若用穷举法搜索,对N个城市需要考虑N!种情况并两两对比,找出最优,其算法复杂性呈指数增长,即所谓“指数爆炸”。

所以,寻求和研究TSP问题的有效启发式算法,是问题的关键。

2.粒子群优化算法的概述粒子群优化算法(Particle Swarm optimization,PSO)又翻译为粒子群算法、微粒群算法、或微粒群优化算法。

是通过模拟鸟群觅食行为而发展起来的一种基于群体协作的随机搜索算法。

通常认为它是群集智能(Swarm intelligence, SI)的一种。

它可以被纳入多主体优化系统 (Multiagent Optimization System, MAOS). 粒子群优化算法是由Eberhart博士和Kennedy博士发明。

PSO模拟鸟群的捕食行为。

一群鸟在随机搜索食物,在这个区域里只有一块食物。

所有的鸟都不知道食物在那里。

运输多染色体遗传的多旅行商问题matlab程序代码

运输多染色体遗传的多旅行商问题matlab程序代码

运输多染色体遗传的多旅行商问题matlab程序代码篇一:多染色体遗传的多旅行商问题(Multi-Gamete Travelling Salesman Problem,MGTSP)是一个经典的组合优化问题,通常用于研究细胞间相互作用和细胞群演化。

在MGTSP中,每个细胞都需要在不同的染色体组合中选择最优的旅行商路径,以最小化细胞间旅行距离和最大化细胞群的最大化收益。

针对MGTSP,可以使用MATLAB等数学软件进行求解。

下面是一个基本的MGTSP 求解程序,包括输入参数和输出结果。

```matlab% 定义MGTSP问题n = 6; % 细胞群数量染色体 = [1 2; 3 4; 5 6]; % 染色体数num_agents = 2; % 个体数量max_iter = 1000; % 最大迭代次数% 初始化变量path = zeros(n, num_agents);cost = zeros(n, num_agents);best_path = zeros(n, num_agents);best_score = 0.0;% 迭代求解for i = 1:max_iter% 随机生成一个个体agent = rand(num_agents);% 初始化路径path(i, :) = 1;cost(i, :) = 0;% 随机生成一个染色体组合染色体_组合 = randperm(染色体);% 计算个体到染色体组合的距离distance = length(染色体_组合 - path(i, :)); % 计算最优路径if distance < cost(i, :)path(i, :) = min(path(i, :),染色体_组合);cost(i, :) = distance;best_score = best_score + 1.0;best_path = path(i, :);end% 更新路径path(i, :) = path(i, :) + 1;% 更新评分cost(i, :) = cost(i, :) + distance;% 检查是否存在全局最优解if all(path == best_path)% 全局最优解存在break;endend% 输出结果disp("最优路径:");disp(best_path);disp("评分:");disp(best_score);```这个程序首先定义了MGTSP问题,包括细胞群数量、染色体数、个体数量和最大迭代次数等参数。

最近邻法与模拟退火算法求解TSP旅行商问题Matlab程序

最近邻法与模拟退火算法求解TSP旅行商问题Matlab程序
2
空间天文台(Space—basedObservatories)的计划,用来探测宇宙起源和外星智 慧生命。欧洲空间局也有类似的 Darwin 计划。对天体成像的时候,需要对两颗 卫星的位置进行调整,如何控制卫星,使消耗的燃料最少,可以用 TSP 来求解。 这里把天体看作城市,距离就是卫星移动消耗的燃料。 美国国家卫生协会在人类基因排序工作中用 TSP 方法绘制放射性杂交图。把 DNA 片段作为城市,它们之间的相似程度作为城市间的距离。法国科学家已经用 这种办法作出了老鼠的放射性杂交图。 此外,旅行商问题还有电缆和光缆布线、晶体结构分析、数据串聚类等多种 用途。更重要的是,它提供了一个研究组合优化问题的理想平台。很多组合优化 问题,比如背包问题、分配问题、车间调度问题都和 TSP 同属 NP 完全问题,它 们都是同等难度的,如果其中一个能用多项式确定性算法解决,那么其他所有的 NP 完全问题也能用多项式算法解决。很多方法本来是从 TSP 发展起来的,后来 推广到其他 NP 完全问题上去。
一条可供选择最后从中选各城市之间示所有的组解空间树求解当节点题货郎纪初商人求找城市1很简其计择的选出间的组合点数2增加时搜索的路径组合数量将成指数级增长从而使得状态空间搜索效率降低要耗费太长的计算时间
目 录
第四章 模拟退火算法以及最近邻法求解 TSP 旅行商问题 ........................................................ 1 4.1 旅行商问题概述 ............................................................................................................... 1 4.2 旅行商问题的应用 ........................................................................................................... 2 4.3 算例问题描述和模型构建 ............................................................................................... 3 4.4 最近邻法求解思路及 Matlab 实现 .................................................................................. 4 4.5 模拟退火算法求解思路及 Matlab 实现 .......................................................................... 5

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实现

模拟退火算法-旅行商问题-matlab实现

clearclca 0.99温度衰减函数的参数t0 97初始温度tf 3终⽌温度t t0;Markov_length 10000Markov链长度load data.txt128 x(:);228 y(:);7040;x, y];data;coordinates [1565.0575.0225.0185.03345.0750.0;4945.0685.05845.0655.06880.0660.0;725.0230.08525.01000.09580.01175.0;10650.01130.0111605.0620.0121220.0580.0;131465.0200.0141530.0 5.015845.0680.0;16725.0370.017145.0665.018415.0635.0;19510.0875.020560.0365.021300.0465.0;22520.0585.023480.0415.024835.0625.0;25975.0580.0261215.0245.0271320.0315.0;281250.0400.029660.0180.030410.0250.0;31420.0555.032575.0665.0331150.01160.0;34700.0580.035685.0595.036685.0610.0;37770.0610.038795.0645.039720.0635.0;40760.0650.041475.0960.04295.0260.0;43875.0920.044700.0500.045555.0815.0;46830.0485.0471170.065.048830.0610.0;49605.0625.050595.0360.0511340.0725.0;521740.0245.0;];coordinates(:,1 [];amount 1城市的数⽬通过向量化的⽅法计算距离矩阵dist_matrix zeros(amount,amount);coor_x_tmp1 11,amount);coor_x_tmp2 ';21,amount);coor_y_tmp2 ';22); sol_new 1产⽣初始解,sol_new是每次产⽣的新解sol_current sol_current是当前解sol_best sol_best是冷却中的最好解E_current E_current是当前解对应的回路距离E_best E_best是最优解p 1;rand('state', sum(clock));for110000sol_current [randperm(amount)];E_current 0;for11)E_current 1));endif E_bestsol_best sol_current;E_best E_current;endendwhile tffor1Markov链长度产⽣随机扰动if0.5)两交换ind1 0;ind2 0;while ind2)ind1 amount);ind2 amount);endtmp1 sol_new(ind1);sol_new(ind1) sol_new(ind2);sol_new(ind2) tmp1;else三交换ind13));ind sort(ind);sol_new 11112131231:end]); end检查是否满⾜约束计算⽬标函数值(即内能)E_new 0;for11)E_new 1));end再算上从最后⼀个城市到第⼀个城市的距离E_new 1));if E_currentE_current E_new;sol_current sol_new;if E_bestE_best E_new;sol_best sol_new;endelse若新解的⽬标函数值⼤于当前解,则仅以⼀定概率接受新解if t)E_current E_new;sol_current sol_new;elsesol_new sol_current;endendendt 控制参数t(温度)减少为原来的a倍endE_best 1));disp('最优解为:');disp(sol_best);disp('最短距离:');disp(E_best);data1 2 );for1:length(sol_best)data1(i, :) 1,i), :);enddata1 11),:)];figureplot(coordinates(:,1', coordinates(:,2)''*k'1', data1(:, 2)''r');title( [ '近似最短路径如下,路程为'clc;clear;close all;coordinates [225.0185.03345.0750.0;4945.0685.05845.0655.06880.0660.0;725.0230.08525.01000.09580.01175.0;10650.01130.0111605.0620.0121220.0580.0;131465.0200.0141530.0 5.015845.0680.0;16725.0370.017145.0665.018415.0635.0;19510.0875.020560.0365.021300.0465.0;22520.0585.023480.0415.024835.0625.0;25975.0580.0261215.0245.0271320.0315.0;281250.0400.029660.0180.030410.0250.0;31420.0555.032575.0665.0331150.01160.0;34700.0580.035685.0595.036685.0610.0;37770.0610.038795.0645.039720.0635.0;40760.0650.041475.0960.04295.0260.0; 43875.0920.044700.0500.045555.0815.0; 46830.0485.0471170.065.048830.0610.0; 49605.0625.050595.0360.0511340.0725.0; 521740.0245.0;];coordinates(:,1 [];data coordinates;读取数据load data.txt;128 x(:);228 y(:);x 1);y 2);start 565.0575.0];data [start; data;start];[start; x, y;start];180;计算距离的邻接表count 1));d zeros(count);for11for1:count1122))...22));d(i,j)20.5 ;6370acos(temp);endendd '; % 对称 i到j==j到iS0存储初值Sum存储总距离rand('state', sum(clock));求⼀个较为优化的解,作为初值for110000S 112), count];temp 0;for11temp 1));endif SumS0 S;Sum temp;endende 0.140终⽌温度L 2000000最⼤迭代次数at 0.999999降温系数T 2初温退⽕过程for1:L产⽣新解c 1112));c sort(c);c1 12);if1c1 1;endif1c2 1;end计算代价函数值df 11...(d(S0(c111)));接受准则if0S0 1111:count)];Sum df;elseif exp(1)S0 1111:count)];Sum df;endT at;if ebreak;endenddata1 2, count);[start; x, y; start];for1:countdata1(:, i) 1';endfigureplot(x, y, 'o'12'r');title( [ '近似最短路径如下,路程为' , num2str( Sum ) ] ) ; disp(Sum);S0。

matlab启发式算法

matlab启发式算法

MATLAB是一种广泛使用的数学软件,它提供了许多算法和工具,包括启发式算法。

启发式算法是一种基于启发式原理的搜索算法,它通过利用一些启发式信息来减少搜索空间,从而加快搜索速度并提高搜索效率。

下面是一个使用MATLAB实现启发式算法的示例,该算法用于解决旅行商问题(TSP)。

旅行商问题是一个经典的优化问题,要求找到从一个城市到另一个城市的最佳路径,使得总旅行距离最短。

传统的搜索算法可能需要很长时间才能找到解决方案,而启发式算法可以利用一些启发式信息来加快搜索速度。

步骤:1. 定义城市和路径首先,我们需要定义城市的坐标和之间的距离。

这可以通过将每个城市标记为一个数组,并在每个城市之间添加距离来定义。

然后,我们需要为每个城市指定一个优先级或重要性。

这是因为我们的算法会优先考虑访问具有高优先级的城市。

2. 初始化路径接下来,我们需要初始化一个初始路径。

这可以通过随机选择一些城市并将其添加到路径中来实现。

我们还需要将当前路径的长度设置为零,以便我们可以轻松地跟踪总距离。

3. 计算启发式值为了找到最佳路径,我们需要计算每个路径的启发式值。

这可以通过将每个路径的总距离除以未访问城市的数量来实现。

这可以让我们更关注那些距离更短且未访问的城市。

4. 选择下一个城市一旦我们有了所有路径的启发式值,我们就可以选择下一个要访问的城市。

我们选择具有最低启发式值的城市作为下一个目标城市。

这可以确保我们始终在寻找最短路径的同时也访问尽可能多的城市。

5. 更新路径一旦我们选择了下一个城市,我们需要将其添加到当前路径中,并更新路径的总长度。

我们还需要从剩余城市中选择一个具有最高优先级的城市并将其添加到剩余城市列表中。

这将允许我们继续搜索未访问的城市并继续寻找更好的路径。

6. 重复步骤4和5重复步骤4和5直到达到指定的最大迭代次数或找到一个满足要求的解决方案为止。

这就是使用MATLAB实现旅行商问题(TSP)的启发式算法的基本步骤。

MATLAB关于旅行商问题遗传算法的研究

MATLAB关于旅行商问题遗传算法的研究

基于遗传算法对TSP问题的研究摘要:作为一种模拟生物自然遗传与进化过程的优化方法,遗传算法(GA)因其具有隐并行性、不需目标函数可微等特点,常被用于解决一些传统优化方法难以解决的问题。

旅行商问题(TSP)是典型的NP难题组合优化问题之一,且被广泛应用于许多领域,所以研究遗传算法求解TSP具有重要的理论意义和应用价值。

关键字:遗传算法旅行商问题Abstract:Genetic algorithm(GA)which has the characteristic of latent parallelism, non-differentiability of objective function and so on,as a optimization method of simulating the process of natural biotic inherit and evolution,is used to solve some problems which are difficult to solve by the traditional optimization method.Travel salesman problem(TSP)is a typical NF s combination and optimization problem,and is widely used in many fields.So the genetic algorithm to solve TSP has important theoretical significance and application value.Keywords:genetic algorithm TSP一、引言在过去,人们往往只能够处理一些简单的问题,对于大型复杂系统的优化和自适应仍然无能为力。

但是在自然界中,生物在这方面表现出了其优异的能力,他们能够通过优胜劣汰、适者生存的自然进化规则进行生存和繁衍,并且慢慢的产生对其生存环境适应性越来越高的优良物种。

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

%多旅行商问题的matlab程序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% Email: jdkirk630@% Release: 1.3% 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 freedom addto = 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 routes pop_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.67 0 1; 0 1 0; 1 0.5 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 = %1.4f, 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 = %1.4f',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 1.1*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。

相关文档
最新文档