遗传算法的matlab通用程序
遗传算法Matlab程序
% f(x)=11*sin(6x)+7*cos(5x),0<=x<=2*pi;%%初始化参数L=16;%编码为16位二进制数N=32;%初始种群规模M=48;%M个中间体,运用算子选择出M/2对母体,进行交叉;对M个中间体进行变异T=100;%进化代数Pc=0.8;%交叉概率Pm=0.03;%%变异概率%%将十进制编码成16位的二进制,再将16位的二进制转成格雷码for i=1:1:Nx1(1,i)= rand()*2*pi;x2(1,i)= uint16(x1(1,i)/(2*pi)*65535);grayCode(i,:)=num2gray(x2(1,i),L);end%% 开始遗传算子操作for t=1:1:Ty1=11*sin(6*x1)+7*cos(5*x1);for i=1:1:M/2[a,b]=min(y1);%找到y1中的最小值a,及其对应的编号bgrayCodeNew(i,:)=grayCode(b,:);%将找到的最小数放到grayCodeNew中grayCodeNew(i+M/2,:)=grayCode(b,:);%与上面相同就可以有M/2对格雷码可以作为母体y1(1,b)=inf;%用来排除已找到的最小值endfor i=1:1:M/2p=unidrnd(L);%生成一个大于零小于L的数,用于下面进行交叉的位置if rand()<Pc % Pc是交叉概率%将选定的染色体的点后的基因进行交换for j=p:1:Ltemp= grayCodeNew(i,j);grayCodeNew(i,j)=grayCodeNew(M-i+1,j);grayCodeNew(M-i+1,j)=temp;endendend%%将全部染色体按概率进行变异for i=1:1:Mfor j=1:1:Lif rand()<Pm %Pm为染色体变异的概率grayCodeNew(i,j)=dec2bin(1-bin2dec(grayCodeNew(i,j)));endendend%%第一代结束后生成的较优的染色体,得以保存然后进行下一代操作for i=1:1:Mx4(1,i)=gray2num(grayCodeNew(i,:));endx3=double(x4)*2*pi/65535;y3=11*sin(6*x3)+7*cos(5*x3);for i=1:1:N[a,b]=min(y3);x1(1,i)=x3(1,b);grayCode(i,:)=grayCodeNew(b,:);y3(1,b)=inf;endendx1y1=11*sin(6*x1)+7*cos(5*x1)。
用MATLAB实现遗传算法程序
用MATLAB实现遗传算法程序一、本文概述遗传算法(Genetic Algorithms,GA)是一种模拟自然界生物进化过程的优化搜索算法,它通过模拟自然选择和遗传学机制,如选择、交叉、变异等,来寻找问题的最优解。
由于其全局搜索能力强、鲁棒性好以及易于实现并行化等优点,遗传算法在多个领域得到了广泛的应用,包括函数优化、机器学习、神经网络训练、组合优化等。
本文旨在介绍如何使用MATLAB实现遗传算法程序。
MATLAB作为一种强大的数学计算和编程工具,具有直观易用的图形界面和丰富的函数库,非常适合用于遗传算法的实现。
我们将从基本的遗传算法原理出发,逐步介绍如何在MATLAB中编写遗传算法程序,包括如何定义问题、编码、初始化种群、选择操作、交叉操作和变异操作等。
通过本文的学习,读者将能够掌握遗传算法的基本原理和MATLAB编程技巧,学会如何使用MATLAB实现遗传算法程序,并能够在实际问题中应用遗传算法求解最优解。
二、遗传算法基础遗传算法(Genetic Algorithm,GA)是一种模拟自然选择和遗传学机制的优化搜索算法。
它借鉴了生物进化中的遗传、交叉、变异等机制,通过模拟这些自然过程来寻找问题的最优解。
遗传算法的核心思想是将问题的解表示为“染色体”,即一组编码,然后通过模拟自然选择、交叉和变异等过程,逐步迭代搜索出最优解。
在遗传算法中,通常将问题的解表示为一个二进制字符串,每个字符串代表一个个体(Individual)。
每个个体都有一定的适应度(Fitness),适应度越高的个体在下一代中生存下来的概率越大。
通过选择(Selection)、交叉(Crossover)和变异(Mutation)等操作,生成新一代的个体,并重复这一过程,直到找到满足条件的最优解或达到预定的迭代次数。
选择操作是根据个体的适应度,选择出适应度较高的个体作为父母,参与下一代的生成。
常见的选择算法有轮盘赌选择(Roulette Wheel Selection)、锦标赛选择(Tournament Selection)等。
完整的遗传算法函数Matlab程序【精品毕业设计】(完整版)
完整的遗传算法函数Matlab程序function [x,endPop,bPop,traceInfo] = ga(bounds,eevalFN,eevalOps,startPop,opts,... termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)n=nargin;if n<2 | n==6 | n==10 | n==12disp('Insufficient arguements')endif n<3 %Default eevalation opts.eevalOps=[];endif n<5opts = [1e-6 1 0];endif isempty(opts)opts = [1e-6 1 0];endif any(eevalFN<48) %Not using a .m fileif opts(2)==1 %Float gae1str=['x=c1; c1(xZomeLength)=', eevalFN ';'];e2str=['x=c2; c2(xZomeLength)=', eevalFN ';'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...eevalFN ';'];endelse %Are using a .m fileif opts(2)==1 %Float gae1str=['[c1 c1(xZomeLength)]=' eevalFN '(c1,[gen eevalOps]);'];e2str=['[c2 c2(xZomeLength)]=' eevalFN '(c2,[gen eevalOps]);'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' eevalFN ...'(x,[gen eevalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];endendif n<6 %Default termination informationtermOps=[100];termFN='maxGenTerm';endif n<12 %Default muatation informationif opts(2)==1 %Float GAmutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];else %Binary GAmutFNs=['binaryMutation'];mutOps=[0.05];endendif n<10 %默认的交叉信息if opts(2)==1 %浮点编码xOverFNs=['arithXover heuristicXover simpleXover'];xOverOps=[2 0;2 3;2 0];else %Binary GAxOverFNs=['simpleXover'];xOverOps=[0.6];endendif n<9 %Default select opts only i.e. roullete wheel.selectOps=[];endif n<8 %Default select infoselectFN=['normGeomSelect'];selectOps=[0.08];endif n<6 %默认的算法终止准则termOps=[100];termFN='maxGenTerm';endif n<4 %初始种群为空startPop=[];endif isempty(startPop) %随机生成初始种群startPop=initializega(80,bounds,eevalFN,eevalOps,opts(1:2));endif opts(2)==0 %二进制编码bits=calcbits(bounds,opts(1));endxOverFNs=parse(xOverFNs);mutFNs=parse(mutFNs);xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness numVar = xZomeLength-1; %变量数目popSize = size(startPop,1); %种群中个体数目endPop = zeros(popSize,xZomeLength); %次种群矩阵c1 = zeros(1,xZomeLength); %个体c2 = zeros(1,xZomeLength); %个体numXOvers = size(xOverFNs,1); %交叉操作次数numMuts = size(mutFNs,1); %变异操作次数epsilon = opts(1); %适应度门限值oeval = max(startPop(:,xZomeLength)); %初始种群中的最优值bFoundIn = 1;done = 0;gen = 1;collectTrace = (nargout>3);floatGA = opts(2)==1;display = opts(3);while(~done)[beval,bindx] = max(startPop(:,xZomeLength)); %当前种群的最优值best = startPop(bindx,:);if collectTracetraceInfo(gen,1)=gen; %当前代traceInfo(gen,2)=startPop(bindx,xZomeLength); %最优适应度traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %平均适应度traceInfo(gen,4)=std(startPop(:,xZomeLength));endif ( (abs(beval - oeval)>epsilon) | (gen==1))if displayfprintf(1,'\n%d %f\n',gen,beval);endif floatGAbPop(bFoundIn,:)=[gen startPop(bindx,:)];elsebPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... startPop(bindx,xZomeLength)];endbFoundIn=bFoundIn+1;oeval=beval;elseif displayfprintf(1,'%d ',gen);endendendPop = feeval(selectFN,startPop,[gen selectOps]); %选择操作if floatGAfor i=1:numXOvers,for j=1:xOverOps(i,1),a = round(rand*(popSize-1)+1); %一个父代个体b = round(rand*(popSize-1)+1); %另一个父代个体xN=deblank(xOverFNs(i,:)); %交叉函数[c1 c2] = feeval(xN,endPop(a,:),endPop(b,:),bounds,[gen… xOverOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseif c1(1:numVar)==endPop(b,(1:numVar))c1(xZomeLength)=endPop(b,xZomeLength);elseeeval(e1str);endif c2(1:numVar)==endPop(a,(1:numVar))c2(xZomeLength)=endPop(a,xZomeLength);elseif c2(1:numVar)==endPop(b,(1:numVar))c2(xZomeLength)=endPop(b,xZomeLength);elseeeval(e2str);endendPop(a,:)=c1;endPop(b,:)=c2;endendfor i=1:numMuts,for j=1:mutOps(i,1),a = round(rand*(popSize-1)+1);c1 = feeval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseeeval(e1str);endendPop(a,:)=c1;endendelse %遗传操作的统计模型for i=1:numXOvers,xN=deblank(xOverFNs(i,:));cp=find(rand(popSize,1)if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); endcp=reshape(cp,size(cp,1)/2,2);for j=1:size(cp,1)a=cp(j,1); b=cp(j,2);[endPop(a,:) endPop(b,:)] = feeval(xN,endPop(a,:),endPop(b,:), bounds,[gen xOverOps(i,:)]); endendfor i=1:numMutsmN=deblank(mutFNs(i,:));for j=1:popSizeendPop(j,:) = feeval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);eeval(e1str);endendend。
遗传算法及其MATLAB程序
遗传算法及其MATLAB实现主要内容遗传算法简介遗传算法的MATLAB实现应用举例一、遗传算法简介遗传算法(Genetic Algorithm,GA)最先是由美国Mic-hgan大学的John Holland于1975年提出的。
遗传算法是模拟达尔文的遗传选择和自然淘汰的生物进化过程的计算模型。
它的思想源于生物遗传学和适者生存的自然规律,是具有“生存+检测”的迭代过程的搜索算法。
遗传算法以一种群体中的所有个体为对象,并利用随机化技术指导对一个被编码的参数空间进行高效搜索。
其中,选择、交叉和变异构成了遗传算法的遗传操作;参数编码、初始群体的设定、适应度函数的设计、遗传操作设计、控制参数设定等5个要素组成了遗传算法的核心内容。
遗传算法的基本步骤:遗传算法是一种基于生物自然选择与遗传机理的随机搜索算法,与传统搜索算法不同,遗传算法从一组随机产生的称为“种群(Population)”的初始解开始搜索过程。
种群中的每个个体是问题的一个解,称为“染色体(chromos ome)”。
染色体是一串符号,比如一个二进制字符串。
这些染色体在后续迭代中不断进化,称为遗传。
在每一代中用“适值(fitness)”来测量染色体的好坏,生成的下一代染色体称为后代(offspring)。
后代是由前一代染色体通过交叉(crossover)或者变异(mutation)运算形成的。
在新一代形成过程中,根据适度的大小选择部分后代,淘汰部分后代。
从而保持种群大小是常数。
适值高的染色体被选中的概率较高,这样经过若干代之后,算法收敛于最好的染色体,它很可能就是问题的最优解或次优解。
主要步骤如下所示:(1)编码:GA在进行搜索之前先将解空间的解数据表示成遗传空间的基因型串结构数据,这些串结构数据的不同组合便构成了不同的点。
(2)初始群体的生成:随机产生N个初始串结构数据,每个串结构数据称为一个个体,N个个体构成了—个群体。
GA以这N个串结构数据作为初始点开始迭代。
2020年遗传算法matlab程序实例精编版
%-----------------------------------------------%---------------------------------------------------遗传算法程序(一):说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作!function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation)% Finds a maximum of a function of several variables.% fmaxga solves problems of the form:% max F(X) subject to: LB <= X <= UB% BestPop - 最优的群体即为最优的染色体群% Trace - 最佳染色体所对应的目标函数值% FUN - 目标函数% LB - 自变量下限% UB - 自变量上限% eranum - 种群的代数,取100--1000(默认200)% popsize - 每一代种群的规模;此可取50--200(默认100)% pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8)% pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1)% pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2)% options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编%码,option(2)设定求解精度(默认1e-4)%% ------------------------------------------------------------------------T1=clock;if nargin<3, error('FMAXGA requires at least three input arguments'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[LB;UB]';bits=[];VarNum=size(bounds,1);precision=options(2);%由求解精度确定二进制编码长度bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间[Pop]=InitPopGray(popsize,bits);%初始化种群[m,n]=size(Pop);NewPop=zeros(m,n);children1=zeros(1,n);children2=zeros(1,n);pm0=pMutation;BestPop=zeros(eranum,n);%分配初始解空间BestPop,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度end[MaxValue,Index]=max(value);BestPop(i,:)=Pop(Index,:);Trace(i,1)=MaxValue;Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率%round(unidrnd(eranum-i)/eranum)[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位Pop=InversionPop;%更新pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);%随着种群向前进化,逐步增大变异率至1/2交叉率p(i)=pMutation;i=i+1;endt=1:eranum;plot(t,Trace(:,1)');title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');[MaxFval,I]=max(Trace(:,1));X=Trace(I,(2:length(bits)+1));hold on; plot(I,MaxFval,'*');text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf ('进化到%d 代,自变量为%s 时,得本次求解的最优值%f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:)));disp(str1);%figure(2);plot(t,p);%绘制变异值增大过程T2=clock;elapsed_time=T2-T1;if elapsed_time(6)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;end %像这种程序当然不考虑运行上小时啦str2=sprintf('程序运行耗时%d 小时%d 分钟%.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%初始化种群%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点function [initpop]=InitPopGray(popsize,bits)len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)initpop(i,:)=pop(1:end-1);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individual%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%解码function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=bval((cs(i)+1):cs(i+1));fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);end%选择操作%采用基于轮盘赌法的非线性排名选择%各个体成员按适应值从大到小分配选择概率:%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中P(0)>P(1)>...>P(n), sum(P(i))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=fit/sum(fit);%计算各个体相对适应度(0,1)q=max(selectprob);%选择最优的概率x=zeros(m,2);x(:,1)=[m:-1:1]';[y x(:,2)]=sort(selectprob);r=q/(1-(1-q)^m);%标准分布基值newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率newfit=cumsum(newfit);%计算各选择概率之和rNums=sort(rand(m,1));fitIn=1;newIn=1;while newIn<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=rand(1,m);y1=find(r<pCross);y2=find(r>=pCross);len=length(y1);if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endif length(y1)>=2for i=0:2:length(y1)-2if opts==0[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));else[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:));endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=round(rand(1,n));%随机生成掩码crossposition=find(hidecode==1);holdposition=find(hidecode==0);children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因%采用多点交叉,交叉点数由变量数决定function [Children1,Children2]=MultiPointCross(Parent1,Parent2)global n Children1 Children2 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));end%变异操作function [NewPop]=Mutation(OldPop,pMutation,VarNum)global m n NewPopr=rand(1,m);position=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;endendendendNewPop=OldPop;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1));NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);endendend遗传算法程序(二):function youhuafunD=code;N=50; % Tunablemaxgen=50; % Tunablecrossrate=0.5; %Tunablemuterate=0.08; %Tunablegeneration=1;num = length(D);fatherrand=randint(num,N,3);score = zeros(maxgen,N);while generation<=maxgenind=randperm(N-2)+2; % 随机配对交叉A=fatherrand(:,ind(1:(N-2)/2));B=fatherrand(:,ind((N-2)/2+1:end));% 多点交叉rnd=rand(num,(N-2)/2);ind=rnd tmp=A(ind);A(ind)=B(ind);B(ind)=tmp;% % 两点交叉% for kk=1:(N-2)/2% rndtmp=randint(1,1,num)+1;% tmp=A(1:rndtmp,kk);% A(1:rndtmp,kk)=B(1:rndtmp,kk);% B(1:rndtmp,kk)=tmp;% endfatherrand=[fatherrand(:,1:2),A,B];% 变异rnd=rand(num,N);ind=rnd [m,n]=size(ind);tmp=randint(m,n,2)+1;tmp(:,1:2)=0;fatherrand=tmp+fatherrand;fatherrand=mod(fatherrand,3);% fatherrand(ind)=tmp;%评价、选择scoreN=scorefun(fatherrand,D);% 求得N个个体的评价函数score(generation,:)=scoreN;[scoreSort,scoreind]=sort(scoreN);sumscore=cumsum(scoreSort);sumscore=sumscore./sumscore(end);childind(1:2)=scoreind(end-1:end);for k=3:Ntmprnd=rand;tmpind=tmprnd difind=[0,diff(tmpind)];if ~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind);generation=generation+1;end% scoremaxV=max(score,[],2);minV=11*300-maxV;plot(minV,'*');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;save DData Dfunction D=codeload youhua.mat% properties F2 and F3F1=A(:,1);F2=A(:,2);F3=A(:,3);if (max(F2)>1450)||(min(F2)<=900)error('DATA property F2 exceed it''s range (900,1450]')end% get group property F1 of data, according to F2 valueF4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[F1,F2,F3,F4];function ScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4*ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);ScoreN=ones(1,N)*300*11;% 这里有待优化for k=1:NFF4k=FF4rnd(:,k);for ite=1:11F0index=find(FF4k==ite);if ~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%遗传算法程序(三):%IAGAfunction best=gaclearMAX_gen=200; %最大迭代步数best.max_f=0; %当前最大的适应度STOP_f=14.5; %停止循环的适应度RANGE=[0 255]; %初始取值范围[0 255]SPEEDUP_INTER=5; %进入加速迭代的间隔advance_k=0; %优化的次数popus=init; %初始化for gen=1:MAX_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;function popus=init%初始化M=50;%种群个体数目N=30;%编码长度popus=round(rand(M,N));return;function fitness=fit(popus,RANGE)%求适应度[M,N]=size(popus);fitness=zeros(M,1);%适应度f=zeros(M,1);%函数值A=RANGE(1);B=RANGE(2);%初始取值范围[0 255]for m=1:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_std=(f-min(f))./(max(f)-min(f));%函数值标准化fitness.f=f;fitness.f_std=f_std;fitness.x=x;return;function picked=choose(popus,fitness)%选择f=fitness.f;f_std=fitness.f_std;[M,N]=size(popus);choose_N=3; %选择choose_N对双亲picked=zeros(choose_N,2); %记录选择好的双亲p=zeros(M,1); %选择概率d_order=zeros(M,1);%把父代个体按适应度从大到小排序f_t=sort(f,'descend');%将适应度按降序排列for k=1:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(1)=ceil(rand*N);%生成杂交位置p(2)=ceil(rand*N);p=sort(p);t=popus(picked(cn,1),p(1):p(2));popus(picked(cn,1),p(1):p(2))=popus(picked(cn,2),p(1):p(2));popus(picked(cn,2),p(1):p(2))=t;endreturn;function popus=aberrance(popus,picked) %变异P_a=0.05;%变异概率[M,N]=size(popus);[M_p,N_p]=size(picked);U=rand(1,2);for kp=1:M_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand;if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%。
遗传算法应用实例及matlab程序
遗传算法应用实例及matlab程序遗传算法是一种模拟自然进化过程的优化算法,在多个领域都有广泛的应用。
下面将以一个经典的实例,车间调度问题,来说明遗传算法在实际问题中的应用,并给出一个基于MATLAB的实现。
车间调度问题是一个经典的组合优化问题,它是指在给定一系列任务和一台机器的情况下,如何安排任务的执行顺序,以便最小化任务的完成时间或最大化任务的完成效率。
这个问题通常是NP困难问题,因此传统的优化算法往往难以找到全局最优解。
遗传算法能够解决车间调度问题,其基本思想是通过模拟生物进化的过程,不断演化和改进任务的调度顺序,以找到最优解。
具体步骤如下:1. 初始种群的生成:生成一批初始调度方案,每个方案都表示为一个染色体,一般采用随机生成的方式。
2. 个体适应度的计算:根据染色体中任务的执行顺序,计算每个调度方案的适应度值,一般使用任务完成时间作为适应度度量。
3. 选择操作:根据个体的适应度,采用选择策略选择一部分优秀个体作为父代。
4. 交叉操作:对选中的个体进行交叉操作,生成新的子代个体。
5. 变异操作:对子代个体进行变异操作,引入随机性,增加搜索空间的广度。
6. 替换操作:用新的个体替换原来的个体,形成新一代的种群。
7. 迭代过程:重复执行选择、交叉、变异和替换操作,直到达到预定的终止条件。
下面给出基于MATLAB的实现示例:matlabfunction [best_solution, best_fitness] =genetic_algorithm(num_generations, population_size) % 初始化种群population = generate_population(population_size);for generation = 1:num_generations% 计算适应度fitness = calculate_fitness(population);% 选择操作selected_population = selection(population, fitness);% 交叉操作crossed_population = crossover(selected_population);% 变异操作mutated_population = mutation(crossed_population);% 替换操作population = replace(population, selected_population, mutated_population);end% 找到最优解[~, index] = max(fitness);best_solution = population(index,:);best_fitness = fitness(index);endfunction population = generate_population(population_size) % 根据问题的具体要求,生成初始种群population = randi([1, num_tasks], [population_size, num_tasks]); endfunction fitness = calculate_fitness(population)% 根据任务执行顺序,计算每个调度方案的适应度% 这里以任务完成时间作为适应度度量fitness = zeros(size(population, 1), 1);for i = 1:size(population, 1)solution = population(i,:);% 计算任务完成时间completion_time = calculate_completion_time(solution);% 适应度为任务完成时间的倒数fitness(i) = 1 / completion_time;endendfunction selected_population = selection(population, fitness) % 根据适应度值选择父代个体% 这里采用轮盘赌选择策略selected_population = zeros(size(population));for i = 1:size(population, 1)% 计算选择概率prob = fitness / sum(fitness);% 轮盘赌选择selected_population(i,:) = population(find(rand <= cumsum(prob), 1),:);endendfunction crossed_population = crossover(selected_population) % 对选中的个体进行交叉操作% 这里采用单点交叉crossed_population = zeros(size(selected_population));for i = 1:size(selected_population, 1) / 2parent1 = selected_population(2*i-1,:);parent2 = selected_population(2*i,:);% 随机选择交叉点crossover_point = randi([1, size(parent1,2)]);% 交叉操作crossed_population(2*i-1,:) = [parent1(1:crossover_point), parent2(crossover_point+1:end)];crossed_population(2*i,:) = [parent2(1:crossover_point), parent1(crossover_point+1:end)];endendfunction mutated_population = mutation(crossed_population) % 对子代个体进行变异操作% 这里采用单点变异mutated_population = crossed_population;for i = 1:size(mutated_population, 1)individual = mutated_population(i,:);% 随机选择变异点mutation_point = randi([1, size(individual,2)]);% 变异操作mutated_population(i,mutation_point) = randi([1, num_tasks]);endendfunction new_population = replace(population, selected_population, mutated_population)% 根据选择、交叉和变异得到的个体替换原来的个体new_population = mutated_population;for i = 1:size(population, 1)if ismember(population(i,:), selected_population, 'rows')% 保留选择得到的个体continue;else% 随机选择一个父代个体进行替换index = randi([1, size(selected_population,1)]);new_population(i,:) = selected_population(index,:);endendend该示例代码实现了车间调度问题的遗传算法求解过程,具体实现了种群的初始化、适应度计算、选择、交叉、变异和替换等操作。
遗传算法matlab程序代码
遗传算法matlab程序代码遗传算法是一种优化算法,用于在给定的搜索空间中寻找最优解。
在Matlab中,可以通过以下代码编写一个基本的遗传算法:% 初始种群大小Npop = 100;% 搜索空间维度ndim = 2;% 最大迭代次数imax = 100;% 初始化种群pop = rand(Npop, ndim);% 最小化目标函数fun = @(x) sum(x.^2);for i = 1:imax% 计算适应度函数fit = 1./fun(pop);% 选择操作[fitSort, fitIndex] = sort(fit, 'descend');pop = pop(fitIndex(1:Npop), :);% 染色体交叉操作popNew = zeros(Npop, ndim);for j = 1:Npopparent1Index = randi([1, Npop]);parent2Index = randi([1, Npop]);parent1 = pop(parent1Index, :);parent2 = pop(parent2Index, :);crossIndex = randi([1, ndim-1]);popNew(j,:) = [parent1(1:crossIndex),parent2(crossIndex+1:end)];end% 染色体突变操作for j = 1:NpopmutIndex = randi([1, ndim]);mutScale = randn();popNew(j, mutIndex) = popNew(j, mutIndex) + mutScale;end% 更新种群pop = [pop; popNew];end% 返回最优解[resultFit, resultIndex] = max(fit);result = pop(resultIndex, :);以上代码实现了一个简单的遗传算法,用于最小化目标函数x1^2 + x2^2。
遗传算法matlab函数的源程序
end
end
end
%确定下一代父代个体
%确定实际子代个体数值
chi_fact=zeros(x_num,chi_num*3);
for j=1:x_num
chi_fact(j,:)=x_range(j,1)+(x_range(j,2)-x_range(j,1))*chi(j,:);
par=chi(:,chi_ada_no(1:par_num));
end ');
par_fac_exc(:,1)=x_range(:,1)+(x_range(:,2)-x_range(:,1)).*par(:,1);%父代个体最优函数值
par_fun_exc=fun(par_fac_exc);
%输出父代样本实际值
par_fact=zeros(x_num,par_num);
for i=1:x_num
par_fact(i,:)=x_range(i,1)+(x_range(i,2)-x_range(i,1))*par(i,:);
if chi_ran(3)<0.5
chi(j,i)=chi_ran(1)*par(j,chi_sel1)+(1-chi_ran(1))*par(j,chi_sel2);
else
chi(j,i)=chi_ran(2)*par(j,chi_sel1)+(1-chi_ran(2))*par(j,chi_sel2);
%例子2:
%fun=@(x) sum(x.*x-cos(18*x))+5;
%x_range=[-1,1;-1,1;-1,1;-1,1;-1,1];
遗传算法在matlab中的实现
遗传算法是一种模拟自然选择与遗传机制的优化算法,它模拟了生物进化的过程,通过优化个体的基因型来达到解决问题的目的。
在工程和科学领域,遗传算法被广泛应用于求解优化问题、寻找最优解、参数优化等领域。
而MATLAB作为一款强大的科学计算软件,拥有丰富的工具箱和编程接口,为实现遗传算法提供了便利。
下面将通过以下步骤介绍如何在MATLAB中实现遗传算法:1. 引入遗传算法工具箱需要在MATLAB环境中引入遗传算法工具箱。
在MATLAB命令窗口输入"ver",可以查看当前已安装的工具箱。
如果遗传算法工具箱未安装,可以使用MATLAB提供的工具箱管理界面进行安装。
2. 定义优化问题在实现遗传算法前,需要清楚地定义优化问题:包括问题的目标函数、约束条件等。
在MATLAB中,可以通过定义一个函数来表示目标函数,并且可以采用匿名函数的形式来灵活定义。
对于约束条件,也需要进行明确定义,以便在遗传算法中进行约束处理。
3. 设置遗传算法参数在实现遗传算法时,需要对遗传算法的参数进行设置,包括种群大小、交叉概率、变异概率、迭代次数等。
这些参数的设置将会直接影响遗传算法的收敛速度和优化效果。
在MATLAB中,可以通过设置遗传算法工具箱中的相关函数来完成参数的设置。
4. 编写遗传算法主程序编写遗传算法的主程序,主要包括对适应度函数的计算、选择、交叉、变异等操作。
在MATLAB中,可以利用遗传算法工具箱提供的相关函数来实现这些操作,简化了遗传算法的实现过程。
5. 运行遗传算法将编写好的遗传算法主程序在MATLAB环境中运行,并观察优化结果。
在运行过程中,可以对结果进行实时监测和分析,以便对遗传算法的参数进行调整和优化。
通过以上步骤,可以在MATLAB中实现遗传算法,并应用于实际的优化问题与工程应用中。
遗传算法的实现将大大提高问题的求解效率与精度,为工程领域带来更多的便利与可能性。
总结:遗传算法在MATLAB中的实现涉及到了引入遗传算法工具箱、定义优化问题、设置算法参数、编写主程序和运行算法等步骤。
遗传算法matlab程序
遗传算法matlab程序编码>> function ret=Code(lenchrom,bound)%本函数将变量编码成染色体,用于随机初始化一个种群% lenchrom input : 染色体长度% bound input : 变量的取值范围% ret output: 染色体的编码值flag=0;while flag==0pick=rand(1,length(lenchrom));ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %线性插值,编码结果以实数向量存入ret 中flag=test(lenchrom,bound,ret); %检验染色体的可行性end交叉操作function ret=Cross(pcross,lenchrom,chrom,sizepop,bound)%本函数完成交叉操作% pcorss input : 交叉概率% lenchrom input : 染色体的长度% chrom input : 染色体群% sizepop input : 种群规模% ret output : 交叉后的染色体for i=1:sizepop %每一轮for循环中,可能会进行一次交叉操作,染色体是随机选择的,交叉位置也是随机选择的,%但该轮for循环中是否进行交叉操作则由交叉概率决定(continue 控制)% 随机选择两个染色体进行交叉pick=rand(1,2);while prod(pick)==0pick=rand(1,2);endindex=ceil(pick.*sizepop);% 交叉概率决定是否进行交叉pick=rand;while pick==0pick=rand;endif pick>pcrosscontinue;endflag=0;while flag==0% 随机选择交叉位pick=rand;while pick==0pick=rand;endpos=ceil(pick.*sum(lenchrom)); %随机选择进行交叉的位置,即选择第几个变量进行交叉,注意:两个染色体交叉的位置相同pick=rand; %交叉开始v1=chrom(index(1),pos);v2=chrom(index(2),pos);chrom(index(1),pos)=pick*v2+(1-pick)*v1;chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉结束flag1=test(lenchrom,bound,chrom(index(1),:)); %检验染色体1的可行性flag2=test(lenchrom,bound,chrom(index(2),:)); %检验染色体2的可行性if flag1*flag2==0flag=0;else flag=1;end %如果两个染色体不是都可行,则重新交叉endendret=chrom;解码function ret=Decode(lenchrom,bound,code,opts)% 本函数对染色体进行解码% lenchrom input : 染色体长度% bound input : 变量取值范围% code input :编码值% opts input : 解码方法标签% ret output: 染色体的解码值switch optscase 'binary' % binary codingfor i=length(lenchrom):-1:1data(i)=bitand(code,2^lenchrom(i)-1); %并低十位,然后将低十位转换成十进制数存在data(i)里面code=(code-data(i))/(2^lenchrom(i)); %低十位清零,然后右移十位endret=bound(:,1)'+data./(2.^lenchrom-1).*(bound(:,2)-bound(:,1))'; %分段解码,以实数向量的形式存入ret中case 'grey' % grey codingfor i=sum(lenchrom):-1:2code=bitset(code,i-1,bitxor(bitget(code,i),bitget(code,i-1)));endfor i=length(lenchrom):-1:1data(i)=bitand(code,2^lenchrom(i)-1);code=(code-data(i))/(2^lenchrom(i));endret=bound(:,1)'+data./(2.^lenchrom-1).*(bound(:,2)-bound(:,1))'; %分段解码,以实数向量的形式存入ret中case 'float' % float codingret=code; %解码结果就是编码结果(实数向量),存入ret中end适应度函数function error = fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn)%该函数用来计算适应度值%x input 个体%inputnum input 输入层节点数%outputnum input 隐含层节点数%net input 网络%inputn input 训练输入数据%outputn input 训练输出数据%error output 个体适应度值%提取w1=x(1:inputnum*hiddennum);B1=x(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);w2=x(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*out putnum);B2=x(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hid dennum+hiddennum*outputnum+outputnum);%网络进化参数net.trainParam.epochs=20;net.trainParam.lr=0.1;net.trainParam.goal=0.00001;net.trainParam.show=100;net.trainParam.showWindow=0;%网络权值赋值net.iw{1,1}=reshape(w1,hiddennum,inputnum);net.lw{2,1}=reshape(w2,outputnum,hiddennum);net.b{1}=reshape(B1,hiddennum,1);net.b{2}=B2;。
(完整版)遗传算法matlab实现源程序
附页:一.遗传算法源程序:clc; clear;population;%评价目标函数值for uim=1:popsizevector=population(uim,:);obj(uim)=hanshu(hromlength,vector,phen);end%obj%min(obj)clear uim;objmin=min(obj);for sequ=1:popsizeif obj(sequ)==objminopti=population(sequ,:);endendclear sequ;fmax=22000;%==for gen=1:maxgen%选择操作%将求最小值的函数转化为适应度函数for indivi=1:popsizeobj1(indivi)=1/obj(indivi);endclear indivi;%适应度函数累加总合total=0;for indivi=1:popsizetotal=total+obj1(indivi);endclear indivi;%每条染色体被选中的几率for indivi=1:popsizefitness1(indivi)=obj1(indivi)/total;endclear indivi;%各条染色体被选中的范围for indivi=1:popsizefitness(indivi)=0;for j=1:indivifitness(indivi)=fitness(indivi)+fitness1(j);endendclear j;fitness;%选择适应度高的个体for ranseti=1:popsizeran=rand;while (ran>1||ran<0)ran=rand;endran;if ran〈=fitness(1)newpopulation(ranseti,:)=population(1,:);elsefor fet=2:popsizeif (ran〉fitness(fet—1))&&(ran<=fitness(fet))newpopulation(ranseti,:)=population(fet,:);endendendendclear ran;newpopulation;%交叉for int=1:2:popsize-1popmoth=newpopulation(int,:);popfath=newpopulation(int+1,:);popcross(int,:)=popmoth;popcross(int+1,:)=popfath;randnum=rand;if(randnum〈 P>cpoint1=round(rand*hromlength);cpoint2=round(rand*hromlength);while (cpoint2==cpoint1)cpoint2=round(rand*hromlength);endif cpoint1>cpoint2tem=cpoint1;cpoint1=cpoint2;cpoint2=tem;endcpoint1;cpoint2;for term=cpoint1+1:cpoint2for ss=1:hromlengthif popcross(int,ss)==popfath(term)tem1=popcross(int,ss);popcross(int,ss)=popcross(int,term);popcross(int,term)=tem1;endendclear tem1;endfor term=cpoint1+1:cpoint2for ss=1:hromlengthif popcross(int+1,ss)==popmoth(term)tem1=popcross(int+1,ss);popcross(int+1,ss)=popcross(int+1,term);popcross(int+1,term)=tem1;endendclear tem1;endendclear term;endclear randnum;popcross;%变异操作newpop=popcross;for int=1:popsizerandnum=rand;if randnumcpoint12=round(rand*hromlength);cpoint22=round(rand*hromlength);if (cpoint12==0)cpoint12=1;endif (cpoint22==0)cpoint22=1;endwhile (cpoint22==cpoint12)cpoint22=round(rand*hromlength);if cpoint22==0;cpoint22=1;endendtemp=newpop(int,cpoint12);newpop(int,cpoint12)=newpop(int,cpoint22);newpop(int,cpoint22)=temp;。
TSP遗传算法
%TSP问题(又名:旅行商问题,货郎担问题)遗传算法通用matlab程序%D是距离矩阵,n为种群个数,建议取为城市个数的1~2倍,%C为停止代数,遗传到第C代时程序停止,C的具体取值视问题的规模和耗费的时间而定%m为适应值归一化淘汰加速指数,最好取为1,2,3,4 ,不宜太大%alpha为淘汰保护指数,可取为0~1之间任意小数,取1时关闭保护功能,最好取为0.8~1.0 %R为最短路径,Rlength为路径长度function [R,Rlength]=geneticTSP(D,n,C,m,alpha)[N,NN]=size(D);farm=zeros(n,N);%用于存储种群for i=1:nfarm(i,:)=randperm(N);%随机生成初始种群endR=farm(1,:);%存储最优种群len=zeros(n,1);%存储路径长度fitness=zeros(n,1);%存储归一化适应值counter=0;while counter<Cfor i=1:nlen(i,1)=myLength(D,farm(i,:));%计算路径长度endmaxlen=max(len);minlen=min(len);fitness=fit(len,m,maxlen,minlen);%计算归一化适应值rr=find(len==minlen);R=farm(rr(1,1),:);%更新最短路径FARM=farm;%优胜劣汰,nn记录了复制的个数nn=0;for i=1:nif fitness(i,1)>=alpha*randnn=nn+1;FARM(nn,:)=farm(i,:);endendFARM=FARM(1:nn,:);[aa,bb]=size(FARM);%交叉和变异while aa<nif nn<=2nnper=randperm(2);elsennper=randperm(nn);endA=FARM(nnper(1),:);B=FARM(nnper(2),:);[A,B]=intercross(A,B);FARM=[FARM;A;B];[aa,bb]=size(FARM);endif aa>nFARM=FARM(1:n,:);%保持种群规模为nendfarm=FARM;clear FARMcounter=counter+1endRlength=myLength(D,R);function [a,b]=intercross(a,b)L=length(a);if L<=10%确定交叉宽度W=1;elseif ((L/10)-floor(L/10))>=rand&&L>10W=ceil(L/10);elseW=floor(L/10);endp=unidrnd(L-W+1);%随机选择交叉范围,从p到p+W for i=1:W%交叉x=find(a==b(1,p+i-1));y=find(b==a(1,p+i-1));[a(1,p+i-1),b(1,p+i-1)]=exchange(a(1,p+i-1),b(1,p+i-1)); [a(1,x),b(1,y)]=exchange(a(1,x),b(1,y));endfunction [x,y]=exchange(x,y)temp=x;x=y;y=temp;% 计算路径的子程序function len=myLength(D,p)[N,NN]=size(D);len=D(p(1,N),p(1,1));for i=1:(N-1)len=len+D(p(1,i),p(1,i+1));end%计算归一化适应值子程序function fitness=fit(len,m,maxlen,minlen)fitness=len;for i=1:length(len)fitness(i,1)=(1-((len(i,1)-minlen)/(maxlen-minlen+0.000001))).^m; end一个C++的程序://c++的程序#include<iostream.h>#include<stdlib.h>template<class T>class Graph{public:Graph(int vertices=10){n=vertices;e=0;}~Graph(){}virtual bool Add(int u,int v,const T& w)=0;virtual bool Delete(int u,int v)=0;virtual bool Exist(int u,int v)const=0;int Vertices()const{return n;}int Edges()const{return e;}protected:int n;int e;};template<class T>class MGraph:public Graph<T>{public:MGraph(int Vertices=10,T noEdge=0);~MGraph();bool Add(int u,int v,const T& w);bool Delete(int u,int v);bool Exist(int u,int v)const;void Floyd(T**& d,int**& path);void print(int Vertices);private:T NoEdge;T** a;};template<class T>MGraph<T>::MGraph(int V ertices,T noEdge){n=V ertices;NoEdge=noEdge;a=new T* [n];for(int i=0;i<n;i++){a[i]=new T[n];a[i][i]=0;for(int j=0;j<n;j++)if(i!=j)a[i][j]=NoEdge;}}template<class T>MGraph<T>::~MGraph(){for(int i=0;i<n;i++)delete[]a[i];delete[]a;}template<class T>bool MGraph<T>::Exist(int u,int v)const{if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]==NoEdge)return false; return true;}template<class T>bool MGraph<T>::Add(int u,int v,const T& w){if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]!=NoEdge){cerr<<"BadInput!"<<endl;return false;}a[u][v]=w;e++;return true;}template<class T>bool MGraph<T>:delete(int u,int v){if(u<0||v<0||u>n-1||v>n-1||u==v||a[u][v]==NoEdge){ cerr<<"BadInput!"<<endl;return false;}a[u][v]=NoEdge;e--;return true;}template<class T>void MGraph<T>::Floyd(T**& d,int**& path) {d=new T* [n];path=new int* [n];for(int i=0;i<n;i++){d[i]=new T[n];path[i]=new int[n];for(int j=0;j<n;j++){d[i][j]=a[i][j];if(i!=j&&a[i][j]<NoEdge)path[i][j]=i;else path[i][j]=-1;}}for(int k=0;k<n;k++){for(i=0;i<n;i++)for(int j=0;j<n;j++)if(d[i][k]+d[k][j]<d[i][j]){d[i][j]=d[i][k]+d[k][j];path[i][j]=path[k][j];}}}template<class T>void MGraph<T>::print(int Vertices){for(int i=0;i<Vertices;i++)for(int j=0;j<Vertices;j++){cout<<a[i][j]<<' ';if(j==Vertices-1)cout<<endl;}}#define noEdge 10000#include<iostream.h>void main(){cout<<"请输入该图的节点数:"<<endl;int vertices;cin>>vertices;MGraph<float> b(vertices,noEdge);cout<<"请输入u,v,w:"<<endl;int u,v;float w;cin>>u>>v>>w;while(w!=noEdge){//u=u-1;b.Add(u-1,v-1,w);b.Add(v-1,u-1,w);cout<<"请输入u,v,w:"<<endl;cin>>u>>v>>w;}b.print(vertices);int** Path;int**& path=Path;float** D;float**& d=D;b.Floyd(d,path);for(int i=0;i<vertices;i++){for(int j=0;j<vertices;j++){cout<<Path[i][j]<<' ';if(j==vertices-1)cout<<endl;}}int *V;V=new int[vertices+1];cout<<"请输入任意一个初始H-圈:"<<endl;for(int n=0;n<=vertices;n++){cin>>V[n];}for(n=0;n<55;n++){for(i=0;i<n-1;i++){for(int j=0;j<n-1;j++){if(i+1>0&&j>i+1&&j<n-1){if(D[V[i]][V[j]]+D[V[i+1]][V[j+1]]<D[V[i]][V[i+1]]+D[V[j]][V[j+1]]){ int l;l=V[i+1];V[i+1]=V[j];V[j]=l;}}}}}float total=0;cout<<"最小回路:"<<endl;for(i=0;i<=vertices;i++){cout<<V[i]+1<<' ';}cout<<endl;for(i=0;i<vertices;i++)total+=D[V[i]][V[i+1]];cout<<"最短路径长度:"<<endl;cout<<total;}C语言程序:#include<stdio.h>#include<stdlib.h>#include<math.h>#include<alloc.h>#include<conio.h>#include<float.h>#include<time.h>#include<graphics.h>#include<bios.h>#define maxpop 100#define maxstring 100struct pp{unsigned char chrom[maxstring];float x,fitness;unsigned int parent1,parent2,xsite;};struct pp *oldpop,*newpop,*p1;unsigned int popsize,lchrom,gem,maxgen,co_min,jrand;unsigned int nmutation,ncross,jcross,maxpp,minpp,maxxy;float pcross,pmutation,sumfitness,avg,max,min,seed,maxold,oldrand[maxstring]; unsigned char x[maxstring],y[maxstring];float *dd,ff,maxdd,refpd,fm[201];FILE *fp,*fp1;float objfunc(float);void statistics();int select();int flip(float);int crossover();void generation();void initialize();void report();float decode();void crtinit();void inversion();float random1();void randomize1();main(){unsigned int gen,k,j,tt;char fname[10];float ttt;clrscr();co_min=0;if((oldpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL) {printf("memory requst fail!\n");exit(0);}if((dd=(float *)farmalloc(maxstring*maxstring*sizeof(float)))==NULL) {printf("memory requst fail!\n");exit(0);}if((newpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL) {printf("memory requst fail!\n");exit(0);}if((p1=(struct pp *)farmalloc(sizeof(struct pp)))==NULL){printf("memory requst fail!\n");exit(0);}for(k=0;k<maxpop;k++) oldpop[k].chrom[0]='\0';for(k=0;k<maxpop;k++) newpop[k].chrom[0]='\0';printf("Enter Result Data Filename:");gets(fname);if((fp=fopen(fname,"w+"))==NULL){printf("cannot open file\n");exit(0);}gen=0;randomize();initialize();fputs("this is result of the TSP problem:",fp);fprintf(fp,"city: %2d psize: %3d Ref.TSP_path: %f\n",lchrom,popsize,refpd); fprintf(fp,"Pc: %f Pm: %f Seed: %f\n",pcross,pmutation,seed);fprintf(fp,"X site:\n");for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n");fprintf(fp,"%5d",x[k]);}fprintf(fp,"\n Y site:\n");for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n");fprintf(fp,"%5d",y[k]);}fprintf(fp,"\n");crtinit();statistics(oldpop);report(gen,oldpop);getch();maxold=min;fm[0]=100.0*oldpop[maxpp].x/ff;do {gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff;report(gen,oldpop);gotoxy(30,25);ttt=clock()/18.2;tt=ttt/60;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0); printf("Min=%6.4f Nm:%d\n",min,co_min);}while((gen<100)&&!bioskey(1));printf("\n gen= %d",gen);do{gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff;report(gen,oldpop);if((gen%100)==0)report(gen,oldpop);gotoxy(30,25);ttt=clock()/18.2;tt=ttt/60;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0); printf("Min=%6.4f Nm:%d\n",min,co_min);}while((gen<maxgen)&&!bioskey(1));getch();for(k=0;k<lchrom;k++){if((k%16)==0)fprintf(fp,"\n");fprintf(fp,"%5d",oldpop[maxpp].chrom[k]);}fprintf(fp,"\n");fclose(fp);farfree(dd);farfree(p1);farfree(oldpop);farfree(newpop);restorecrtmode();exit(0);}/*%%%%%%%%%%%%%%%%*/float objfunc(float x1){float y;y=100.0*ff/x1;return y;}/*&&&&&&&&&&&&&&&&&&&*/void statistics(pop)struct pp *pop;{int j;sumfitness=pop[0].fitness;min=pop[0].fitness;max=pop[0].fitness;maxpp=0;minpp=0;for(j=1;j<popsize;j++){sumfitness=sumfitness+pop[j].fitness;if(pop[j].fitness>max){max=pop[j].fitness;maxpp=j;}if(pop[j].fitness<min){min=pop[j].fitness;minpp=j;}}avg=sumfitness/(float)popsize;}/*%%%%%%%%%%%%%%%%%%%%*/void generation(){unsigned int k,j,j1,j2,i1,i2,mate1,mate2;float f1,f2;j=0;do{mate1=select();pp:mate2=select();if(mate1==mate2)goto pp;crossover(oldpop[mate1].chrom,oldpop[mate2].chrom,j); newpop[j].x=(float)decode(newpop[j].chrom);newpop[j].fitness=objfunc(newpop[j].x);newpop[j].parent1=mate1;newpop[j].parent2=mate2;newpop[j].xsite=jcross;newpop[j+1].x=(float)decode(newpop[j+1].chrom); newpop[j+1].fitness=objfunc(newpop[j+1].x);newpop[j+1].parent1=mate1;newpop[j+1].parent2=mate2;newpop[j+1].xsite=jcross;if(newpop[j].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j].chrom[k];oldpop[minpp].x=newpop[j].x;oldpop[minpp].fitness=newpop[j].fitness;co_min++;return;}if(newpop[j+1].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j+1].chrom[k];oldpop[minpp].x=newpop[j+1].x;oldpop[minpp].fitness=newpop[j+1].fitness;co_min++;return;}j=j+2;}while(j<popsize);}/*%%%%%%%%%%%%%%%%%*/void initdata(){unsigned int ch,j;clrscr();printf("-----------------------\n");printf("A SGA\n");printf("------------------------\n");/*pause();*/clrscr();printf("*******SGA DATA ENTRY AND INITILIZATION *******\n"); printf("\n");printf("input pop size");scanf("%d",&popsize);printf("input chrom length");scanf("%d",&lchrom);printf("input max generations");scanf("%d",&maxgen);printf("input crossover probability");scanf("%f",&pcross);printf("input mutation prob");scanf("%f",&pmutation);randomize1();clrscr();nmutation=0;ncross=0;}/*%%%%%%%%%%%%%%%%%%%%*/void initreport(){int j,k;printf("pop size=%d\n",popsize);printf("chromosome length=%d\n",lchrom);printf("maxgen=%d\n",maxgen);printf("pmutation=%f\n",pmutation);printf("pcross=%f\n",pcross);printf("initial generation statistics\n");printf("ini pop max fitness=%f\n",max);printf("ini pop avr fitness=%f\n",avg);printf("ini pop min fitness=%f\n",min);printf("ini pop sum fit=%f\n",sumfitness);}void initpop(){unsigned char j1;unsigned int k5,i1,i2,j,i,k,j2,j3,j4,p5[maxstring]; float f1,f2;j=0;for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=k;for(k=0;k<lchrom;k++)p5[k]=oldpop[j].chrom[k];randomize();for(;j<popsize;j++){j2=random(lchrom);for(k=0;k<j2+20;k++){j3=random(lchrom);j4=random(lchrom);j1=p5[j3];p5[j3]=p5[j4];p5[j4]=j1;}for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=p5[k];}for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++)dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);for(j=0;j<popsize;j++){oldpop[j].x=(float)decode(oldpop[j].chrom); oldpop[j].fitness=objfunc(oldpop[j].x); oldpop[j].parent1=0;oldpop[j].parent2=0;oldpop[j].xsite=0;}}/*&&&&&&&&&&&&&&&&&*/void initialize(){int k,j,minx,miny,maxx,maxy;initdata();minx=0;miny=0;maxx=0;maxy=0;for(k=0;k<lchrom;k++){x[k]=rand();if(x[k]>maxx)maxx=x[k];if(x[k]<minx)minx=x[k];y[k]=rand();if(y[k]>maxy)maxy=y[k];if(y[k]<miny)miny=y[k];}if((maxx-minx)>(maxy-miny)){maxxy=maxx-minx;}else {maxxy=maxy-miny;}maxdd=0.0;for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++){dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);if(maxdd<dd[k*lchrom+j])maxdd=dd[k*lchrom+j]; }refpd=dd[lchrom-1];for(k=0;k<lchrom;k++)refpd=refpd+dd[k*lchrom+k+2];for(j=0;j<lchrom;j++)dd[j*lchrom+j]=4.0*maxdd;ff=(0.765*maxxy*pow(lchrom,0.5));minpp=0;min=dd[lchrom-1];for(j=0;j<lchrom-1;j++){if(dd[lchrom*j+lchrom-1]<min){min=dd[lchrom*j+lchrom-1];minpp=j;}}initpop();statistics(oldpop);initreport();}/*&&&&&&&&&&&&&&&&&&*/void report(int l,struct pp *pop){int k,ix,iy,jx,jy;unsigned int tt;float ttt;cleardevice();gotoxy(1,1);printf("city:%4d para_size:%4d maxgen:%4d ref_tour:%f\n",lchrom,popsize,maxgen,refpd);printf("ncross:%4d Nmutation:%4d Rungen:%4d A VG=%8.4f MIN=%8.4f\n\n" ,ncross,nmutation,l,avg,min);printf("inpath:%6.4f Minpath length:%10.4f Ref_co_tour:%f\n",pop[maxpp].x/maxxy,pop[maxpp].x,ff);printf("Co_minpath:%6.4f Maxfit:%10.8f",100.0*pop[maxpp].x/ff,pop[maxpp].fitness);ttt=clock()/18.2;tt=ttt/60;printf("Run clock:%2d:%2d:%4d.2f\n",tt/60,tt%60,ttt-tt*60.0);setcolor(1%15+1);for(k=0;k<lchrom-1;k++){ix=x[pop[maxpp].chrom[k]];iy=y[pop[maxpp].chrom[k]]+110;jx=x[pop[maxpp].chrom[k+1]];jy=y[pop[maxpp].chrom[k+1]]+110;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}ix=x[pop[maxpp].chrom[0]];iy=y[pop[maxpp].chrom[0]]+110;jx=x[pop[maxpp].chrom[lchrom-1]];jy=y[pop[maxpp].chrom[lchrom-1]]+110;line(ix,iy,jx,jy);putpixel(jx,jy,RED);setcolor(11);outtextxy(ix,iy,"*");setcolor(12);for(k=0;k<1%200;k++){ix=k+280;iy=366-fm[k]/3;jx=ix+1;jy=366-fm[k+1]/3;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}printf("GEN:%3d",l);printf("Minpath:%f Maxfit:%f",pop[maxpp].x,pop[maxpp].fitness);printf("Clock:%2d:%2d:%4.2f\n",tt/60,tt%60,ttt-tt*60.0); }/*###############*/float decode(unsigned char *pp){int j,k,l;float tt;tt=dd[pp[0]*lchrom+pp[lchrom-1]];for(j=0;j<lchrom-1;j++){tt=tt+dd[pp[j]*lchrom+pp[j+1]];}l=0;for(k=0;k<lchrom-1;k++)for(j=k+1;j<lchrom;j++){if(pp[j]==pp[k])l++;}return tt+4*l*maxdd;}/*%%%%%%%%%%%%%%%%%%*/void crtinit(){int driver,mode;struct palettetype p;driver=DETECT;mode=0;initgraph(&driver,&mode,"");cleardevice();}/*$$$$$$$$$$$$$$$$$$$$*/int select(){double rand1,partsum;float r1;int j;partsum=0.0;j=0;rand1=random1()*sumfitness;do{partsum=partsum+oldpop[j].fitness;j=j+1;}while((partsum<rand1)&&(j<popsize));return j-1;}/*$$$$$$$$$$$$$$$*/int crossover(unsigned char *parent1,unsigned char *parent2,int k5) {int k,j,mutate,i1,i2,j5;int j1,j2,j3,s0,s1,s2;unsigned char jj,ts1[maxstring],ts2[maxstring];float f1,f2;s0=0;s1=0;s2=0;if(flip(pcross)){jcross=random(lchrom-1);j5=random(lchrom-1);ncross=ncross+1;if(jcross>j5){k=jcross;jcross=j5;j5=k;}}else jcross=lchrom;if(jcross!=lchrom){s0=1;k=0;for(j=jcross;j<j5;j++){ts1[k]=parent1[j];ts2[k]=parent2[j];k++;}j3=k;for(j=0;j<lchrom;j++){j2=0;while((parent2[j]!=ts1[j2])&&(j2<k)){j2++;}if(j2==k){ts1[j3]=parent2[j];j3++;}}j3=k;for(j=0;j<lchrom;j++){j2=0;while((parent1[j]!=ts2[j2])&&(j2<k)){j2++;}if(j2==k){ts2[j3]=parent1[j];j3++;}}for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=ts1[j];newpop[k5+1].chrom[j]=ts2[j];}}{for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=parent1[j];newpop[k5+1].chrom[j]=parent2[j];}mutate=flip(pmutation);if(mutate){s1=1;nmutation=nmutation+1;for(j3=0;j3<200;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5].chrom[j];newpop[k5].chrom[j]=newpop[k5].chrom[j1];newpop[k5].chrom[j1]=jj;}}mutate=flip(pmutation);if(mutate){s2=1;nmutation=nmutation+1;for(j3=0;j3<100;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5+1].chrom[j];newpop[k5+1].chrom[j]=newpop[k5+1].chrom[j1];newpop[k5+1].chrom[j1]=jj;}}}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[i2]]; f1=f1+dd[lchrom*newpop[k5].chrom[(i1+1)%lchrom]+ newpop[k5].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5].chrom[i2]+newpop[k5].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5].chrom);}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[i2]]; f1=f1+dd[lchrom*newpop[k5+1].chrom[(i1+1)%lchrom]+ newpop[k5+1].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5+1].chrom[i2]+newpop[k5+1].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5+1].chrom);}}return 1;}/*$$$$$$$$$$$$$$$*/void inversion(unsigned int k,unsigned int j,unsigned char *ss) {unsigned int l1,i;unsigned char tt;l1=(j-k)/2;for(i=0;i<l1;i++){tt=ss[k+i+1];ss[k+i+1]=ss[j-i];ss[j-i]=tt;}}/*%%%%%%%%%%%%%%%*/void randomize1(){int i;randomize();for(i=0;i<lchrom;i++)oldrand[i]=random(30001)/30000.0;jrand=0;}/*%%%%%%%%%%%*/float random1(){jrand=jrand+1;if(jrand>=lchrom){jrand=0;randomize1();}return oldrand[jrand];}/*%%%%%%%%%%*/int flip(float probability){float ppp;ppp=random(20001)/20000.0;if(ppp<=probability)return 1;return 0;}改进后用来求解VRP问题的Delphi程序:unit uEA;interfaceusesuUtilsEA, uIEA, uITSP, Classes, GaPara, windows, SysUtils, fEA_TSP;typeTIndividual = class(TInterfacedObject, IIndividual)private// The internally stored fitness valuefFitness: TFloat;fWeConstrain: integer;fBackConstrain: integer;fTimeConstrain: integer;procedure SetFitness(const Value: TFloat);function GetFitness: TFloat;function GetWeConstrain: integer;procedure SetWeConstrain(const Value: integer);procedure SetBackConstrain(const Value: integer);function GetBackConstrain: integer;function GetTimeConstrain: integer;procedure SetTimeConstrain(const Value: integer);publicproperty Fitness : TFloat read GetFitness write SetFitness;property WeConstrain :integer read GetWeConstrain write SetWeConstrain; property BackConstrain :integer read GetBackConstrain write SetBackConstrain; property TimeConstrain :integer read GetTimeConstrain write SetTimeConstrain; end;TTSPIndividual = class(TIndividual, ITSPIndividual)private// The route we travelfRouteArray : ArrayInt;fWeConstrain: integer;fBackConstrain: integer;fTimeConstrain: integer;function GetRouteArray(I: Integer): Integer;procedure SetRouteArray(I: Integer; const Value: Integer);procedure SetSteps(const Value: Integer);function GetSteps: Integer;function GetWeConstrain: integer;procedure SetWeConstrain(const Value: integer);procedure SetBackConstrain(const Value: integer);procedure SetTimeConstrain(const Value: integer);function GetBackConstrain: integer;function GetTimeConstrain: integer;public// Constructor, called with initial route sizeconstructor Create(Size : TInt); reintroduce;destructor Destroy; override;property RouteArray[I : Integer] : Integer read GetRouteArray write SetRouteArray; // The number of steps on the routeproperty Steps : Integer read GetSteps write SetSteps;property Fitness : TFloat read GetFitness write SetFitness;property WeConstrain :integer read GetWeConstrain write SetWeConstrain; property BackConstrain :integer read GetWeConstrain write SetBackConstrain; property TimeConstrain :integer read GetTimeConstrain write SetTimeConstrain; end;TTSPCreator = class(TInterfacedObject, ITSPCreator)private// The Control component we are associated withfController: ITSPController;function GetController: ITSPController;procedure SetController(const Value: ITSPController);public// Function to create a random individualfunction CreateIndividual : IIndividual;function CreateFeasibleIndividual: IIndividual;property Controller : ITSPController read GetController write SetController; end;TKillerPercentage = class(TInterfacedObject, IKillerPercentage)privatefPer: TFloat;procedure SetPercentage(const Value: TFloat);function GetPercentage: TFloat;publicfunction Kill(Pop : IPopulation): Integer;// Percentage of population to be killedproperty Percentage: TFloat read GetPercentage write SetPercentage;end;TParentSelectorTournament = class(TInterfacedObject, IParentSelector)publicfunction SelectParent(Population: IPopulation): IIndividual;end;TTSPBreederCrossover = class(TInterfacedObject, IBreeder)publicfunction BreedOffspring(PSelector: IParentSelector; Pop: IPopulation): IIndividual; end;TTSPMutator = class(TInterfacedObject, ITSPMutator)privatefTrans: TFloat;fInv: TFloat;procedure SetInv(const Value: TFloat);procedure SetTrans(const Value: TFloat);function GetInv: TFloat;function GetTrans: TFloat;publicprocedure Mutate(Individual: IIndividual);published// Probability of doing a transpositionproperty Transposition: TFloat read GetTrans write SetTrans;// Probability of doing an inversionproperty Inversion: TFloat read GetInv write SetInv;end;TTSPExaminer = class(TInterfacedObject, ITSPExaminer)private// The Control component we are associated withfController: ITSPController;function GetController: ITSPController;procedure SetController(const Value: ITSPController);public// Returns the fitness of an individual as a real number where 0 => best function GetFitness(Individual : IIndividual) : TFloat;property Controller : ITSPController read GetController write SetController; end;TPopulation = class(TInterfacedObject, IPopulation)private// The populationfPop : TInterfaceList;// Worker for breedingfBreeder: IBreeder;// Worker for killingfKiller: IKiller;// Worker for parent selectionfParentSelector: IParentSelector;// Worker for mutationfMutator: IMutator;// Worker for initial creationfCreator: ICreator;// Worker for fitness calculationfExaminer: IExaminer;// On Change eventFOnChange: TNotifyEvent;procedure Change;// Getters and Settersfunction GetIndividual(I: Integer): IIndividual;function GetCount: Integer;function GetBreeder: IBreeder;function GetCreator: ICreator;function GetExaminer: IExaminer;function GetKiller: IKiller;function GetMutator: IMutator;function GetOnChange: TNotifyEvent;function GetParentSelector: IParentSelector;procedure SetBreeder(const Value: IBreeder);procedure SetCreator(const Value: ICreator);procedure SetExaminer(const Value: IExaminer);procedure SetKiller(const Value: IKiller);procedure SetMutator(const Value: IMutator);procedure SetOnChange(const Value: TNotifyEvent);procedure SetParentSelector(const Value: IParentSelector);// not interfacedprocedure DanQuickSort(SortList: TInterfaceList; L, R: Integer; SCompare: TInterfaceCompare); procedure Sort(Compare: TInterfaceCompare);protected// Comparison function for Sort()function CompareIndividuals(I1, I2: IIndividual): Integer;// Sort the populationprocedure SortPopulation;public// The constructorconstructor Create;// The destructordestructor Destroy; override;// Adds an individual to the populationprocedure Add(New : IIndividual);// Deletes an individual from the populationprocedure Delete(I : Integer);// Runs a single generationprocedure Generation;// Initialise the populationprocedure Initialise(Size : Integer);// Clear ourselves outprocedure Clear;// Get the fitness of an individualfunction FitnessOf(I : Integer) : TFloat;// Access to the population membersproperty Pop[I : Integer] : IIndividual read GetIndividual; default;// The size of the populationproperty Count : Integer read GetCount;property ParentSelector : IParentSelector read GetParentSelector write SetParentSelector; property Breeder : IBreeder read GetBreeder write SetBreeder;property Killer : IKiller read GetKiller write SetKiller;property Mutator : IMutator read GetMutator write SetMutator;property Creator : ICreator read GetCreator write SetCreator;property Examiner : IExaminer read GetExaminer write SetExaminer;// An eventproperty OnChange : TNotifyEvent read GetOnChange write SetOnChange;end;TTSPController = class(TInterfacedObject, ITSPController) privatefXmin, fXmax, fYmin, fYmax: TFloat;{ The array of 'cities' }fCities : array of TPoint2D;{ The array of 'vehicles' }fVehicles : array of TVehicle;{ The array of 'vehicle number' }fNoVehicles : ArrayInt;/////////////////////{ The number of 'new cities' }fCityCount: Integer;{ The number of 'old cities' }foldCityCount: Integer;{ The number of 'travelers' }fTravelCount:Integer; ///////////////////////{ The number of 'depots' }fDepotCount:Integer; ///////////////////////{ Getters... }function GetCity(I: Integer): TPoint2D;function GetNoVehicle(I: Integer): TInt;function GetCityCount: Integer;function GetOldCityCount: Integer;function GetTravelCount:Integer;function GetDepotCount:Integer;function GetXmax: TFloat;function GetXmin: TFloat;function GetYmax: TFloat;function GetYmin: TFloat;{ Setters... }procedure SetCityCount(const Value: Integer);procedure SetOldCityCount(const Value: Integer); procedure SetTravelCount(const Value: Integer); ///////////// procedure SetDepotCount(const Value: Integer); ///////////// procedure SetXmax(const V alue: TFloat);procedure SetXmin(const Value: TFloat);procedure SetYmax(const V alue: TFloat);procedure SetYmin(const Value: TFloat);function TimeCostBetween(C1, C2: Integer): TFloat; function GetTimeConstraint(Individual: IIndividual): TInt; function DateSpanToMin(d1, d2: TDateTime): integer; function GetVehicleInfo(routeInt: Tint): integer; procedure writeTimeArray;procedure writeCostArray;public。
遗传算法及其MATLAB程序
遗传算法及其MATLAB实现主要参考书:MATLAB 6.5 辅助优化计算与设计飞思科技产品研发中心编著电子工业出版社2003.1遗传算法及其应用陈国良等编著人民邮电出版社1996.6主要内容:遗传算法简介遗传算法的MATLAB实现应用举例在工业工程中,许多最优化问题性质十分复杂,很难用传统的优化方法来求解.自1960年以来,人们对求解这类难解问题日益增加.一种模仿生物自然进化过程的、被称为“进化算法(evolutionary algorithm)”的随机优化技术在解这类优化难题中显示了优于传统优化算法的性能。
目前,进化算法主要包括三个研究领域:遗传算法、进化规划和进化策略。
其中遗传算法是迄今为止进化算法中应用最多、比较成熟、广为人知的算法。
一、遗传算法简介遗传算法(Genetic Algorithm, GA)最先是由美国Mic-hgan大学的John Holland于1975年提出的。
遗传算法是模拟达尔文的遗传选择和自然淘汰的生物进化过程的计算模型。
它的思想源于生物遗传学和适者生存的自然规律,是具有“生存+检测”的迭代过程的搜索算法。
遗传算法以一种群体中的所有个体为对象,并利用随机化技术指导对一个被编码的参数空间进行高效搜索。
其中,选择、交叉和变异构成了遗传算法的遗传操作;参数编码、初始群体的设定、适应度函数的设计、遗传操作设计、控制参数设定等5个要素组成了遗传算法的核心内容。
遗传算法的基本步骤:遗传算法是一种基于生物自然选择与遗传机理的随机搜索算法,与传统搜索算法不同,遗传算法从一组随机产生的称为“种群(Population)”的初始解开始搜索过程。
种群中的每个个体是问题的一个解,称为“染色体(chromos ome)”。
染色体是一串符号,比如一个二进制字符串。
这些染色体在后续迭代中不断进化,称为遗传。
在每一代中用“适值(fitness)”来测量染色体的好坏,生成的下一代染色体称为后代(offspring)。
遗传算法MATLAB完整代码
遗传算法解决简单问题%主程序:用遗传算法求解y=200*exp*x).*sin(x)在区间[-2,2]上的最大值clc;clear all;close all;global BitLengthglobal boundsbeginglobal boundsendbounds=[-2,2];precision=;boundsbegin=bounds(:,1);boundsend=bounds(:,2);%计算如果满足求解精度至少需要多长的染色体BitLength=ceil(log2((boundsend-boundsbegin)'./precision));popsize=50; %初始种群大小Generationmax=12; %最大代数pcrossover=; %交配概率pmutation=; %变异概率%产生初始种群population=round(rand(popsize,BitLength));%计算适应度,返回适应度Fitvalue和累计概率cumsump [Fitvalue,cumsump]=fitnessfun(population);Generation=1;while Generation<Generationmax+1for j=1:2:popsize%选择操作seln=selection(population,cumsump);%交叉操作scro=crossover(population,seln,pcrossover);scnew(j,:)=scro(1,:);scnew(j+1,:)=scro(2,:);%变异操作smnew(j,:)=mutation(scnew(j,:),pmutation);smnew(j+1,:)=mutation(scnew(j+1,:),pmutation);endpopulation=scnew; %产生了新的种群%计算新种群的适应度[Fitvalue,cumsump]=fitnessfun(population);%记录当前代最好的适应度和平均适应度[fmax,nmax]=max(Fitvalue);fmean=mean(Fitvalue);ymax(Generation)=fmax;ymean(Generation)=fmean;%记录当前代的最佳染色体个体x=transform2to10(population(nmax,:));%自变量取值范围是[-2,2],需要把经过遗传运算的最佳染色体整合到[-2,2]区间xx=boundsbegin+x*(boundsend-boundsbegin)/(power((boundsend),BitLength)-1);xmax(Generation)=xx;Generation=Generation+1;endGeneration=Generation-1;Bestpopulation=xx;Besttargetfunvalue=targetfun(xx);%绘制经过遗传运算后的适应度曲线。
遗传算法解决TSP问题的matlab程序
1.遗传算法解决TSP 问题(附matlab源程序)2.知n个城市之间的相互距离,现有一个推销员必须遍访这n个城市,并且每个城市3.只能访问一次,最后又必须返回出发城市。
如何安排他对这些城市的访问次序,可使其4.旅行路线的总长度最短?5.用图论的术语来说,假设有一个图g=(v,e),其中v是顶点集,e是边集,设d=(dij)6.是由顶点i和顶点j之间的距离所组成的距离矩阵,旅行商问题就是求出一条通过所有顶7.点且每个顶点只通过一次的具有最短距离的回路。
8.这个问题可分为对称旅行商问题(dij=dji,,任意i,j=1,2,3,…,n)和非对称旅行商9.问题(dij≠dji,,任意i,j=1,2,3,…,n)。
10.若对于城市v={v1,v2,v3,…,vn}的一个访问顺序为t=(t1,t2,t3,…,ti,…,tn),其中11.ti∈v(i=1,2,3,…,n),且记tn+1= t1,则旅行商问题的数学模型为:12.min l=σd(t(i),t(i+1)) (i=1,…,n)13.旅行商问题是一个典型的组合优化问题,并且是一个np难问题,其可能的路径数目14.与城市数目n是成指数型增长的,所以一般很难精确地求出其最优解,本文采用遗传算法15.求其近似解。
16.遗传算法:17.初始化过程:用v1,v2,v3,…,vn代表所选n个城市。
定义整数pop-size作为染色体的个数18.,并且随机产生pop-size个初始染色体,每个染色体为1到18的整数组成的随机序列。
19.适应度f的计算:对种群中的每个染色体vi,计算其适应度,f=σd(t(i),t(i+1)).20.评价函数eval(vi):用来对种群中的每个染色体vi设定一个概率,以使该染色体被选中21.的可能性与其种群中其它染色体的适应性成比例,既通过轮盘赌,适应性强的染色体被22.选择产生后台的机会要大,设alpha∈(0,1),本文定义基于序的评价函数为eval(vi)=al23.pha*(1-alpha).^(i-1) 。
三个遗传算法matlab程序实例
遗传算法程序(一):说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作!function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation)% Finds a maximum of a function of several variables.% fmaxga solves problems of the form:% max F(X) subject to: LB <= X <= UB% BestPop - 最优的群体即为最优的染色体群% Trace - 最佳染色体所对应的目标函数值% FUN - 目标函数% LB - 自变量下限% UB - 自变量上限% eranum - 种群的代数,取100--1000(默认200)% popsize - 每一代种群的规模;此可取50--200(默认100)% pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8)% pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1)% pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2)% options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编%码,option(2)设定求解精度(默认1e-4)%% ------------------------------------------------------------------------T1=clock;if nargin<3, error('FMAXGA requires at least three input arguments'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[LB;UB]';bits=[];VarNum=size(bounds,1);precision=options(2);%由求解精度确定二进制编码长度bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间[Pop]=InitPopGray(popsize,bits);%初始化种群[m,n]=size(Pop);NewPop=zeros(m,n);children1=zeros(1,n);children2=zeros(1,n);pm0=pMutation;BestPop=zeros(eranum,n);%分配初始解空间BestPop,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度end[MaxValue,Index]=max(value);BestPop(i,:)=Pop(Index,:);Trace(i,1)=MaxValue;Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率%round(unidrnd(eranum-i)/eranum)[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位Pop=InversionPop;%更新pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);%随着种群向前进化,逐步增大变异率至1/2交叉率p(i)=pMutation;i=i+1;endt=1:eranum;plot(t,Trace(:,1)');title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');[MaxFval,I]=max(Trace(:,1));X=Trace(I,(2:length(bits)+1));hold on; plot(I,MaxFval,'*');text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf ('进化到%d 代,自变量为%s 时,得本次求解的最优值%f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:)));disp(str1);%figure(2);plot(t,p);%绘制变异值增大过程T2=clock;elapsed_time=T2-T1;if elapsed_time(6)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;end %像这种程序当然不考虑运行上小时啦str2=sprintf('程序运行耗时%d 小时%d 分钟%.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%初始化种群%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点function [initpop]=InitPopGray(popsize,bits)len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)initpop(i,:)=pop(1:end-1);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individual%解码function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=bval((cs(i)+1):cs(i+1));fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);end%选择操作%采用基于轮盘赌法的非线性排名选择%各个体成员按适应值从大到小分配选择概率:%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中P(0)>P(1)>...>P(n), sum(P(i))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=fit/sum(fit);%计算各个体相对适应度(0,1)q=max(selectprob);%选择最优的概率x=zeros(m,2);x(:,1)=[m:-1:1]';[y x(:,2)]=sort(selectprob);r=q/(1-(1-q)^m);%标准分布基值newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率newfit=cumsum(newfit);%计算各选择概率之和rNums=sort(rand(m,1));fitIn=1;newIn=1;while newIn<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=rand(1,m);y1=find(r<pCross);y2=find(r>=pCross);len=length(y1);if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endif length(y1)>=2for i=0:2:length(y1)-2if opts==0[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));else[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:));endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=round(rand(1,n));%随机生成掩码crossposition=find(hidecode==1);holdposition=find(hidecode==0);children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因%采用多点交叉,交叉点数由变量数决定function [Children1,Children2]=MultiPointCross(Parent1,Parent2)global n Children1 Children2 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));end%变异操作function [NewPop]=Mutation(OldPop,pMutation,VarNum)global m n NewPopr=rand(1,m);position=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;endendendendNewPop=OldPop;%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1));NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);endendend遗传算法程序(二):function youhuafunD=code;N=50; % Tunablemaxgen=50; % Tunablecrossrate=0.5; %Tunablemuterate=0.08; %Tunablegeneration=1;num = length(D);fatherrand=randint(num,N,3);score = zeros(maxgen,N);while generation<=maxgenind=randperm(N-2)+2; % 随机配对交叉A=fatherrand(:,ind(1:(N-2)/2));B=fatherrand(:,ind((N-2)/2+1:end));% 多点交叉rnd=rand(num,(N-2)/2);ind=rnd tmp=A(ind);A(ind)=B(ind);B(ind)=tmp;% % 两点交叉% for kk=1:(N-2)/2% rndtmp=randint(1,1,num)+1;% tmp=A(1:rndtmp,kk);% A(1:rndtmp,kk)=B(1:rndtmp,kk);% B(1:rndtmp,kk)=tmp;% endfatherrand=[fatherrand(:,1:2),A,B];% 变异rnd=rand(num,N);ind=rnd [m,n]=size(ind);tmp=randint(m,n,2)+1;tmp(:,1:2)=0;fatherrand=tmp+fatherrand;fatherrand=mod(fatherrand,3);% fatherrand(ind)=tmp;%评价、选择scoreN=scorefun(fatherrand,D);% 求得N个个体的评价函数score(generation,:)=scoreN;[scoreSort,scoreind]=sort(scoreN);sumscore=cumsum(scoreSort);sumscore=sumscore./sumscore(end);childind(1:2)=scoreind(end-1:end);for k=3:Ntmprnd=rand;tmpind=tmprnd difind=[0,diff(tmpind)];if ~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind);generation=generation+1;end% scoremaxV=max(score,[],2);minV=11*300-maxV;plot(minV,'*');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;save DData Dfunction D=codeload youhua.mat% properties F2 and F3F1=A(:,1);F2=A(:,2);F3=A(:,3);if (max(F2)>1450)||(min(F2)<=900)error('DATA property F2 exceed it''s range (900,1450]') end% get group property F1 of data, according to F2 valueF4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[F1,F2,F3,F4];function ScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4*ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);ScoreN=ones(1,N)*300*11;% 这里有待优化for k=1:NFF4k=FF4rnd(:,k);for ite=1:11F0index=find(FF4k==ite);if ~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;遗传算法程序(三):%IAGAfunction best=gaclearMAX_gen=200; %最大迭代步数best.max_f=0; %当前最大的适应度STOP_f=14.5; %停止循环的适应度RANGE=[0 255]; %初始取值范围[0 255] SPEEDUP_INTER=5; %进入加速迭代的间隔advance_k=0; %优化的次数popus=init; %初始化for gen=1:MAX_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;function popus=init%初始化M=50;%种群个体数目N=30;%编码长度popus=round(rand(M,N));return;function fitness=fit(popus,RANGE)%求适应度[M,N]=size(popus);fitness=zeros(M,1);%适应度f=zeros(M,1);%函数值A=RANGE(1);B=RANGE(2);%初始取值范围[0 255]for m=1:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_std=(f-min(f))./(max(f)-min(f));%函数值标准化fitness.f=f;fitness.f_std=f_std;fitness.x=x; return;function picked=choose(popus,fitness)%选择f=fitness.f;f_std=fitness.f_std;[M,N]=size(popus);choose_N=3; %选择choose_N对双亲picked=zeros(choose_N,2); %记录选择好的双亲p=zeros(M,1); %选择概率d_order=zeros(M,1);%把父代个体按适应度从大到小排序f_t=sort(f,'descend');%将适应度按降序排列for k=1:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(1)=ceil(rand*N);%生成杂交位置p(2)=ceil(rand*N);p=sort(p);t=popus(picked(cn,1),p(1):p(2));popus(picked(cn,1),p(1):p(2))=popus(picked(cn,2),p(1):p(2));popus(picked(cn,2),p(1):p(2))=t;endreturn;function popus=aberrance(popus,picked) %变异P_a=0.05;%变异概率[M,N]=size(popus);[M_p,N_p]=size(picked);U=rand(1,2);for kp=1:M_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand;if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)遗传算法优化pid参数matlab程序chap5_4m%GA(Generic Algorithm) program to optimize Parameters of PID clear all;clear all;global rin yout timefG=100;Size=30;CodeL=10;MinX(1)=zeros(1);MaxX(1)=20*ones(1);MinX(2)=zeros(1);MaxX(2)=1.0*ones(1);MinX(3)=zeros(1);MaxX(3)=1.0*ones(1);E=round(rand(Size,3*CodeL));%Initian Code!BsJ=0;for kg=1:1:Gtime(kg)=kg;for s=1:1:Sizem=E(s,:);y1=0;y2=0;y3=0;m1=m(1:1:CodeL);for i=1:1:CodeLy1=y1+m1(i)*2^(i-1);endKpid(s,1)=(MaxX(1)-MinX(1))*y1/1023+MinX(1);m2=m(CodeL+1:1:2*CodeL);for i=1:1:CodeLy2=y2+m2(i)*2^(i-1);endKpid(s,2)=(MaxX(2)-MinX(2))*y2/1023+MinX(2);m3=m(2*CodeL+1:1:3*CodeL);for i=1:1:CodeLy3=y3+m3(i)*2^(i-1);endKpid(s,3)=(MaxX(3)-MinX(3))*y3/1023+MinX(3);%*******Step 1:Evaluate Best J*******Kpidi=Kpid(s,:);[Kpidi,BsJ]=chap5_3f(Kpidi,BsJ);BsJi(s)=BsJ;end[OderJi,IndexJi]=sort(BsJi);BestJ(kg)=OderJi(1);BJ=BestJ(kg);Ji=BsJi+1e-10;fi=1./Ji;%Cm=max(Ji);%fi=Cm-Ji; %Avoiding deviding zero[Oderfi,Indexfi]=sort(fi);%Arranging fi small to bigger%Bestfi=Oderfi(Size); %Let Bestfi=max(fi)%BestS=Kpid(Indexfi(Size),:); %Let BestS=E(m),m is the Indexfi belong to %max(fi)Bestfi=Oderfi(Size);%Let Bestfi=max(fi)BestS=E(Indexfi(Size),:);%Let BestS=E(m),m is the Indexfi belong to max(fi)kgBJBestS;%****Step 2:Select and Reproduct Operation***fi_sum=sum(fi);fi_Size=(Oderfi/fi_sum)*Size;fi_S=floor(fi_Size); %Selecting Bigger fi valuekk=1;for i=1:1:Sizefor j=1:1:fi_S(i) %Select and ReproduceTempE(kk,:)=E(Indexfi(i),:);kk=kk+1; %kk is used to reproduce endend%**********Step 3:Crossover Operation******pc=0.06;n=ceil(20*rand);for i=1:2:(Size-1)temp=rand;if pc>tempfor j=n:1:20TempE(i,j)=E(i+1,j);TempE(i+1,j)=E(i,j);endendendTempE(Size,:)=BestS;E=TempE;%***************Step 4: Mutation Operation************** %pm=0.001;pm=0.001-[1:1:Size]*(0.001)/Size;%Bigger fi,smaller pm %pm=0.0; %No mutation%pm=0.1; %Big mutationfor i=1:1:Sizefor j=1:1:3*CodeLtemp=rand;if pm>temp %Mutation Conditionif TempE(i,j)==0TempE(i,j)=1;elseTempE(i,j)=0;endendendend%Guarantee TempE(Size,:)belong to the best individual TempE(Size,:)=BestS;E=TempE;%***************************************************endBestfiBestSKpidiBest_J=BestJ(G)figure(1);plot(time,BestJ);xlabel('Time');ylabel('Best J');figure(2);plot(timef,rin,'r',timef,yout,'b');xlabel('Time(s)');ylabel('ran,yout');****************************************************** chap5_3f.mfunction [Kpidi,BsJ]=pid_gaf(Kpidi,BsJ)global rin yout timefts=0.001;sys=tf(400,[1,50,0]);dsys=c2d(sys,ts,'z');[num,den]=tfdata(dsys,'v');rin=1.0;u_1=0.0;u_2=0.0;y_1=0.0;y_2=0.0;x=[0,0,0]';B=0;error_1=0;tu=1;s=0;P=100;for k=1:1:Ptimef(k)=k*ts;r(k)=rin;u(k)=Kpidi(1)*x(1)+Kpidi(2)*x(2)+Kpidi(3)*x(3);if u(k)>=10u(k)=10;endif u(k)<=-10u(k)=-10;endyout(k)=-den(2)*y_1-den(3)*y_2+num(2)*u_1+num(3)*u_2;error(k)=r(k)-yout(k);%-------------------Return of PID parameters----------------u_2=u_1;u_1=u(k);y_2=y_1;y_1=yout(k);x(1)=error(k); % Calculating Px(2)=(error(k)-error_1)/ts; % Dx(3)=x(3)+error(k)*ts; % Ierror_2=error_1;error_1=error(k);if s==0if yout(k)>0.95&yout(k)<1.05tu=timef(k);s=1;endendendfor i=1:1:PJi(i)=0.999*abs(error(i))+0.01*u(i)^2*0.1;B=B+Ji(i);if i>1erry(i)=yout(i)-yout(i-1);if erry(i)<0B=B+100*abs(erry(i));endendendBsj=B+0.2*tu*10。
matlab遗传算法设计
matlab遗传算法设计在MATLAB中设计遗传算法需要遵循以下步骤:1.定义问题参数:首先,你需要定义问题的参数,包括适应度函数、种群大小、交叉概率、变异概率和迭代次数等。
2.初始化种群:根据问题的参数,初始化一个种群,通常可以使用随机数生成器来生成初始解。
3.评估适应度:对于每个个体,计算其适应度值,这通常是通过将个体作为输入参数传递给适应度函数来完成的。
4.选择操作:根据适应度值,选择出适应度较高的个体,用于下一代种群的生成。
5.交叉操作:随机选择两个个体进行交叉操作,生成新的个体。
6.变异操作:对新的个体进行变异操作,以增加种群的多样性。
7.迭代更新:重复上述步骤,直到达到预设的迭代次数或满足终止条件。
8.输出结果:输出最终的种群中最优的个体作为问题的解。
下面是一个简单的MATLAB遗传算法示例代码:matlab复制代码% 遗传算法参数设置popSize = 100; % 种群大小crossoverRate = 0.8; % 交叉概率mutationRate = 0.01; % 变异概率maxGeneration = 100; % 最大迭代次数% 初始化种群pop = round(rand(popSize,1)); % 生成初始种群% 适应度函数(这里假设我们要最小化的目标函数是 x^2)fitnessFunction = @(x) x.^2;% 迭代更新种群for generation = 1:maxGeneration% 评估适应度fitness = fitnessFunction(pop);% 选择操作[newPop,~] = rouletteWheelSelection(pop,fitness);% 交叉操作newPop = crossover(newPop, crossoverRate);% 变异操作newPop = mutation(newPop, mutationRate);% 更新种群pop = newPop;end% 输出最优解[~, bestIndex] = min(fitness);bestSolution = pop(bestIndex);fprintf('最优解:%d\n', bestSolution);在这个示例中,我们使用了轮盘赌选择、均匀交叉和均匀变异等遗传算法的操作。
遗传算法matlab程序
function result=sga(n,a,b,pc,pm,e)%n—群体规模;a—搜索上限;b—搜索下限;%pc—交叉概率;pm—变异概率;e—计算精度;for i=1:50 %求出群体的码串最小长度mif (b-a)/e>2^(i)m=i+1elsei=i+1endendpopusize=n;chromlength=m;j=1;popu=round(rand(popusize,chromlength)); %随机产生n行m列的初始群体while j<=30 %设置程序中止条件py=chromlength;for i=1:py %进行二进制转换成十进制的解码操作popu1(:,i)=2.^(py-1).*popu(:,i);Py=py-1;endpopu2=sum(popu1,2);x=a+popu2*(b-a)/(2^l-1);yvalue=2*x.^2.*cos(3*x)+x.*sin(5*x)+8; %计算群体中每个个体的适应度for i=1:popusize %执行复制操作if yvalue(i)<0yvalue(i)=0;endendfitscore=yvalue/sum(yvalue);%个体被选中的概率fitscore=cumsum(fitscore);% 群体中个体的累积概率wh=sort(rand(popusize,1));% 从小到大排列wheel=1;fitone=1;while wheel<=popusize %执行转盘式选择操作if wh(wheel)<fitscore(fitone)newpopu(wheel,:)=popu(fitone,:);wheel=wheel+1;elsefitone=fitone+1;endendpopu=newpopu;for i=1:2:popusize-1 %执行交叉操作if rand<pccpoint=round(rand*chromlength);newpopu(i,:)=[popu(i,1:cpoint) popu(i+1,cpoint+1:chromlength)]; newpopu(i+1,:)=[popu(i+1,1:cpoint) popu(i,cpoint+1:chromlength)]; elsenewpopu(i,:)=popu(i,:);newpopu(i+1,:)=popu(i+1,:);endendpopu=newpopu;for i=1:popusize %执行变异操作if rand<pmmpoint=round(rand*chromlength);if mpoint<=0;mpoint=1;endnewpopu(i,:)=popu(i,:);if newpopu(i,mpoint)==0newpopu(i,mpoint)=1;elsenewpopu(i,mpoint)=0;endelsenewpopu(i,:)=popu(i,:);endend[y(j) index]=max(yvalue); %求出群体中适应值最大的个体及其适应值bestindividual=newpopu(index,:);py=chromlength;for i=1:py %进行二进制转换成十进制的解码操作bestindividual(1,i)=2.^(py-1).*bestindividual(:,i);py=py-1;endr(j)=a+sum(bestindividual,2)*(b-a)/(2^l-1);popu=newpopu;j=j+1;% 重新赋值并返回endfplot('2*x.^2.*cos(3*x)+x.*sin(5*x)+8';[a b]);hold on;plot(r,y,'r*');hold offxlabel('x');ylabel('y')[y index]=max(y); %计算最大值及其位置result=[r(index) y];% 返回优化结果她含着笑,切着冰屑悉索的萝卜,她含着笑,用手掏着猪吃的麦糟,她含着笑,扇着炖肉的炉子的火,她含着笑,背了团箕到广场上去晒好那些大豆和小麦,大堰河,为了生活,在她流尽了她的乳液之后,她就用抱过我的两臂,劳动了。
遗传算法的Matlab7.0程序实现
function pop=encoding(popsize,stringlength,dimension)pop=round(rand(popsize.dimension*string—length+1));function new—pop=cross~over(pop,popsize,stringlength,dimension)match=round(rand(1,popsize)*(popsize一1))+1;for i=1:popsize .["childl,child2]=cross—running(pop (i,:),pop(match(i),:),stringlength,di—mension);new—pop(2*i——1:2*i,:)=[-childl}child2];endfunction[childl,child2]=eross—running(par—entl,parent2,stringlength,dimension)cpoint=round((stringlength--1)*rand(1,di—…mension))+l;for j=1:dimensionchildl((j一1)*stringlength+1:j*string—length)=[parentl((j一1)*stringlength+1:(j一1)*stringlength+cpoint(j))parent2((j一1)* stringlength+cpoint(j)+1:j*stringlength)];child2((j一1)*stringlength+1:j-'k string—length)=[parent2((j一1)*stringlength+1:(j一1)*stringlength+cpoint(j))parentl((j一1)-'k stringlength+cpoint(j)+1:j*stringlength)];endfunction new—pop 2 mutation(new—pop,string—length,dimension,pm)new—popsize=size(new—pop,1);for i一1:new—popsizeif rand<pmmpoint--round(rand(1.dimension)*(string—length一1))+1;for j=1:dimensionnew—pop(i,(j一1)-'k stringlength+mpoint (j))一1一new—pop(i,(j一1)*stringlength+ mpoint(j));endendendfunction pop—decoding(pop,stringlength,dimen—sion,X—bound)popsize=size(pop,1);temp--2.‘(stringlength一1:一1:0)/(2‘string—length--1);for i一1:dimensionbound(i)=X—bound(i,2)一x—bound(i,1);endfor i=1:popsizeforj=1:dimensionm(:,j)一pop(i,stringlength*(j一1)+1:stringlength*j);endx2temp*m ox—x.*bound+x—bound(:,1)’;’pop(i,dimension*stringlength+1)一funname (x);Endfunction selected=selection(pop,popsize,string—length,dimension)popsize—new2size(pop,1);r=rand(1,popsize):fitness=pop(:,dimension*stringlength+1);fitness=fitness/sum(fitness);fitness=cumsum(fitness);for i=l:popsizef0√~1:popsize~newi j--a.“if,(i)三:fit:00110110,则解码后selected(i':) ,,‘。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
已知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次为基础,每次旋转都为新的种群选择一个染色体。
赌轮是按每个染色体的适应度进行选择染色体的。
step1 、对每个染色体vi,计算累计概率qi,q0=0;qi=σeval(vj) j=1,…,i;i=1,…pop-size.step2、从区间(0,pop-size)中产生一个随机数r;step3、若qi-1 step4、重复step2和step3共pop-size次,这样可以得到pop-size 个复制的染色体。
grefenstette编码:由于常规的交叉运算和变异运算会使种群中产生一些无实际意义的染色体,本文采用grefenstette编码《遗传算法原理及应用》可以避免这种情况的出现。
所谓的grefenstette编码就是用所选队员在未选(不含淘汰)队员中的位置,如:8 15 2 16 10 7 4 3 11 14 6 12 9 5 18 13 17 1对应:8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1。
交叉过程:本文采用常规单点交叉。
为确定交叉操作的父代,从到pop-size重复以下过程:从[0,1]中产生一个随机数r,如果r 将所选的父代两两组队,随机产生一个位置进行交叉,如:8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 16 12 3 5 6 8 5 6 3 1 8 5 6 3 3 2 1 1交叉后为:8 14 2 13 8 6 3 2 5 1 8 5 6 3 3 2 1 16 12 3 5 6 8 5 6 37 3 4 3 2 4 2 2 1变异过程:本文采用均匀多点变异。
类似交叉操作中选择父代的过程,在r 选择多个染色体vi作为父代。
对每一个选择的父代,随机选择多个位置,使其在每位置按均匀变异(该变异点xk的取值范围为[ukmin,ukmax],产生一个[0,1]中随机数r,该点变异为x'k=ukmin+r(ukmax-ukmin))操作。
如:8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1变异后:8 14 2 13 10 6 3 2 2 7 3 4 5 2 4 1 2 1反grefenstette编码:交叉和变异都是在grefenstette编码之后进行的,为了循环操作和返回最终结果,必须逆grefenstette编码过程,将编码恢复到自然编码。
循环操作:判断是否满足设定的带数xzome,否,则跳入适应度f的计算;是,结束遗传操作,跳出。
matlab 代码distTSP.txt0 6 18 4 87 0 17 3 74 4 0 4 520 19 24 0 228 8 16 6 0%GATSP.mfunction gatsp1()clear;load distTSP.txt;distance=distTSP;N=5;ngen=100;ngpool=10;%ngen=input('# of generations to evolve = ');%ngpool=input('# of chromosoms in the gene pool = '); % size of genepool gpool=zeros(ngpool,N+1); % gene poolfor i=1:ngpool, % intialize gene poolgpool(i,:)=[1 randomize([2:N]')' 1];for j=1:i-1while gpool(i,:)==gpool(j,:)gpool(i,:)=[1 randomize([2:N]')' 1];endendendcostmin=100000;tourmin=zeros(1,N);cost=zeros(1,ngpool);increase=1;resultincrease=1;for i=1:ngpool,cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));end% record current best solution[costmin,idx]=min(cost);tourmin=gpool(idx,:);disp([num2str(increase) 'minmum trip length = ' num2str(costmin)])costminold2=200000;costminold1=150000;resultcost=100000;tourminold2=zeros(1,N);tourminold1=zeros(1,N);resulttour=zeros(1,N);while(abs(costminold2-costminold1) ;100)&(abs(costminold1-costmin) ;10 0)&(increase ;500)costminold2=costminold1; tourminold2=tourminold1;costminold1=costmin;tourminold1=tourmin;increase=increase+1;if resultcost>costminresultcost=costmin;resulttour=tourmin;resultincrease=increase-1;endfor i=1:ngpool,cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));end% record current best solution[costmin,idx]=min(cost);tourmin=gpool(idx,:);%==============% copy gens in th gpool according to the probility ratio% >1.1 copy twice% >=0.9 copy once% ;0.9 remove[csort,ridx]=sort(cost);% sort from small to big.csum=sum(csort);caverage=csum/ngpool;cprobilities=caverage./csort;copynumbers=0;removenumbers=0;for i=1:ngpool,if cprobilities(i) >1.1copynumbers=copynumbers+1;endif cprobilities(i) <0.9removenumbers=removenumbers+1;endendcopygpool=min(copynumbers,removenumbers);for i=1:copygpoolfor j=ngpool:-1:2*i+2 gpool(j,:)=gpool(j-1,:);endgpool(2*i+1,:)=gpool(i,:);endif copygpool==0gpool(ngpool,:)=gpool(1,:);end%=========%when genaration is more than 50,or the patterns in a couple are too close,do mutationfor i=1:ngpool/2%sameidx=[gpool(2*i-1,:)==gpool(2*i,:)];diffidx=find(sameidx==0);if length(diffidx)<=2gpool(2*i,:)=[1 randomize([2:12]')' 1];endend%===========%cross gens in couplesfor i=1:ngpool/2[gpool(2*i-1,:),gpool(2*i,:)]=crossgens(gpool(2*i-1,:),gpool(2*i, :));endfor i=1:ngpool,cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));end% record current best solution[costmin,idx]=min(cost);tourmin=gpool(idx,:);disp([num2str(increase) 'minmum trip length = ' num2str(costmin)]) enddisp(['cost function evaluation: ' int2str(increase) ' times!']) disp(['n:' int2str(resultincrease)])disp(['minmum trip length = ' num2str(resultcost)])disp('optimum tour = ')disp(num2str(resulttour))%====================================================function B=randomize(A,rowcol)% Usage: B=randomize(A,rowcol)% randomize row orders or column orders of A matrix% rowcol: if =0 or omitted, row order (default)% if = 1, column orderrand('state',sum(100*clock))if nargin == 1,rowcol=0;endif rowcol==0,[m,n]=size(A);p=rand(m,1);[p1,I]=sort(p);B=A(I,:);elseif rowcol==1,Ap=A';[m,n]=size(Ap);p=rand(m,1);[p1,I]=sort(p);B=Ap(I,:)';end%=====================================================function y=rshift(x,dir)% Usage: y=rshift(x,dir)% rotate x vector to right (down) by 1 if dir = 0 (default)% or rotate x to left (up) by 1 if dir = 1if nargin ;2, dir=0; end[m,n]=size(x);if m>1,if n == 1,col=1;elseif n>1,error('x must be a vector! break');end % x is a column vectorelseif m == 1,if n == 1, y=x;returnelseif n>1,col=0; % x is a row vector endendif dir==1, % rotate left or upif col==0, % row vector, rotate lefty = [x(2:n) x(1)];elseif col==1,y = [x(2:n); x(1)]; % rotate upendelseif dir==0, % default rotate right or downif col==0,y = [x(n) x(1:n-1)];elseif col==1 % column vectory = [x(n); x(1:n-1)];endend%================================================== function [L1,L2]=crossgens(X1,X2)% Usage:[L1,L2]=crossgens(X1,X2)s=randomize([2:12]')';n1=min(s(1),s(11));n2=max(s(1),s(11));X3=X1;X4=X2;for i=n1:n2,for j=1:13,if X2(i)==X3(j),X3(j)=0;endif X1(i)==X4(j), X4(j)=0;endendendj=13;k=13;for i=12:-1:2,if X3(i)~=0,j=j-1;t=X3(j);X3(j)=X3(i);X3(i)=t;endif X4(i)~=0,k=k-1;t=X4(k);X4(k)=X4(i);X4(i)=t;endendfor i=n1:n2X3(2+i-n1)=X2(i);X4(2+i-n1)=X1(i);endL1=X3;L2=X4;%=======================。