遗传算法典范MATLAB代码

合集下载

利用MATLAB编制的遗传算法代码

利用MATLAB编制的遗传算法代码

function gaTSPCityNum=30;[dislist,Clist]=tsp(CityNum);inn=100; %初始种群大小¡gnmax=1000; %最大概率pc=0.8; %交叉概率pm=0.8; %变异概率%产生初始种群for i=1:inns(i,:)=randperm(CityNum);end[f,p]=objf(s,dislist);gn=1;while gn<gnmax+1for j=1:2:innseln=sel(s,p); %选择操作scro=cro(s,seln,pc); %交叉操作scnew(j,:)=scro(1,:);scnew(j+1,:)=scro(2,:);smnew(j,:)=mut(scnew(j,:),pm); %变异操作smnew(j+1,:)=mut(scnew(j+1,:),pm);ends=smnew; %产生了新的种群[f,p]=objf(s,dislist); %计算新种群的适应度%记录当前代最好和平均的适应度[fmax,nmax]=max(f);ymean(gn)=1000/mean(f);ymax(gn)=1000/fmax;%记录当前代的最佳个体x=s(nmax,:);drawTSP(Clist,x,ymax(gn),gn,0);gn=gn+1;%pause;endgn=gn-1;figure(2);plot(ymax,'r'); hold on;plot(ymean,'b');grid;title('ËÑË÷¹ý³Ì');legend('×îÓŽâ','ƽ¾ù½â');end%------------------------------------------------%计算适应度函数function [f,p]=objf(s,dislist);inn=size(s,1); %读取种群大小¡for i=1:innf(i)=CalDist(dislist,s(i,:)); %计算函数值,即适应度endf=1000./f';%计算选择概率fsum=0;for i=1:innfsum=fsum+f(i)^15;endfor i=1:innps(i)=f(i)^15/fsum;end%计算累积概率p(1)=ps(1);for i=2:innp(i)=p(i-1)+ps(i);endp=p';end%--------------------------------------------------function pcc=pro(pc);test(1:100)=0;l=round(100*pc);test(1:l)=1;n=round(rand*99)+1;pcc=test(n);end%--------------------------------------------------%“选择”操作function seln=sel(s,p);inn=size(p,1);%从种群中选择两个个体for i=1:2r=rand; %产生一个随机数prand=p-r;j=1;while prand(j)<0j=j+1;endseln(i)=j; %选中个体的序号endend%------------------------------------------------%“交叉”操作function scro=cro(s,seln,pc);bn=size(s,2);pcc=pro(pc); %根据交叉概率决定是否进行交叉操作,1则是,0则否scro(1,:)=s(seln(1),:);scro(2,:)=s(seln(2),:);if pcc==1c1=round(rand*(bn-2))+1; %在[1,bn-1]范围内随机产生一个交叉位 c2=round(rand*(bn-2))+1;chb1=min(c1,c2);chb2=max(c1,c2);middle=scro(1,chb1+1:chb2);scro(1,chb1+1:chb2)=scro(2,chb1+1:chb2);scro(2,chb1+1:chb2)=middle;for i=1:chb1while find(scro(1,chb1+1:chb2)==scro(1,i))zhi=find(scro(1,chb1+1:chb2)==scro(1,i));y=scro(2,chb1+zhi);scro(1,i)=y;endwhile find(scro(2,chb1+1:chb2)==scro(2,i))zhi=find(scro(2,chb1+1:chb2)==scro(2,i));y=scro(1,chb1+zhi);scro(2,i)=y;endendfor i=chb2+1:bnwhile find(scro(1,1:chb2)==scro(1,i))zhi=find(scro(1,1:chb2)==scro(1,i));y=scro(2,zhi);scro(1,i)=y;endwhile find(scro(2,1:chb2)==scro(2,i))zhi=find(scro(2,1:chb2)==scro(2,i));y=scro(1,zhi);scro(2,i)=y;endendendend%--------------------------------------------------%“变异”操作function snnew=mut(snew,pm);bn=size(snew,2);snnew=snew;pmm=pro(pm); %¸根据变异概率决定是否进行变异操作,1则是,0则否if pmm==1c1=round(rand*(bn-2))+1; %在[1,bn-1]范围内随机产生一个变异位 c2=round(rand*(bn-2))+1;chb1=min(c1,c2);chb2=max(c1,c2);x=snew(chb1+1:chb2);snnew(chb1+1:chb2)=fliplr(x); endend。

遗传算法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遗传算法 算例

下面是一个使用MATLAB实现的基本遗传算法算例。

本例用于解决简单的优化问题:寻找函数f(x) = x^2在[-10,10]范围内的最小值。

```matlab定义问题参数PopSize = 100; 种群数量Genes = -10:0.1:10; 基因范围FitnessFunc = @(x) -x.^2; 适应度函数(这里为了方便,使用了-x^2,即求最大值,实际应用中应改为-f(x))MaxGen = 50; 最大迭代次数初始化种群Pop = zeros(PopSize, length(Genes));for i = 1:PopSizePop(i,:) = rand(1,length(Genes))*2*Genes - Genes; 随机产生初始种群end开始迭代for gen = 1:MaxGen计算当前种群适应度Fitness = FitnessFunc(Pop);[BestFit, Index] = max(Fitness); 找到最佳适应度BestFitPos = Pop(Index,:); 找到最佳适应度对应的基因选择(轮盘赌选择)NewPop = zeros(PopSize, length(Genes));SumFitness = sum(Fitness);RandomFitness = rand(PopSize,1)*SumFitness; 随机生成每个个体的"随机适应度"for i = 1:PopSize[~, Index] = min(RandomFitness); 用随机适应度进行选择(越小被选中概率越大)NewPop(i,:) = Pop(Index,:); 将选择出的个体放入新种群RandomFitness(Index) = SumFitness; 将已选择的个体的随机适应度设为最大值,避免重复选择end交叉(杂交)for i = 1:PopSize/2随机选择两个父代个体Parent1 = NewPop(randi([1 PopSize]),:);Parent2 = NewPop(randi([1 PopSize]),:);生成新个体Child1 = (Parent1 + Parent2)/2; 中间值交叉Child2 = Parent1 + (Parent2 - Parent1)*rand; 一点交叉将新个体加入新种群NewPop((i-1)*2+1,:) = Child1;NewPop((i-1)*2+2,:) = Child2;end变异for i = 1:PopSizeif rand < 0.01 变异概率为0.01随机选择一个基因进行变异(取反)GeneIdx = randi(length(Genes));NewPop(i,GeneIdx) = ~NewPop(i,GeneIdx);endend更新种群Pop = NewPop;end输出结果BestFit = FitnessFunc(BestFitPos);fprintf('Best fitness: f\n', BestFit);fprintf('Best position: s\n', num2str(BestFitPos));```这个例子比较简单,只用了基本的遗传算法操作:选择、交叉和变异。

三个遗传算法matlab程序实例

三个遗传算法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代码遗传算法经典学习Matlab代码遗传算法实例:也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。

对于初学者,尤其是还没有编程经验的非常有用的一个文件遗传算法实例% 下面举例说明遗传算法 %% 求下列函数的最大值 %% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。

% % 将变量域[0,10] 离散化为二值域[0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。

%% %%--------------------------------------------------------------------------------------------------------------%%--------------------------------------------------------------------------------------------------------------%% 编程%-----------------------------------------------% 2.1初始化(编码)% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。

%遗传算法子程序%Name: initpop.m%初始化function pop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,% roud对矩阵的每个单元进行圆整。

遗传算法matlab代码

遗传算法matlab代码

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:N tmprnd=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 value F4=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;遗传算法实例:% 下面举例说明遗传算法%% 求下列函数的最大值%% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01 。

遗传算法matlab代码

遗传算法matlab代码
figure(1);%打开第一个窗口
fplot(f,[xmin,xmax]);%隐函数画图
grid on;hold on;
plot(x,fit,'k*');%作图,画初始种群的适应度图像
title('(a)染色体的初始位置');%标题
xlabel('x');ylabel('f(x)');%标记轴
close all;
clc;%清屏
tic;%计时器开始计时
n=20;ger=100;pc=0.65;pm=0.05;%初始化参数
%以上为经验值,可以更改。
% 生成初始种群
v=init_population(n,22); %得到初始种群,22串长,生成20*22的0-1矩阵
[N,L]=size(v); %得到初始规模行,列
v=fliplr(v); %实现左右翻转颠倒
[s,c]=size(v); %c代表串长。求行,列
aux=0:1:c-1; %21维向量
aux=ones(s,1)*aux;%权值向量矩阵
x1=sum((v.*2.^aux)');%权值 %注意转置 %sum是求列和
x=xymin+(xymax-xymin)*x1./(2^c-1); %最大值4194303;
disp(sprintf('Number of generations:%d',ger));
disp(sprintf('Population size:%d',N));
disp(sprintf('Crossover probability:%.3f',pc));

遗传算法MATLAB完整代码(不用工具箱)

遗传算法MATLAB完整代码(不用工具箱)

遗传算法MATLAB完整代码(不用工具箱)遗传算法解决简单问题%主程序:用遗传算法求解y=200*exp(-0.05*x).*sin(x)在区间[-2,2]上的最大值clc;clear all;close all;global BitLengthglobal boundsbeginglobal boundsendbounds=[-2,2];precision=0.0001;boundsbegin=bounds(:,1);boundsend=bounds(:,2);%计算如果满足求解精度至少需要多长的染色体BitLength=ceil(log2((boundsend-boundsbegin)'./precision));popsize=50; %初始种群大小Generationmax=12; %最大代数pcrossover=0.90; %交配概率pmutation=0.09; %变异概率%产生初始种群population=round(rand(popsize,BitLength));%计算适应度,返回适应度Fitvalue和累计概率cumsump[Fitvalue,cumsump]=fitnessfun(population);Generation=1;while Generation<generationmax+1< p="">for 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);%绘制经过遗传运算后的适应度曲线。

遗传算法matlab程序代码

遗传算法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代码

标准遗传算法MATLAB代码

%用遗传算法进行简单函数的优化,可以显示中间过程clearbn=22; %个体串长度inn=50; %初始种群大小gnmax=200; %最大代数pc=0.8; %交叉概率pm=0.05; %变异概率%产生初始种群s=round(rand(inn,bn));gnf1=5;gnf2=20;%计算适应度,返回适应度f和累积概率p[f,p]=objf(s);gn=1;while gn<gnmax+1xp=-1:0.01:2;yp=ft(xp);for d=1:innxi=n2to10(s(d,:));xdi(d)=-1.0+xi*3/(power(2,bn)-1);endyi=ft(xdi);plot(xp,yp,'b-',xdi,yi,'g*');strt=['当前代数gn=' num2str(gn)];text(-0.75,1,strt);text(-0.75,3.5,'* 当前种群','Color','g');if gn<gnf1pause;endhold on;for j=1:2:inn%选择操作seln=sel(s,p);xs1=n2to10(s(seln(1),:));xds1=-1.0+xs1*3/(power(2,bn)-1);ys1=ft(xds1);xs2=n2to10(s(seln(2),:));xds2=-1.0+xs2*3/(power(2,bn)-1);ys2=ft(xds2);hold on;drawnow;plot(xds1,ys1,'r*',xds2,ys2,'r*');%交叉操作scro=cro(s,seln,pc);scnew(j,:)=scro(1,:);scnew(j+1,:)=scro(2,:);%变异操作smnew(j,:)=mut(scnew(j,:),pm);smnew(j+1,:)=mut(scnew(j+1,:),pm);enddrawnow;text(-0.75,3.3,'* 选择后','Color','r');if gn<gnf1pause;endfor d=1:innxc=n2to10(scnew(d,:));xdc(d)=-1.0+xc*3/(power(2,bn)-1); endyc=ft(xdc);drawnow;plot(xdc,yc,'m*');text(-0.75,3.1,'* 交叉后','Color','m');if gn<gnf1pause;endhold on;for d=1:innxm=n2to10(smnew(d,:));xdm(d)=-1.0+xm*3/(power(2,bn)-1); endym=ft(xdm);drawnow;plot(xdm,ym,'c*');text(-0.75,2.9,'* 变异后','Color','c');if gn<gnf2pause;endhold off;s=smnew; %产生了新的种群%计算新种群的适应度[f,p]=objf(s);%记录当前代最好和平均的适应度[fmax,nmax]=max(f);fmean=mean(f);ymax(gn)=fmax;ymean(gn)=fmean;%记录当前代的最佳个体x=n2to10(s(nmax,:));xx=-1.0+x*3/(power(2,bn)-1);xmax(gn)=xx;gn=gn+1;endgn=gn-1;figure(2);subplot(2,1,1);plot(1:gn,[ymax;ymean]);title('历代适应度变化','fonts',10);legend('最大适应度','平均适应度');string1=['最终适应度',num2str(ymax(gn))]; gtext(string1);subplot(2,1,2);plot(1:gn,xmax,'r-');legend('自变量');string2=['最终自变量',num2str(xmax(gn))]; gtext(string2);。

遗传算法matlab源代码

遗传算法matlab源代码

方案一的程序编码函数主文件:function[Xp,LC1,LC2,LC3]=CLBGA8(M,Pm) %%%陈璐斌编程,解决VRP问题(带时间窗)%%输入参数%M遗传进化迭代次数%Pm变异概率%%输出参数%Xp最优个体%LC1目标收敛曲线%LC2平均适应度收敛曲线%LC3最优适应度收敛曲线%%%变量初始化Xp=zeros(1,5);LC1=zeros(1,M);LC2=zeros(1,M);LC3=zeros(1,M);Best=inf;%%编码方式-第一步:产生初始种群N=10;%N 种群规模farm=cell(1,N);%存储种群的细胞结构k=1;while (N-k>=0)G=randperm(5);%产生5个客户的全排列farm{k}=G;k=k+1;end%%%进化迭代计数器counter=1;while counter<=M%%第二步:交叉%交叉采用双亲双子单点交叉N=10;%种群规模newfarm=cell(1,2*N-4);%存储子代的细胞结构Ser=randperm(N);%两两随机配对表生成for i=1:(N-2)%避免交叉概率为1 A=farm{Ser(i)};B=farm{Ser(i+1)};%取出父代P0=unidrnd(5);%随机选择交叉点aa=zeros(1,5);bb=zeros(1,5);A_=A;B_=B;for ii=1:5-P0aa(ii)=B(P0+ii);endfor ii=1:5-P0for iiii=1:5if(B(P0+ii)==A_(iiii))A_(iiii)=0;endendendfor iii=6-P0:5for iiii=1:5if(A_(iiii)~=0)aa(iii)=A_(iiii);A_(iiii)=0;breakendendendfor ii=1:5-P0bb(ii)=A(P0+ii);endfor ii=1:5-P0for iiii=1:5if(A(P0+ii)==B_(iiii))B_(iiii)=0;endendendfor iii=6-P0:5for iiii=1:5if(B_(iiii)~=0)bb(iii)=B_(iiii);B_(iiii)=0;breakendendend%产生子代newfarm{2*i-1}=aa;newfarm{2*i}=bb;endFARM=[farm,newfarm];%新旧种群合并%%第三步:选择复制%%计算当前种群适应度并存储N=10;SYZ=zeros(1,3*N-4);syz=zeros(1,3*N-4);for i=1:(3*N-4)x=FARM{i};SYZ(i)=clb8(x);end%%选择复制,较优的N个个体复制到下一代k=1;while k<=(3*N-4)maxSYZ=max(SYZ);posSYZ=find(SYZ==maxSYZ);POS=posSYZ(1);k=k+1;farm{k}=FARM{POS};syz(k)=SYZ(POS);SYZ(POS)=0;end%记录和更新,更新最优个体,记录收敛曲线数据maxsyz=max(syz);meansyz=mean(syz);pos=find(syz==maxsyz);LC2(counter+1)=meansyz;if maxsyzBest=maxsyz;Xp=farm{pos(1)};endLC3(counter+1)=Best;d=[0,6.4,3.2,3.9,3.7,2;6.4,0,2.9,2.1,4.5,4.1;3.2,2.9,0,1.5,3.3,1.2;3.9,2.1,1.5,0,3.6,2.6;3.7,4.5,3.3,3.6 ,0,3.8;...2.0,4.1,1.2,2.6,3.8,0;];%距离矩阵t=[0,0.16,0.08,0.1,0.09,0.05;0.16,0,0.07,0.05,0.11,0.1;0.08,0.07,0,0.04,0.08,0.03;...0.1,0.05,0.04,0,0.09,0.07;0.09,0.11,0.08,0.09,0,0.10;0.05,0.1,0.03,0.07,0.1,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7];xx=x;%取出染色体j=1;%分工点初始化%%取距离向量d1,d2d1=zeros(1,6);d1(1)=d(1,xx(1)+1);for i=1:4d1(i+1)=d(xx(i)+1,xx(i+1)+1);endd1(6)=d(xx(5)+1,1);%%时间窗计算T=t(1,xx(1)+1);pun1=0;if T<early(xx(1))pun1=early(xx(1))-T;T=early(xx(1));endT=T+w(xx(1));for i=2:5T=T+t(xx(i-1)+1,xx(i)+1);if T<early(xx(i))pun1=pun1+early(xx(i))-T;T=early(xx(i));endT=T+w(xx(5));endF=sum(10.*d1)+sum(10.*d2)+20*pun1; LC1(counter+1)=F;%%第四步:变异N=10;for i=1:Nif Pm>randAA=farm{i};POS1=unidrnd(5);POS2=unidrnd(5);temp=AA(POS1);AA(POS1)=AA(POS2);AA(POS2)=temp;farm{i}=AA;endendcounter=counter+1;end%%第五步:绘制收敛曲线图figure(2);plot(LC1);xlabel('迭代次数');ylabel('目标的值');title('目标的收敛曲线');figure(3);plot(LC2);xlabel('迭代次数');ylabel('适应度函数的平均值');title('平均适应度函数的收敛曲线');plot(LC3);xlabel('迭代次数');ylabel('适应度函数的最优值');title('最优适应度函数的收敛曲线');适应度文件:%%计算载重量和时间窗%%适应度函数计算function Fitness=clb8(x)d=[0,6.4,3.2,3.9,3.7,2;6.4,0,2.9,2.1,4.5,4.1;3.2,2.9,0,1.5,3.3,1.2;3.9,2.1,1.5,0,3.6,2.6;3.7,4.5,3.3,3.6 ,0,3.8;...2.0,4.1,1.2,2.6,3.8,0;];%距离矩阵t=[0,0.16,0.08,0.1,0.09,0.05;0.16,0,0.07,0.05,0.11,0.1;0.08,0.07,0,0.04,0.08,0.03;...0.1,0.05,0.04,0,0.09,0.07;0.09,0.11,0.08,0.09,0,0.10;0.05,0.1,0.03,0.07,0.1,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7];xx=x;%取出染色体j=1;%分工点初始化%%取距离向量d1,d2d1=zeros(1,6);d1(1)=d(1,xx(1)+1);for i=1:4d1(i+1)=d(xx(i)+1,xx(i+1)+1);endd1(6)=d(xx(5)+1,1);%%时间窗计算T=t(1,xx(1)+1);pun1=0;if T<early(xx(1))pun1=early(xx(1))-T;T=early(xx(1));endT=T+w(xx(1));T=T+t(xx(i-1)+1,xx(i)+1);if T<early(xx(i))pun1=pun1+early(xx(i))-T;T=early(xx(i));endT=T+w(xx(5));endF=sum(10.*d1)+sum(10.*d2)+20*pun1;Fitness=1/F;计算时间文件:function[T]=TOTALT(Xp1)Xp=Xp1;t=[0,0.16,0.08,0.1,0.09,0.05;0.16,0,0.07,0.05,0.11,0.1;0.08,0.07,0,0.04,0.08,0.03;...0.1,0.05,0.04,0,0.09,0.07;0.09,0.11,0.08,0.09,0,0.10;0.05,0.1,0.03,0.07,0.1,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7];T=t(1,Xp(1)+1);if T<early(Xp(1))T=early(Xp(1));endT=T+w(Xp(1));for i=2:5T=T+t(Xp(i-1)+1,Xp(i)+1);if T<early(Xp(i))T=early(Xp(1));endT=T+w(Xp(i));endT=T+t(1,Xp(5)+1);方案二的程序编码主函数文件:function[Xp,LC1,LC2,LC3]=CLBGA9(M,Pm)%%%陈璐斌编程,解决VRP问题(带时间窗)%%输入参数%M遗传进化迭代次数%Pm变异概率%%输出参数%Xp最优个体%LC1子目标2收敛曲线%LC2平均适应度收敛曲线%LC3最优适应度收敛曲线%%%变量初始化Xp=zeros(1,6);LC1=zeros(1,M);LC2=zeros(1,M);LC3=zeros(1,M);Best=inf;%%编码方式-第一步:产生初始种群N=10;%N 种群规模%Q=[2.4,3.3,2.1,2.7,2.3,1.6,2.0,1.2,3.6,1.9];%需求矩阵farm=cell(1,N);%存储种群的细胞结构k=1;while (N-k>=0)G=randperm(6);%产生6个客户的全排列farm{k}=G;k=k+1;end%%%进化迭代计数器counter=1;while counter<=M%%第二步:交叉%交叉采用双亲双子单点交叉N=10;%种群规模newfarm=cell(1,2*N-4);%存储子代的细胞结构Ser=randperm(N);%两两随机配对表生成for i=1:(N-2)%避免交叉概率为1A=farm{Ser(i)};B=farm{Ser(i+1)};%取出父代P0=unidrnd(6);%随机选择交叉点aa=zeros(1,6);bb=zeros(1,6);A_=A;B_=B;for ii=1:6-P0aa(ii)=B(P0+ii);endfor ii=1:6-P0for iiii=1:6if(B(P0+ii)==A_(iiii))A_(iiii)=0;endendendfor iii=7-P0:6for iiii=1:6if(A_(iiii)~=0)aa(iii)=A_(iiii);A_(iiii)=0;breakendendendfor ii=1:6-P0bb(ii)=A(P0+ii);endfor ii=1:6-P0for iiii=1:6if(A(P0+ii)==B_(iiii))B_(iiii)=0;endendendfor iii=7-P0:6for iiii=1:6if(B_(iiii)~=0)bb(iii)=B_(iiii);B_(iiii)=0;breakendendend%产生子代newfarm{2*i-1}=aa;newfarm{2*i}=bb;endFARM=[farm,newfarm];%新旧种群合并%%第三步:选择复制%%计算当前种群适应度并存储N=10;SYZ=zeros(1,3*N-4);syz=zeros(1,3*N-4);for i=1:(3*N-4)x=FARM{i};SYZ(i)=clb9(x);end%%选择复制,较优的N个个体复制到下一代k=1;while k<=(3*N-4)maxSYZ=max(SYZ);posSYZ=find(SYZ==maxSYZ);POS=posSYZ(1);k=k+1;farm{k}=FARM{POS};syz(k)=SYZ(POS);SYZ(POS)=0;end%记录和更新,更新最优个体,记录收敛曲线数据maxsyz=max(syz);meansyz=mean(syz);pos=find(syz==maxsyz);LC2(counter+1)=meansyz;if maxsyzBest=maxsyz;Xp=farm{pos(1)};endLC3(counter+1)=Best;d=[0,6.4,3.2,3.9,3.7,35,2;6.4,0,2.9,2.1,4.5,32.5,4.1;3.2,2.9,0,1.5,3.3,35.7,1.2;3.9,2.1,1.5,0,3.6,34.5,2.6;...3.7,4.5,3.3,3.6,0,37,3.8;35,32.5,35.7,34.5,37,0,38.5;2,4.1,1.2,2.6,3.8,38.5,0];%距离矩阵t=[0,0.16,0.08,0.1,0.1,0.88,0.05;0.16,0,0.07,0.05,0.11,0.81,0.1;0.08,0.07,0,0.04,0.08,0.9,0.03;...0.1,0.05,0.04,0,0.09,0.86,0.07;0.1,0.11,0.08,0.09,0,0.92,0.1;0.88,0.81,0.9,0.86,0.92,0,0.96;...0.05,0.1,0.03,0.07,0.1,0.96,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.2,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7,0.6];xx=x;%取出染色体j=1;%分工点初始化%%取距离向量d1,d2d1=zeros(1,7);d1(1)=d(1,xx(1)+1);for i=1:5d1(i+1)=d(xx(i)+1,xx(i+1)+1);endd1(7)=d(xx(6)+1,1);%%时间窗计算T=t(1,xx(1)+1);pun1=0;if T<early(xx(1))pun1=early(xx(1))-T;T=early(xx(1));endT=T+w(xx(1));for i=2:6T=T+t(xx(i-1)+1,xx(i)+1);if T<early(xx(i))pun1=pun1+early(xx(i))-T;T=early(xx(i));endT=T+w(xx(6));endF=sum(10.*d1) +20*pun1;LC1(counter+1)=F;%%第四步:变异N=10;for i=1:Nif Pm>randAA=farm{i};POS1=unidrnd(6);POS2=unidrnd(6);temp=AA(POS1);AA(POS1)=AA(POS2);AA(POS2)=temp;farm{i}=AA;endendcounter=counter+1;end%%第五步:绘制收敛曲线图figure(2);plot(LC1);xlabel('迭代次数');ylabel('目标的值');title('目标的收敛曲线');figure(3);plot(LC2);xlabel('迭代次数');ylabel('适应度函数的平均值');title('平均适应度函数的收敛曲线');figure(4);plot(LC3);xlabel('迭代次数');ylabel('适应度函数的最优值');title('最优适应度函数的收敛曲线');适应度文件:%%计算载重量和时间窗%%适应度函数计算function Fitness=clb9(x)d=[0,6.4,3.2,3.9,3.7,35,2;6.4,0,2.9,2.1,4.5,32.5,4.1;3.2,2.9,0,1.5,3.3,35.7,1.2;3.9,2.1,1.5,0,3.6,34.5,2.6;...3.7,4.5,3.3,3.6,0,37,3.8;35,32.5,35.7,34.5,37,0,38.5;2,4.1,1.2,2.6,3.8,38.5,0];%距离矩阵t=[0,0.16,0.08,0.1,0.1,0.88,0.05;0.16,0,0.07,0.05,0.11,0.81,0.1;0.08,0.07,0,0.04,0.08,0.9,0.03;...0.1,0.05,0.04,0,0.09,0.86,0.07;0.1,0.11,0.08,0.09,0,0.92,0.1;0.88,0.81,0.9,0.86,0.92,0,0.96;...0.05,0.1,0.03,0.07,0.1,0.96,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.2,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7,0.6];late=[2.5,3.4,3.3,2.7,2.5,4.5];xx=x;%取出染色体j=1;%分工点初始化%%取距离向量d1,d2d1=zeros(1,7);d1(1)=d(1,xx(1)+1);for i=1:5d1(i+1)=d(xx(i)+1,xx(i+1)+1);endd1(7)=d(xx(6)+1,1);%%时间窗计算T=t(1,xx(1)+1);pun1=0;if T<early(xx(1))pun1=early(xx(1))-T;T=early(xx(1));endT=T+w(xx(1));for i=2:6T=T+t(xx(i-1)+1,xx(i)+1);if T<early(xx(i))pun1=pun1+early(xx(i))-T;T=early(xx(i));endT=T+w(xx(6));endF=sum(10.*d1) +20*pun1;Fitness=1/F;计算时间文件:function[T]=TOTALT2(Xp1)Xp=Xp1;t=[0,0.16,0.08,0.1,0.1,0.88,0.05;0.16,0,0.07,0.05,0.11,0.81,0.1;0.08,0.07,0,0.04,0.08,0.9,0.03;...0.1,0.05,0.04,0,0.09,0.86,0.07;0.1,0.11,0.08,0.09,0,0.92,0.1;0.88,0.81,0.9,0.86,0.92,0,0.96;... 0.05,0.1,0.03,0.07,0.1,0.96,0;];%行驶时间矩阵w=[0.15,0.2,0.18,0.25,0.2,0.22];%服务时间矩阵%%时间窗向量early=[0.15,0.3,0.7,0.4,0.7,0.6];T=t(1,Xp(1)+1);if T<early(Xp(1))T=early(Xp(1));endT=T+w(Xp(1));for i=2:6T=T+t(Xp(i-1)+1,Xp(i)+1);if T<early(Xp(i))T=early(Xp(1));endT=T+w(Xp(i));endT=T+t(1,Xp(6)+1)。

遗传算法GA的MATLAB代码

遗传算法GA的MATLAB代码

MATLAB实现算法代码:GA(遗传算法)——整数编码function [BestGene,aa] = GA(MaxGeneration,GeneSize,GeneNum,pcross,pmute,minGene,maxGene)Parent = Init(GeneSize,GeneNum,minGene,maxGene);[BestGene,Parent] = KeepBest(Parent);aa = [];for i = 1:MaxGeneration[i 1/value(BestGene)]Child = chose(Parent);Child = cross(Child,pcross);Child = mute(Child,pmute,maxGene);[BestGene,Parent] = KeepBest(Child);aa = [aa;value(BestGene)];endfunction GeneInit = Init(GeneSize,GeneNum,minGene,maxGene)GeneInit = [];for i = 1:GeneSizex = []; x = ceil(rand(1,GeneNum).*(maxGene-minGene)) + minGene;GeneInit = [GeneInit;x];endGeneInit = [GeneInit;x];function Child = chose(Parent)GeneSize = size(Parent,1);for i = 1:GeneSizex = Parent(i,:);val(i) = value(x);endValSum = sum(val);val = val / ValSum;for i = 2:GeneSizeval(i) = val(i) + val(i-1);endfor i = 1:GeneSizerandval = rand;if randval <= val(1)Child(i,:) = Parent(1,:);endfor j = 2:GeneSizeif randval > val(j-1) && randval <= val(j)Child(i,:) = Parent(j,:);break;endendendChild(end,:) = Parent(end,:);function Child = cross(Parent,pcross)[GeneSize,GeneNum] = size(Parent);GeneSize = GeneSize - 1;Child = Parent;for i = 1:GeneSize/2if rand < pcrossflag = 0;while( flag==0 )randval1 = floor((GeneNum-1)*rand) + 1;randval2 = floor((GeneNum-1)*rand) + 1;if randval1 ~= randval2flag = 1;endendtemp = Child(2*i-1,randval1:randval2);Child(2*i-1,randval1:randval2) = Child(2*i,randval1:randval2);Child(2*i,randval1:randval2) = temp;endendfunction Child = mute(Parent,pmute,maxGene)[GeneSize,GeneNum] = size(Parent);GeneSize = GeneSize - 1;Child = Parent;for i = 1:GeneSizeif rand < pmuterandval = ceil((GeneNum-1)*rand) + 1;Child(i,randval) = maxGene(randval) - Child(i,randval) + 1;endendfunction [BestGene,Parent] = KeepBest(Child)[GeneSize,GeneNum] = size(Child);for i = 1:GeneSizex = Child(i,:);val(i) = value(x);endBigVal = val(1);flag = 1;for i = 2:GeneSizeif BigVal < val(i)BigVal = val(i);flag = i;endendBestGene = Child(flag,:); Parent = Child;Parent(1,:) = BestGene; Parent(end,:) = BestGene;。

遗传算法matlab代码

遗传算法matlab代码

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 value F4=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;遗传算法实例:% 下面举例说明遗传算法%% 求下列函数的最大值%% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01 。

遗传算法matlab代码

遗传算法matlab代码

遗传算法matlab代码以下是一个简单的遗传算法的MATLAB 代码示例:matlab复制代码% 遗传算法参数设置pop_size = 50; % 种群大小num_vars = 10; % 变量数目num_generations = 100; % 进化的代数mutation_rate = 0.01; % 变异率crossover_rate = 0.8; % 交叉率% 初始化种群population = rand(pop_size, num_vars);% 开始进化for i = 1:num_generations% 计算适应度fitness = evaluate_fitness(population);% 选择操作selected_population = selection(population, fitness);% 交叉操作offspring_population = crossover(selected_population,crossover_rate);% 变异操作mutated_population = mutation(offspring_population,mutation_rate);% 生成新种群population = [selected_population; mutated_population];end% 选择最优解best_solution = population(find(fitness == max(fitness)), :);% 适应度函数function f = evaluate_fitness(population)f = zeros(size(population));for i = 1:size(population, 1)f(i) = sum(population(i, :));endend% 选择函数function selected_population = selection(population, fitness)% 轮盘赌选择total_fitness = sum(fitness);probabilities = fitness / total_fitness;selected_indices = zeros(pop_size, 1);for i = 1:pop_sizer = rand();cumulative_probabilities = cumsum(probabilities);for j = 1:pop_sizeif r <= cumulative_probabilities(j)selected_indices(i) = j;break;endendendselected_population = population(selected_indices, :);end% 交叉函数function offspring_population = crossover(parental_population, crossover_rate)offspring_population = zeros(size(parental_population));num_crossovers = ceil(size(parental_population, 1) *crossover_rate);crossover_indices = randperm(size(parental_population, 1),num_crossovers);以下是另一个一个简单的遗传算法的MATLAB 代码示例:matlab复制代码% 初始化种群population = rand(nPopulation, nGenes);% 进化迭代for iGeneration = 1:nGeneration% 计算适应度fitness = evaluateFitness(population);% 选择父代parentIdx = selection(fitness);parent = population(parentIdx, :);% 交叉产生子代child = crossover(parent);% 变异子代child = mutation(child);% 更新种群population = [parent; child];end% 评估最优解bestFitness = -Inf;for i = 1:nPopulationf = evaluateFitness(population(i, :));if f > bestFitnessbestFitness = f;bestIndividual = population(i, :);endend% 可视化结果plotFitness(fitness);其中,nPopulation和nGenes分别是种群大小和基因数;nGeneration是迭代次数;evaluateFitness函数用于计算个体的适应度;selection函数用于选择父代;crossover函数用于交叉产生子代;mutation函数用于变异子代。

遗传算法的Matlab实现讲解

遗传算法的Matlab实现讲解
x(i)=decodechrom(bestindividual,1,chromlength)*10/(2^chromlength-1); %最佳个体解码 y(i)=bestfit+Cmin; %最佳个体适应度
y_mean(i)=mean(fitvalue+Cmin); %第i代平均适应度
pop=newpop; end fplot('2*x+10*sin(5*x)+7*cos(4*x)',[0 10]) hold on plot(x,y,'r*') hold off
temp1=decodechrom(pop,1,chromlength); %将pop每行转化成十进制数
x=temp1*(Xmax-Xmin)/(2^chromlength-1); %将十进制域 中的数转化为变 量域 的数 objvalue=2*x+10*sin(5*x)+7*cos(4*x); %计算目标函数值
Matlab编程实现GA
计算目标函数值
计算目标函数值 % calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示 例仿真,可根据不同优化问题予以修改。 %遗传算法子程序
%Name: calobjvalue.m
%实现目标函数的计算 function [objvalue]=calobjvalue(pop,chromlength,Xmax,Xmin)
bestindividual=pop(1,:);
bestfit=fitvalue(1); for i=2:px
if fitvalue(i)>bestfit
bestindividual=pop(i,:); bestfit=fitvalue(i);

遗传算法Matlab源代码

遗传算法Matlab源代码

遗传算法Matlab源代码完整可以运行的数值优化遗传算法源代码function[X,MaxFval,BestPop,Trace]=fga(FUN,bounds,MaxEranum,PopSiz e,options,pCross,pMutation,pInversion)%[X,MaxFval,BestPop,Trace]=fga(FUN,bounds,MaxEranum,PopSiz e,options,pCross,pMutation,pInversion)% Finds a maximum of a function of several variables.% fga solves problems of the form:% max F(X) subject to: LB = X = UB (LB=bounds(:,1),UB=bounds(:,2))% X - 最优个体对应自变量值% MaxFval - 最优个体对应函数值% BestPop - 最优的群体即为最优的染色体群% Trace - 每代最佳个体所对应的目标函数值% FUN - 目标函数% bounds - 自变量范围% MaxEranum - 种群的代数,取50--500(默认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 nargin2, error('FMAXGA requires at least three input arguments'); endif nargin==2, MaxEranum=150;PopSize=100;options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==3, PopSize=100;options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==4, options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==5, pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==6, pMutation=0.1;pInversion=0.25;endif nargin==7, pInversion=0.25;endif (options(1)==0|options(1)==1)find((bounds(:,1)-bounds(:,2))0)error('数据输入错误,请重新输入:');end% 定义全局变量global m n NewPop children1 children2 VarNum% 初始化种群和变量precision = options(2);bits = ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间VarNum = size(bounds,1);[Pop] = InitPop(PopSize,bounds,bits,options);%初始化种群[m,n] = size(Pop);fit = zeros(1,m);NewPop = zeros(m,n);children1 = zeros(1,n);children2 = zeros(1,n);pm0 = pMutation;BestPop = zeros(MaxEranum,n);%分配初始解空间BestPop,TraceTrace = zeros(1,MaxEranum);完整可以运行的数值优化遗传算法源代码Lb = ones(PopSize,1)*bounds(:,1)';Ub = ones(PopSize,1)*bounds(:,2)';%二进制编码采用多点交叉和均匀交叉,并逐步增大均匀交叉概率%浮点编码采用离散交叉(前期)、算术交叉(中期)、AEA重组(后期)OptsCrossOver = [ones(1,MaxEranum)*options(1);...round(unidrnd(2*(MaxEranum-[1:MaxEranum]))/MaxEranum)]';%浮点编码时采用两种自适应变异和一种随机变异(自适应变异发生概率为随机变异发生的2倍)OptsMutation = [ones(1,MaxEranum)*options(1);unidrnd(5,1,MaxEranum)]';if options(1)==3D=zeros(n);CityPosition=bounds;D = sqrt((CityPosition(:, ones(1,n)) - CityPosition(:, ones(1,n))').^2 +...(CityPosition(:,2*ones(1,n)) - CityPosition(:,2*ones(1,n))').^2 );end%========================================================================== % 进化主程序%%===================================== ===================================== eranum = 1;H=waitbar(0,'Please wait...');while(eranum=MaxEranum)for j=1:mif options(1)==1%eval(['[fit(j)]=' FUN '(Pop(j,:));']);%但执行字符串速度比直接计算函数值慢fit(j)=feval(FUN,Pop(j,:));%计算适应度elseif options(1)==0%eval(['[fit(j)]=' FUN '(b2f(Pop(j,:),bounds,bits));']);fit(j)=feval(FUN,(b2f(Pop(j,:),bounds,bits)));elsefit(j)=-feval(FUN,Pop(j,:),D);endend[Maxfit,fitIn]=max(fit);%得到每一代最大适应值Meanfit(eranum)=mean(fit);BestPop(eranum,:)=Pop(fitIn,:);Trace(eranum)=Maxfit;if options(1)==1Pop=(Pop-Lb)./(Ub-Lb);%将定义域映射到[0,1]:[Lb,Ub]--[0,1] ,Pop--(Pop-Lb)./(Ub-Lb)endswitch round(unifrnd(0,eranum/MaxEranum))%进化前期尽量使用实行锦标赛选择,后期逐步增大非线性排名选择case {0} [selectpop]=TournamentSelect(Pop,fit,bits);%锦标赛选择case {1}[selectpop]=NonlinearRankSelect(Pop,fit,bits);%非线性排名选择end完整可以运行的数值优化遗传算法源代码[CrossOverPop]=CrossOver(selectpop,pCross,OptsCrossOver(er anum,:));%交叉[MutationPop]=Mutation(CrossOverPop,fit,pMutation,VarNum,O ptsMutation(eranum,:)); %变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位%更新种群if options(1)==1Pop=Lb+InversionPop.*(Ub-Lb);%还原PopelsePop=InversionPop;endpMutation=pm0+(eranum^3)*(pCross/2-pm0)/(eranum^4); %逐步增大变异率至1/2交叉率percent=num2str(round(100*eranum/MaxEranum));waitbar(eranum/MaxEranum,H,['Evolution complete ',percent,'%']);eranum=eranum+1;endclose(H);% 格式化输出进化结果和解的变化情况t=1:MaxEranum;plot(t,Trace,t,Meanfit);legend('解的变化','种群的变化');title('函数优化的遗传算法');xlabel('进化世代数');ylabel('每一代最优适应度');[MaxFval,MaxFvalIn]=max(Trace);if options(1)==1|options(1)==3X=BestPop(MaxFvalIn,:);elseif options(1)==0X=b2f(BestPop(MaxFvalIn,:),bounds,bits);endhold on;plot(MaxFvalIn,MaxFval,'*');text(MaxFvalIn+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf(' Best generation:\n %d\n\n Best X:\n %s\n\n MaxFval\n %f\n',...MaxFvalIn,num2str(X),MaxFval);disp(str1);% -计时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_t ime(4)-1;end完整可以运行的数值优化遗传算法源代码str2=sprintf('elapsed_time\n %d (h) %d (m) %.4f (s)',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%===================================== ===================================== % 遗传操作子程序%%===================================== ===================================== % -- 初始化种群--% 采用浮点编码和二进制Gray编码(为了克服二进制编码的Hamming悬崖缺点)function [initpop]=InitPop(popsize,bounds,bits,options)numVars=size(bounds,1);%变量数目rang=(bounds(:,2)-bounds(:,1))';%变量范围if options(1)==1initpop=zeros(popsize,numVars);initpop=(ones(popsize,1)*rang).*(rand(popsize,numVars))+(ones (popsize,1)*bounds(:,1)');elseif options(1)==0precision=options(2);%由求解精度确定二进制编码长度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);i1时,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 individualelsefor i=1:popsizeinitpop(i,:)=randperm(numVars);%为Tsp问题初始化种群endend% -- 二进制串解码--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 [NewPop]=NonlinearRankSelect(OldPop,fit,bits) global m n NewPopfit=fit';selectprob=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=[0 cumsum(newfit)];%计算各选择概率之和rNums=rand(m,1);newIn=1;while(newIn=m)NewPop(newIn,:)=OldPop(length(find(rNums(newIn)newfit)),:);newIn=newIn+1;end% -- 锦标赛选择(含精英选择) --function [NewPop]=TournamentSelect(OldPop,fit,bits)global m n NewPopnum=floor(m./2.^(1:10));num(find(num==0))=[];L=length(num);a=sum(num);b=m-a;PopIn=1;while(PopIn=L)r=unidrnd(m,num(PopIn),2^PopIn);[LocalMaxfit,In]=max(fit(r),[],2);SelectIn=r((In-1)*num(PopIn)+[1:num(PopIn)]');NewPop(sum(num(1:PopIn))-num(PopIn)+1:sum(num(1:PopIn)),:)=OldPop(SelectIn,:);PopIn=PopIn+1;r=[];In=[];LocalMaxfit=[];endif b1NewPop((sum(num)+1):(sum(num)+b-1),:)=OldPop(unidrnd(m,1,b-1),:);end[GlobalMaxfit,I]=max(fit);%保留每一代中最佳个体NewPop(end,:)=OldPop(I,:);% -- 交叉操作--function [NewPop]=CrossOver(OldPop,pCross,opts)global m n NewPopr=rand(1,m);完整可以运行的数值优化遗传算法源代码y1=find(rpCross);y2=find(r=pCross);len=length(y1);if len==1|(len2mod(len,2)==1)%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endi=0;if length(y1)=2if opts(1)==1%浮点编码交叉while(i=length(y1)-2)NewPop(y1(i+1),:)=OldPop(y1(i+1),:);NewPop(y1(i+2),:)=OldPop(y1(i+2),:);if opts(2)==0n1%discret crossoverPoints=sort(unidrnd(n,1,2));NewPop(y1(i+1),Points(1):Points(2))=OldPop(y1(i+2),Points(1):Po ints(2));NewPop(y1(i+2),Points(1):Points(2))=OldPop(y1(i+1),Points(1):Po ints(2));elseif opts(2)==1%arithmetical crossoverPoints=round(unifrnd(0,pCross,1,n));CrossPoints=find(Points==1);r=rand(1,length(CrossPoints));NewPop(y1(i+1),CrossPoints)=r.*OldPop(y1(i+1),CrossPoints)+(1 -r).*OldPop(y1(i+2),CrossPoints);NewPop(y1(i+2),CrossPoints)=r.*OldPop(y1(i+2),CrossPoints)+(1 -r).*OldPop(y1(i+1),CrossPoints); else %AEA recombination Points=round(unifrnd(0,pCross,1,n));CrossPoints=find(Points==1);v=unidrnd(4,1,2);NewPop(y1(i+1),CrossPoints)=(floor(10^v(1)*OldPop(y1(i+1),Cro ssPoints))+...10^v(1)*OldPop(y1(i+2),CrossPoints)-floor(10^v(1)*OldPop(y1(i+2),CrossPoints)))/10^v(1);NewPop(y1(i+2),CrossPoints)=(floor(10^v(2)*OldPop(y1(i+2),Cro ssPoints))+...10^v(2)*OldPop(y1(i+1),CrossPoints)-floor(10^v(2)*OldPop(y1(i+1),CrossPoints)))/10^v(2);endi=i+2;endelseif opts(1)==0%二进制编码交叉while(i=length(y1)-2)if opts(2)==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),:)); endi=i+2;endelse %Tsp问题次序杂交for i=0:2:length(y1)-2xPoints=sort(unidrnd(n,1,2));NewPop([y1(i+1)y1(i+2)],xPoints(1):xPoints(2))=OldPop([y1(i+2)y1(i+1)],xPoints(1):xPoints(2));完整可以运行的数值优化遗传算法源代码%NewPop(y1(i+2),xPoints(1):xPoints(2))=OldPop(y1(i+1),xPo ints(1):xPoints(2));temp=[OldPop(y1(i+1),xPoints(2)+1:n)OldPop(y1(i+1),1:xPoints(2))];for del1i=xPoints(1):xPoints(2)temp(find(temp==OldPop(y1(i+2),del1i)))=[];endNewPop(y1(i+1),(xPoints(2)+1):n)=temp(1:(n-xPoints(2)));NewPop(y1(i+1),1:(xPoints(1)-1))=temp((n-xPoints(2)+1):end);temp=[OldPop(y1(i+2),xPoints(2)+1:n)OldPop(y1(i+2),1:xPoints(2))];for del2i=xPoints(1):xPoints(2)temp(find(temp==OldPop(y1(i+1),del2i)))=[];endNewPop(y1(i+2),(xPoints(2)+1):n)=temp(1:(n-xPoints(2)));NewPop(y1(i+2),1:(xPoints(1)-1))=temp((n-xPoints(2)+1):end);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,fit,pMutation,VarNum,opts) global m n NewPopNewPop=OldPop;r=rand(1,m);MutIn=find(r=pMutation);L=length(MutIn);完整可以运行的数值优化遗传算法源代码i=1;if opts(1)==1%浮点变异maxfit=max(fit);upfit=maxfit+0.05*abs(maxfit);if opts(2)==1|opts(2)==3while(i=L)%自适应变异(自增或自减)Point=unidrnd(n);T=(1-fit(MutIn(i))/upfit)^2;q=abs(1-rand^T);%if q1%按严格数学推理来说,这段程序是不能缺少的% q=1%endp=OldPop(MutIn(i),Point)*(1-q);if unidrnd(2)==1NewPop(MutIn(i),Point)=p+q;elseNewPop(MutIn(i),Point)=p;endi=i+1;endelseif opts(2)==2|opts(2)==4%AEA变异(任意变量的某一位变异)while(i=L)Point=unidrnd(n);T=(1-abs(upfit-fit(MutIn(i)))/upfit)^2;v=1+unidrnd(1+ceil(10*T));%v=1+unidrnd(5+ceil(10*eranum/MaxEranum));q=mod(floor(OldPop(MutIn(i),Point)*10^v),10);NewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)-(q-unidrnd(9))/10^v;i=i+1;endelsewhile(i=L)Point=unidrnd(n);if round(rand)NewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)*(1-rand);elseNewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)+(1-OldPop(MutIn(i),Point))*rand; endi=i+1;endendelseif opts(1)==0%二进制串变异if L=1while i=Lk=unidrnd(n,1,VarNum); %设置变异点数(=变量数)for j=1:length(k)if NewPop(MutIn(i),k(j))==1NewPop(MutIn(i),k(j))=0;else完整可以运行的数值优化遗传算法源代码NewPop(MutIn(i),k(j))=1;endendi=i+1;endendelse%Tsp变异if opts(2)==1|opts(2)==2|opts(2)==3|opts(2)==4numMut=ceil(pMutation*m);r=unidrnd(m,numMut,2);[LocalMinfit,In]=min(fit(r),[],2);SelectIn=r((In-1)*numMut+[1:numMut]');while(i=numMut)mPoints=sort(unidrnd(n,1,2));if mPoints(1)~=mPoints(2)NewPop(SelectIn(i),1:mPoints(1)-1)=OldPop(SelectIn(i),1:mPoints(1)-1);NewPop(SelectIn(i),mPoints(1):mPoints(2)-1)=OldPop(SelectIn(i),mPoints(1)+1:mPoints(2));NewPop(SelectIn(i),mPoints(2))=OldPop(SelectIn(i),mPoints(1));NewPop(SelectIn(i),mPoints(2)+1:n)=OldPop(SelectIn(i),mPoints( 2)+1:n);elseNewPop(SelectIn(i),:)=OldPop(SelectIn(i),:);endi=i+1;endr=rand(1,m);MutIn=find(r=pMutation);L=length(MutIn);while i=LmPoints=sort(unidrnd(n,1,2));rIn=randperm(mPoints(2)-mPoints(1)+1);NewPop(MutIn(i),mPoints(1):mPoints(2))=OldPop(MutIn(i),mPoin ts(1)+rIn-1);i=i+1;endendend% -- 倒位操作--function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r=pInversion);len=length(PopIn);if len=1while(i=len)d=sort(unidrnd(n,1,2));完整可以运行的数值优化遗传算法源代码NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1)); i=i+1;。

遗传算法Matlab代码

遗传算法Matlab代码

遗传算法优缺点遗传算法的优点:1. 与问题领域无关切快速随机的搜索能力。

2. 搜索从群体出发,具有潜在的并行性,可以进行多个个体的同时比较,robust.3. 搜索使用评价函数启发,过程简单4. 使用概率机制进行迭代,具有随机性。

5. 具有可扩展性,容易与其他算法结合。

缺点是:1。

没有能够及时利用网络的反馈信息,故算法的搜索速度比较慢,要得要较精确的解需要较多的训练时间。

2。

算法对初始种群的选择有一定的依赖性,能够结合一些启发算法进行改进。

3。

算法的并行机制的潜在能力没有得到充分的利用,这也是当前遗传算法的一个研究热点方向。

核心函数:(1)function [pop]=initializega(num,bounds,eevalFN,eevalOps,options)--初始种群的生成函数【输出参数】pop--生成的初始种群【输入参数】num--种群中的个体数目bounds--代表变量的上下界的矩阵eevalFN--适应度函数eevalOps--传递给适应度函数的参数options--选择编码形式(浮点编码或是二进制编码)[precision F_or_B],如precision--变量进行二进制编码时指定的精度F_or_B--为1时选择浮点编码,否则为二进制编码,由precision指定精度)(2)function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)--遗传算法函数【输出参数】x--求得的最优解endPop--最终得到的种群bPop--最优种群的一个搜索轨迹【输入参数】bounds--代表变量上下界的矩阵evalFN--适应度函数evalOps--传递给适应度函数的参数startPop-初始种群opts[epsilon prob_ops display]--opts(1:2)等同于initializega的options参数,第三个参数控制是否输出,一般为0。

遗传算法matlab代码0304190947

遗传算法matlab代码0304190947
求pop1的每行之和222将二进制编码转化为十进制数2decodechromm函数的功能是将染色体或二进制编码转换为十进制参数spoint表示待解码的二进制串的起始位置对于多个变量而言如有两个变量采用20为表示每个变量为10则第一个变量从1开始另一个变量从11开始
function youhuafun Nhomakorabea=code; N=50; maxgen=50; % Tunable % Tunable end
%Name: crossover.m % 2.4 选择复制 % 选择或复制操作是决定哪些个体可以进入下一代。 程序中采用 赌轮盘选择法选择,这种方法较易实现。 % 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤: % 1) 在第 t 代,由(1)式计算 fsum 和 pi % 2) 产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum % 3) 求 ∑fi≥s 中最小的 k ,则第 k 个个体被选中 % 4) 进行 N 次 2) 、 3)操作,得到 N 个个体,成为第 t=t+1 代种群 %遗传算法子程序 %Name: selection.m %选择复制 function [newpop]=selection(pop,fitvalue) totalfit=sum(fitvalue); %求适应值之和 fitvalue=fitvalue/totalfit; %单个个体被选择的概率 fitvalue=cumsum(fitvalue); %如 cumsum(fitvalue)=[1 3 6 10] [px,py]=size(pop); ms=sort(rand(px,1)); %从小到大排列 fitin=1; newin=1; while newin<=px if(ms(newin))<fitvalue(fitin) newpop(newin)=pop(fitin); newin=newin+1; else fitin=fitin+1; end end % 2.5 交叉 % 交叉(crossover),群体中的每个个体之间都以一定的概率 pc 交叉,即两个个体从各自字符串的某一位置 % (一般是随机确定) 开始互相交换, 这类似生物进化过程中的 基因分裂与重组。例如,假设 2 个父代个体 x1,x2 为: % x1=0100110 % x2=1010001 % 从每个个体的第 3 位开始交叉,交又后得到 2 个新的子代个 体 y1,y2 分别为: % y1=0100001 % y2=1010110 % 这样 2 个子代个体就分别具有了 2 个父代个体的某些特征。 利用交又我们有可能由父代个体在子代组合成具有更高适合度 的个体。 % 事实上交又是遗传算法区别于其它传统优化方法的主要特点 之一。 %遗传算法子程序 % 2.7 求出群体中最大得适应值及其个体 %遗传算法子程序 fitvalue=[1 2 3 4], 则 % 2.6 变异 % 变异(mutation),基因的突变普遍存在于生物的进化过程中。 变异是指父代中的每个个体的每一位都以概率 pm 翻转,即由 “1”变为“0”, % 或由“0”变为“1”。遗传算法的变异特性可以使求解过程随机地 搜索到解可能存在的整个空间,因此可以在一定程度上求得全局 最优解。 %遗传算法子程序 %Name: mutation.m %变异 function [newpop]=mutation(pop,pm) [px,py]=size(pop); newpop=ones(size(pop)); for i=1:px if(rand<pm) mpoint=round(rand*py); if mpoint<=0 mpoint=1; end newpop(i)=pop(i); if any(newpop(i,mpoint))==0 newpop(i,mpoint)=1; else newpop(i,mpoint)=0; end else newpop(i)=pop(i); end end %交叉 function [newpop]=crossover(pop,pc) [px,py]=size(pop); newpop=ones(size(pop)); for i=1:2:px-1 if(rand<pc) cpoint=round(rand*py); newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)]; newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)]; else newpop(i,:)=pop(i); newpop(i+1,:)=pop(i+1); end end

matlab智能算法代码

matlab智能算法代码

matlab智能算法代码MATLAB是一种功能强大的数值计算和科学编程软件,它提供了许多智能算法的实现。

下面是一些常见的智能算法及其在MATLAB中的代码示例:1. 遗传算法(Genetic Algorithm):MATLAB中有一个专门的工具箱,称为Global Optimization Toolbox,其中包含了遗传算法的实现。

以下是一个简单的遗传算法示例代码:matlab.% 定义目标函数。

fitness = @(x) x^2;% 设置遗传算法参数。

options = gaoptimset('Display', 'iter','PopulationSize', 50);% 运行遗传算法。

[x, fval] = ga(fitness, 1, options);2. 粒子群优化算法(Particle Swarm Optimization):MATLAB中也有一个工具箱,称为Global Optimization Toolbox,其中包含了粒子群优化算法的实现。

以下是一个简单的粒子群优化算法示例代码:matlab.% 定义目标函数。

fitness = @(x) x^2;% 设置粒子群优化算法参数。

options = optimoptions('particleswarm', 'Display','iter', 'SwarmSize', 50);% 运行粒子群优化算法。

[x, fval] = particleswarm(fitness, 1, [], [], options);3. 支持向量机(Support Vector Machine):MATLAB中有一个机器学习工具箱,称为Statistics and Machine Learning Toolbox,其中包含了支持向量机的实现。

遗传算法matlab程序代码

遗传算法matlab程序代码

function [R,Rlength]= GA_TSP(xyCity,dCity,Population,nPopulation,pCrossover,percent,pMutation,generation,nR,rr,rang eCity,rR,moffspring,record,pi,Shock,maxShock)clear allA=load('d.txt');AxyCity=[A(1,:);A(2,:)]; %x,y为各地点坐标xyCityfigure(1)grid onhold onscatter(xyCity(1,:),xyCity(2,:),'b+')grid onnCity=50;nCityfor i=1:nCity %计算城市间距离for j=1:nCitydCity(i,j)=abs(xyCity(1,i)-xyCity(1,j))+abs(xyCity(2,i)-xyCity(2,j));endend %计算城市间距离xyCity; %显示城市坐标dCity %显示城市距离矩阵%初始种群k=input('取点操作结束'); %取点时对操作保护disp('-------------------')nPopulation=input('种群个体数量:'); %输入种群个体数量if size(nPopulation,1)==0nPopulation=50; %默认值endfor i=1:nPopulationPopulation(i,:)=randperm(nCity-1); %产生随机个体endPopulation %显示初始种群pCrossover=input('交叉概率:'); %输入交叉概率percent=input('交叉部分占整体的百分比:'); %输入交叉比率pMutation=input('突变概率:'); %输入突变概率nRemain=input('最优个体保留最大数量:');pi(1)=input('选择操作最优个体被保护概率:');%输入最优个体被保护概率pi(2)=input('交叉操作最优个体被保护概率:');pi(3)=input('突变操作最优个体被保护概率:');maxShock=input('最大突变概率:');if size(pCrossover,1)==0pCrossover=0.85;endif size(percent,1)==0percent=0.5;endif size(pMutation,1)==0pMutation=0.05;endShock=0;rr=0;Rlength=0;counter1=0;counter2=0;R=zeros(1,nCity-1);[newPopulation,R,Rlength,counter2,rr]=select(Population,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain);R0=R;record(1,:)=R;rR(1)=Rlength;Rlength0=Rlength;generation=input('算法终止条件A.最多迭代次数:');%输入算法终止条件if size(generation,1)==0generation=200;endnR=input('算法终止条件B.最短路径连续保持不变代数:');if size(nR,1)==0nR=10;endwhile counter1<generation&counter2<nRif counter2<nR*1/5Shock=0;elseif counter2<nR*2/5Shock=maxShock*1/4-pMutation;elseif counter2<nR*3/5Shock=maxShock*2/4-pMutation;elseif counter2<nR*4/5Shock=maxShock*3/4-pMutation;elseShock=maxShock-pMutation;endcounter1newPopulationoffspring=crossover(newPopulation,nCity,pCrossover,percent,nPopulation,rr,pi,nRemain);offspringmoffspring=Mutation(offspring,nCity,pMutation,nPopulation,rr,pi,nRemain,Shock);[newPopulation,R,Rlength,counter2,rr]=select(moffspring,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain);counter1=counter1+1;rR(counter1+1)=Rlength;record(counter1+1,:)=R;endR0;Rlength0;R;Rlength;minR=min(rR);disp('最短路经出现代数:')rr=find(rR==minR)disp('最短路经:')record(rr,:);mR=record(rr(1,1),:)disp('终止条件一:')counter1disp('终止条件二:')counter2disp('最短路经长度:')minRdisp('最初路经长度:')rR(1)figure(2)plotaiwa(xyCity,mR,nCity)figure(3)i=1:counter1+1;plot(i,rR(i))grid onfunction[newPopulation,R,Rlength,counter2,rr]=select(Population,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain)Distance=zeros(nPopulation,1); %零化路径长度Fitness=zeros(nPopulation,1); %零化适应概率Sum=0; %路径长度for i=1:nPopulation %计算个体路径长度for j=1:nCity-2Distance(i)=Distance(i)+dCity(Population(i,j),Population(i,j+1));end %对路径长度调整,增加起始点到路径首尾点的距离Distance(i)=Distance(i)+dCity(Population(i,1),nCity)+dCity(Population(i,nCity-1),nCity);Sum=Sum+Distance(i); %累计总路径长度end %计算个体路径长度if Rlength==min(Distance)counter2=counter2+1;elsecounter2=0;endRlength=min(Distance); %更新最短路径长度Rlength;rr=find(Distance==Rlength);R=Population(rr(1,1),:); %更新最短路径for i=1:nPopulationFitness(i)=(max(Distance)-Distance(i)+0.001)/(nPopulation*(max(Distance)+0.001)-Sum); %适应概率=个体/总和。

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

遗传算法经典学习Matlab代码遗传算法实例:也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。

对于初学者,尤其是还没有编程经验的非常有用的一个文件遗传算法实例% 下面举例说明遗传算法 %% 求下列函数的最大值 %% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。

%% 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。

%% %%--------------------------------------------------------------------------------------------------------------%%--------------------------------------------------------------------------------------------------------------%% 编程%-----------------------------------------------% 2.1初始化(编码)% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。

%遗传算法子程序%Name: initpop.m%初始化function pop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,% roud对矩阵的每个单元进行圆整。

这样产生的初始种群。

% 2.2 计算目标函数值% 2.2.1 将二进制数转化为十进制数(1)%遗传算法子程序%Name: decodebinary.m%产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制function pop2=decodebinary(pop)[px,py]=size(pop); %求pop行和列数for i=1:pypop1(:,i)=2.^(py-i).*pop(:,i);endpop2=sum(pop1,2); %求pop1的每行之和% 2.2.2 将二进制编码转化为十进制数(2)% decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置% (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。

本例为1),% 参数1ength表示所截取的长度(本例为10)。

%遗传算法子程序%Name: decodechrom.m%将二进制编码转换成十进制function pop2=decodechrom(pop,spoint,length)pop1=pop(:,spoint:spoint+length-1);pop2=decodebinary(pop1);% 2.2.3 计算目标函数值% calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。

%遗传算法子程序%Name: calobjvalue.m%实现目标函数的计算function [objvalue]=calobjvalue(pop)temp1=decodechrom(pop,1,10); %将pop每行转化成十进制数x=temp1*10/1023; %将二值域中的数转化为变量域的数objvalue=10*sin(5*x)+7*cos(4*x); %计算目标函数值% 2.3 计算个体的适应值%遗传算法子程序%Name:calfitvalue.m%计算个体的适应值function fitvalue=calfitvalue(objvalue)global Cmin;Cmin=0;[px,py]=size(objvalue);for i=1:pxif objvalue(i)+Cmin>0temp=Cmin+objvalue(i);elsetemp=0.0;endfitvalue(i)=temp;endfitvalue=fitvalue';% 2.4 选择复制% 选择或复制操作是决定哪些个体可以进入下一代。

程序中采用赌轮盘选择法选择,这种方法较易实现。

% 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤:% 1)在第 t 代,由(1)式计算 fsum 和 pi% 2)产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum% 3)求∑fi≥s 中最小的 k ,则第 k 个个体被选中% 4)进行 N 次2)、3)操作,得到 N 个个体,成为第 t=t+1 代种群%遗传算法子程序%Name: selection.m%选择复制function [newpop]=selection(pop,fitvalue)totalfit=sum(fitvalue); %求适应值之和fitvalue=fitvalue/totalfit; %单个个体被选择的概率fitvalue=cumsum(fitvalue); %如 fitvalue=[1 2 3 4],则 cumsum(fitvalue)=[1 3 6 10][px,py]=size(pop);ms=sort(rand(px,1)); %从小到大排列fitin=1;newin=1;while newin<=pxif(ms(newin))<fitvalue(fitin)newpop(newin)=pop(fitin);newin=newin+1;elsefitin=fitin+1;endend% 2.5 交叉% 交叉(crossover),群体中的每个个体之间都以一定的概率 pc 交叉,即两个个体从各自字符串的某一位置% (一般是随机确定)开始互相交换,这类似生物进化过程中的基因分裂与重组。

例如,假设2个父代个体x1,x2为:% x1=0100110% x2=1010001% 从每个个体的第3位开始交叉,交又后得到2个新的子代个体y1,y2分别为:% y1=0100001% y2=1010110% 这样2个子代个体就分别具有了2个父代个体的某些特征。

利用交又我们有可能由父代个体在子代组合成具有更高适合度的个体。

% 事实上交又是遗传算法区别于其它传统优化方法的主要特点之一。

%遗传算法子程序%Name: crossover.m%交叉function [newpop]=crossover(pop,pc)[px,py]=size(pop);newpop=ones(size(pop));for i=1:2:px-1if(rand<pc)cpoint=round(rand*py);newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)];newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)];elsenewpop(i,:)=pop(i);newpop(i+1,:)=pop(i+1);endend% 2.6 变异% 变异(mutation),基因的突变普遍存在于生物的进化过程中。

变异是指父代中的每个个体的每一位都以概率 pm 翻转,即由“1”变为“0”,% 或由“0”变为“1”。

遗传算法的变异特性可以使求解过程随机地搜索到解可能存在的整个空间,因此可以在一定程度上求得全局最优解。

%遗传算法子程序%Name: mutation.m%变异function [newpop]=mutation(pop,pm)[px,py]=size(pop);newpop=ones(size(pop));for i=1:pxif(rand<pm)mpoint=round(rand*py);if mpoint<=0mpoint=1;endnewpop(i)=pop(i);if any(newpop(i,mpoint))==0 newpop(i,mpoint)=1;elsenewpop(i,mpoint)=0;endelsenewpop(i)=pop(i);end% 2.7 求出群体中最大得适应值及其个体%遗传算法子程序%Name: best.m%求出群体中适应值最大的值function [bestindividual,bestfit]=best(pop,fitvalue) [px,py]=size(pop);bestindividual=pop(1,:);bestfit=fitvalue(1);for i=2:pxif fitvalue(i)>bestfitbestindividual=pop(i,:);bestfit=fitvalue(i);end% 2.8 主程序%遗传算法主程序%Name:genmain05.mclearclfpopsize=20; %群体大小chromlength=10; %字符串长度(个体长度)pc=0.6; %交叉概率pm=0.001; %变异概率pop=initpop(popsize,chromlength); %随机产生初始群体for i=1:20 %20为迭代次数[objvalue]=calobjvalue(pop); %计算目标函数fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度[newpop]=selection(pop,fitvalue); %复制[newpop]=crossover(pop,pc); %交叉[newpop]=mutation(pop,pc); %变异[bestindividual,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值y(i)=max(bestfit);n(i)=i;pop5=bestindividual;x(i)=decodechrom(pop5,1,chromlength)*10/1023;pop=newpop;endfplot('10*sin(5*x)+7*cos(4*x)',[0 10])hold onplot(x,y,'r*')hold off[z index]=max(y); %计算最大值及其位置x5=x(index)%计算最大值对应的x值y=z【问题】求f(x)=x 10*sin(5x) 7*cos(4x)的最大值,其中0<=x<=9【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08【程序清单】%编写目标函数function[sol,eval]=fitness(sol,options)x=sol(1);eval=x 10*sin(5*x) 7*cos(4*x);%把上述函数存储为fitness.m文件并放在工作目录下initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenT erm',25,'normGeomSelect',...[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代运算借过为:x =7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)注:遗传算法一般用来取得近似最优解,而不是最优解。

相关文档
最新文档