完整的遗传算法函数Matlab程序【精品毕业设计】(完整版)

合集下载

遗传算法matlab程序实例

遗传算法matlab程序实例

;)1rts(psid ;))):,I(poPtseB(rts2mun,lavFxaM,)X(rts2mun,I,'s%�是 体 色 染 应 对 n\f% 值 优 最 的 解 求 次 本 得 , 时 s% 为 量 变 自 , 代 d% 到 化 进 '( ftnirps=1rts ;)])lavFxaM(rts2mun '=XAMF'[,lavFxaM,5+I(txet ;)'*',lavFxaM,I(tolp ;no dloh ;))1+)stib(htgnel:2(,I(ecarT=X ;))1,:(ecarT(xam=]I,lavFxaM[ ;)')ssentifxam( 度 应 适 优 最 代 一 每 '(lebaly;)')munare( 数 代 世 化 进 '(lebalx;)' 法 算 传 遗 的 化 优 数 函 '(eltit
;)borptceles(tros=])2,:(x y[ ;']1:1-:m[=)1,:(x ;)2,m(sorez=x 率概的优最择选%;)borptceles(xam=q )1,0(度应适对相体个各算计%;)tif(mus/tif=borptceles d ne 据依名排做值应适为值数函以%;)))stib,sdnuob,):,i(pop(f2b(,):,1(NUF(lavef=)i(tif m:1=i rof ;)1,m(sorez=tif ;)n,m(sorez=poptceles n m labolg )stib,sdnuob,pop,NUF(tceleSknaRraenilnoN=]poptceles[ noitcnuf 1=))i(P(mus ,)n(P>...>)1(P>)0(P 中其 ,i^)q-1(*)n^)q-1(-1/q(=)i(P% �率概择选配分小到大从值应适按员成体个各% 择选名排性线非的法赌盘轮于基用采% 作操择选%

遗传算法的MATLAB程序实例之欧阳歌谷创编

遗传算法的MATLAB程序实例之欧阳歌谷创编

遗传算法的程序实例欧阳歌谷(2021.02.01)如求下列函数的最大值f(x)=10*sin(5x)+7*cos(4x) x∈[0,10]一、初始化(编码)initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),长度大小取决于变量的二进制编码的长度(在本例中取10位)。

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

这样产生的初始种群。

二、计算目标函数值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-1).*pop(:,i);py=py-1;endpop2=sum(pop1,2); %求pop1的每行之和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);3、计算目标函数值calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。

2020年遗传算法matlab程序实例精编版

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遗传算法工具箱函数及实例讲解核心函数:(1)function [pop]=initializega(num,bo unds,eevalFN,eevalOps,optio ns)--初始种群的生成函数【输出参数】pop--生成的初始种群【输入参数】num--种群中的个体数目bo unds--代表变量的上下界的矩阵eevalFN--适应度函数eevalOps--传递给适应度函数的参数op tions--选择编码形式(浮点编码或是二进制编码)[p recision F_o r_B],如p recisio n--变量进行二进制编码时指定的精度F_or_B--为1时选择浮点编码,否则为二进制编码,由p recision指定精度)(2)function [x,endPop,bPop,trace Info] = ga(bounds,evalFN,evalOps,sta rtPop,op ts,...te rmFN,te rmOps,selectFN,selectOps,xOve rFNs,xOve rOps,mutFNs,mutOps)--遗传算法函数【输出参数】x--求得的最优解e ndPop--最终得到的种群bPop--最优种群的一个搜索轨迹【输入参数】bo unds--代表变量上下界的矩阵evalFN--适应度函数evalOps--传递给适应度函数的参数sta rtPop-初始种群op ts[epsilon p rob_ops display]--opts(1:2)等同于initializega的options参数,第三个参数控制是否输出,一般为0。

如[1e-6 1 0]te rmFN--终止函数的名称,如['maxGe nTerm']te rmOps--传递个终止函数的参数,如[100]selectFN--选择函数的名称,如['no rmGeo mSelect']selectOps--传递个选择函数的参数,如[0.08]xOve rFNs--交叉函数名称表,以空格分开,如['arithXover heuristicXove r simple Xove r'] xOve rOps--传递给交叉函数的参数表,如[2 0;2 3;2 0]mutFNs--变异函数表,如['boundaryMuta tio n multiNonU nifMuta tio n nonU nifMutatio n unifMuta tion']mutOps--传递给交叉函数的参数表,如[4 0 0;6 100 3;4 100 3;4 0 0]注意】matlab工具箱函数必须放在工作目录下【问题】求f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中0<=x<=9【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08【程序清单】%编写目标函数functio n[sol,eval]=fitness(sol,op tio ns)x=sol(1);eval=x+10*sin(5*x)+7*cos(4*x);%把上述函数存储为fitness.m文件并放在工作目录下initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10[x e ndPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'ma xGenTerm',25,'no rmGeo mSelect',...[0.08],['arithXove r'],[2],'no nU nifMuta tio n',[2 25 3]) %25次遗传迭代运算借过为:x =7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)注:遗传算法一般用来取得近似最优解,而不是最优解。

遗传算法的MATLAB程序实例

遗传算法的MATLAB程序实例

遗传算法的法式实例之迟辟智美创作如求下列函数的最年夜值f(x)=10*sin(5x)+7*cos(4x) x∈[0,10]一、初始化(编码)initpop.m函数的功能是实现群体的初始化,popsize暗示群体的年夜小,chromlength暗示染色体的长度(二值数的长度),长度年夜小取决于变量的二进制编码的长度(在本例中取10位).代码:%Name: initpop.m%初始化function pop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength));% rand随机发生每个单位为{0,1} 行数为popsize,列数为chromlength的矩阵,% roud对矩阵的每个单位进行圆整.这样发生的初始种群.二、计算目标函数值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-1).*pop(:,i);py=py-1;endpop2=sum(pop1,2); %求pop1的每行之和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);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);%计算目标函数值三、计算个体的适应值四选择复制选择或复制把持是决定哪些个体可以进入下一代.法式中采纳赌轮盘选择法选择,这种方法较易实现.根据方程pi=fi/∑fi=fi/fsum ,选择步伐:1)在第t 代,由(1)式计算fsum 和pi2)发生{0,1} 的随机数rand( .),求s=rand( .)*fsum3)求∑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)); %从小到年夜排列,将"rand(px,1)"发生的一列随机数酿成轮盘赌形式的暗示方法,由小到年夜排列fitin=1; %fivalue是一向量,fitin代表向量中元素位,即fitvalue(fitin)代表第fitin个个体的单个个体被选择的概率newin=1; %同理while newin<=pxif(ms(newin))<fitvalue(fitin) %ms(newin)暗示的是ms 列向量中第"newin"位数值,同理fitvalue(fitin)newpop(newin,:)=pop(fitin,:); %赋值,即将旧种群中的第fitin个个体保管到下一代(newpop)newin=newin+1;elsefitin=fitin+1;endend五2.5 交叉交叉(crossover),群体中的每个个体之间都以一定的概率pc 交叉,即两个个体从各自字符串的某一位置(一般是随机确定)开始互相交换,这类似生物进化过程中的基因分裂与重组.例如,假设2个父代个体x1,x2为:x1=0100110x2=1010001从每个个体的第3位开始交叉,交又后获得2个新的子代个体y1,y2分别为:y1=0100001y2=1010110这样2个子代个体就分别具有了2个父代个体的某些特征.利用交又我们有可能由父代个体在子代组合成具有更高适合度的个体.事实上交又是遗传算法区别于其它传统优化方法的主要特点之一.%Name: crossover.m%交叉function [newpop]=crossover_multiv(pop,pc)global Numv[px,py]=size(pop);m=py/Numv;for j=1:Numvpop1=ones(px,m);pop2=pop(:,m*(j-1)+1:m*j); %取出相应变量对应的二进制编码段for i=1:2:px-1if(rand<pc)cpoint=round(rand*(m-1)); %cpoint为交叉点pop1(i,:)=[pop2(i,1:cpoint) pop2(i+1,cpoint+1:m)];pop1(i+1,:)=[pop2(i+1,1:cpoint) pop2(i,cpoint+1:m)];elsepop1(i,:)=pop2(i,1:m);pop1(i+1,:)=pop2(i+1,1:m);endendnewpop(:,m*(j-1)+1:m*j)=pop1; %将交叉后的一个参数的编码放入新种群中end六、变异变异(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<=0 mpoint=1;endnewpop(i,:)=pop(i,:);if any(newpop(i,mpoint))==0 newpop(i,mpoint)=1;else newpop(i,mpoint)=0;endelsenewpop(i,:)=pop(i,:);endend七、求出群体中最年夜得适应值及其个体%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);endend八、主法式%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。

遗传算法及其MATLAB实现

遗传算法及其MATLAB实现

Y
输出结果 终止
N
计算群体中各个体适应度 从左至右依次执行遗传算子
pm
j=0 选择个体变异点 执行变异
pc
j=0 根据适应度选择复制个体 执行复制
j=0 选择两个交叉个体 执行交叉 将交叉后的两个新个体 添入新群体中 j = j+2
将复制的个体添入 新群体中
j = j+1
将变异后的个体添入 新群体中
发展
遗传算法——进化计算——计算智能——人工智能 70年代初,Holland提出了“模式定理”(Schema Theorem),一般认为是“遗 传算法的基本定理”,从而奠定了遗传算法研究的理论基础; 1985年,在美国召开了第一届遗传算法国际会议,并且成立了国际遗传算法学会 (ISGA,International Society of Genetic Algorithms); 1989年,Holland的学生D. J. Goldherg出版了“Genetic Algorithms in Search, Optimization, and Machine Learning”,对遗传算法及其应用作了全面而系统的论 述; 1991年,L. Davis编辑出版了《遗传算法手册》,其中包括了遗传算法在工程技术 和社会生活中大量的应用实例。
⑦倒位运算:对一复杂的问题可能需要用到“倒位”。倒位是指 一个染色体某区段正常排列顺序发生 的颠倒造成染色体内的 180

DNA序列重新排列,它包括臂内倒位和臂间倒位。 例:染色体S=1001011011101110011010101001划线部分倒位得 ' S =100101100101001110111101001
'
'
首先用随机数产生一个或多个交配点位置,然后两个个体在交配 点位置互换部分基因码形成两个子个体。 例:有两条染色体S 01001011 ,S 10010101 交换后4位基因得 ,S 10011011 S 01000101 可以被看成是原染色体 S1 和S 2 的子代染色体。

(完整版)基于改进遗传算法的路径规划MATLAB实现

基于遗传算法的路径规划MATLAB实现主程序:clear all;close all;t=23; %过程点个数=t-1s=500; %种群规模pc=0.90; %交叉概率pm=0.20; %变异概率pop=zeros(s,t);for i=1:spop(i,1:t-1)=randperm(t-1);endfor k=1:1:2000 %进化代次数kif mod(k,10)==1kendpop=lujingdis(pop);c=15;%选择淘汰个数pop=lujingselect(pop,c);p=rand;if p>=pcpop=lujingcross(pop);endif p>=pmpop=lujingmutate(pop);Endendpopmin(pop(:,t))J=pop(:,t);fi=1./J;[Oderfi,Indexfi]=sort(fi); %安排fi从小到大BestS=pop(Indexfi(s),:); %使BestS=E(m),m即是属于max(fi)的Indexfi I=BestS;x=[2 3 6 10 14 17 22 20 23 25 30 28 25 21 29 16 18 15 9 11 6 5 ];y=[5 26 14 29 27 24 28 22 26 30 30 17 13 15 4 13 3 1 6 2 2 7];%过程点坐标% x=[1 2 3 4 6 9 11 10 8 9 6 4]; %12个过程点的坐标% y=[1 2 3 4 8 10 11 9 5 2 1 2];for i=1:1:t-1x1(i)=x(I(i));y1(i)=y(I(i));endx(t)=x(I(1));y(t)=y(I(1));a = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 11 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 0 0 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 11 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 11 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 01 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 11 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 11 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 10 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1];%31*31栅格%a = [1 1 1 1 1 1 1 1 1 11 1 1 0 0 1 1 1 0 01 0 1 0 0 1 1 1 1 10 0 1 1 1 1 0 1 1 01 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 11 0 0 1 1 0 1 1 1 11 1 1 1 1 1 1 1 1 01 1 1 1 1 1 1 1 1 10 1 1 1 1 1 0 0 1 1];%11*11栅格b = a;b(end+1,end+1) = 0;colormap([0 0 0;1 1 1]),pcolor(b)axis image xy;%绘制栅格图hold on;figure(1);plot(x,y,'-or');适应度函数程序:lujingdis.mfunction [pop]=qiujuli(pop)[s,t]=size(pop);for i=1:1:sdd=0;for j=1:1:t-2dd=dd+lujingcalculate(pop(i,j),pop(i,j+1));endpop(i,t)=dd;End距离计算程序:lujingcalculate.mfunction [d]=juli(m,n)x=[2 3 6 10 14 17 22 20 23 25 30 28 25 21 29 16 18 15 9 11 6 5 ]; y=[5 26 14 29 27 24 28 22 26 30 30 17 13 15 4 13 3 1 6 2 2 7]; %x=[1 2 3 4 6 9 11 10 8 9 6 4];% y=[1 2 3 4 8 10 11 9 5 2 1 2];d=sqrt((x(m)-x(n))^2+(y(m)-y(n))^2);选择算子程序:lujingselect.mfunction [pop]=select(pop,k)[s,t]=size(pop);m11=(pop(:,t));m11=m11';mmax=zeros(1,k);mmin=zeros(1,k);num=1;while num<k+1[a,mmax(num)]=max(m11);m11(mmax(num))=a;num=num+1;endnum=1;while num<k+1[b,mmin(num)]=min(m11);m11(mmin(num))=a;num=num+1;endfor i=1:kpop(mmax(i),:)=pop(mmin(i),:);End交叉算子程序:lujingcross.mfunction [pop]=cross(pop)[s,t]=size(pop);pop1=pop;for i=1:2:sm=randperm(t-3)+1;crosspoint(1)=min(m(1),m(2));crosspoint(2)=max(m(1),m(2));for j=1:crosspoint(1)while find(pop(i,crosspoint(1)+1:crosspoint(2))==pop(i,j))zhi=find(pop(i,crosspoint(1)+1:crosspoint(2))==pop(i,j));y=pop(i+1,crosspoint(1)+zhi);pop(i,j)=y;endendfor j=crosspoint(2)+1:t-1while find(pop(i,crosspoint(1)+1:crosspoint(2))==pop(i,j))zhi=find(pop(i,crosspoint(1)+1:crosspoint(2))==pop(i,j));y=pop(i+1,crosspoint(1)+zhi);pop(i,j)=y;endendend[pop]=lujingdis(pop);for i=1:sif pop1(i,t)<pop(i,t)pop(i,:)=pop1(i,:);endEnd变异算子程序:lujingmutate.mfunction [pop] = mutate(pop)[s,t]=size(pop);pop1=pop;for i=1:2:sm=randperm(t-3)+1;mutatepoint(1)=min(m(1),m(2));mutatepoint(2)=max(m(1),m(2));mutate =round((mutatepoint(2)-mutatepoint(1))/2-0.5);for j=1:mutatezhong=pop(i,mutatepoint(1)+j);pop(i,mutatepoint(1)+j)=pop(i,mutatepoint(2)-j);pop(i,mutatepoint(2)-j)=zhong;endend[pop]=lujingdis(pop);for i=1:sif pop1(i,t)<pop(i,t)pop(i,:)=pop1(i,:);endend。

用Matlab实现遗传算法

用GA找到函数最小值x = ga(fitnessfcn,nvars)局部无约束最小值,x是目标函数的适应度函数,nvars是适应度函数的尺寸(设计变量的数量)。

目标函数和适应度函数接受了1×N大小的x矢量,在x返回一个标量的计算值。

x = ga(fitnessfcn,nvars,A,b)在线性不等式约束下,适应度函数的局部最小值。

如果这个问题有m个线性不等式和n个变量,则A是m×n矩阵,b是m×1矩阵。

注意:当人口类型选项设置为“位串”或者“自定义”,线性约束不满足。

x = ga(fitnessfcn,nvars,A,b,Aeq,beq)存在线性等式约束下,适应度函数的局部最小值。

如果没有不等式存在,设置A=[] 和 b=[]。

如果问题存在r个线性等式约束和n个变量,那么Aeq 是r ×n矩阵的大小,beq是r大小的矢量。

注意:当人口类型选项设置为“位串”或者“自定义”,线性约束不满足。

x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB)定义了一系列设计变量x的最小和最大边界。

以至于在范围内找到一个解。

如果没有边界存在,LB 和 UB设置为空矩阵。

如果x(i)无下界,设置LB(i) = -Inf;如果x(i)无上界,设置UB(i) = Inf。

x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon)服从在非线性约束条件下的最小值,非线性函数接收x,返回C和Ceq向量,分别代表非线性的不等式和等式。

GA最小化适应度函数,在C(x)≤0和Ceq(x)=0的条件下。

如果无边界存在,设置 LB=[] 和 UB=[]。

注意:当人口类型选项设置为“位串”或者“自定义”,非线性约束不满足。

x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon,options)用在结构选项中的值代替默认的优化参数来进行最小化,它也可以用gaoptimset函数来创建,具体参考gaoptimset的用法。

遗传算法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;endendnewpop;clear cpoint12;clear cpoint22;clear randnum;clear int;for ium=1:popsizevector1=newpop(ium,:);obj1(ium)=hanshu(hromlength,vector1,phen);endclear ium;obj1max=max(obj1);for ar=1:popsizeif obj1(ar)==obj1maxnewpop(ar,:)=opti;endend%遗传操作结束二.粒子群算法源程序:%------初始格式化-------------------------------------------------- clear all;clc;format long;%------给定初始化条件---------------------------------------------- c1=1.4962;%学习因子1c2=1.4962;%学习因子2w=0.7298;%惯性权重MaxDT=100;%最大迭代次数D=2;%搜索空间维数(未知数个数)N=40;%初始化群体个体数目eps=10^(-6);%设置精度(在已知最小值时候用)%------初始化种群的个体(可以在这里限定位置和速度的范围)------------ for i=1:Nfor j=1:Dx(i,j)=randn;%随机初始化位置v(i,j)=randn;%随机初始化速度endend%------先计算各个粒子的适应度,并初始化Pi和Pg---------------------- for i=1:Np(i)=fitness(x(i,:),D);y(i,:)=x(i,:);endpg=x(1,:);%Pg为全局最优for i=2:Nif fitness(x(i,:),D)<FITNESS(pg,D)pg=x(i,:);endend%------进入主要循环,按照公式依次迭代,直到满足精度要求------------ for t=1:MaxDTtfor i=1:Nv(i,:)=w*v(i,:)+c1*rand*(y(i,:)-x(i,:))+c2*rand*(pg-x(i,:)); x(i,:)=x(i,:)+v(i,:);if fitness(x(i,:),D)<p(i)p(i)=fitness(x(i,:),D);y(i,:)=x(i,:);endif p(i)<FITNESS(pg,D)pg=y(i,:);endendPbest(t)=fitness(pg,D);end%------进入主要循环,按照公式依次迭代,直到满足精度要求------------ for t=1:MaxDTfor i=1:Nv(i,:)=w*v(i,:)+c1*rand*(y(i,:)-x(i,:))+c2*rand*(pg-x(i,:));x(i,:)=x(i,:)+v(i,:);if fitness(x(i,:),D)<p(i)p(i)=fitness(x(i,:),D);y(i,:)=x(i,:);endif p(i)<FITNESS(pg,D)pg=y(i,:);endendPbest(t)=fitness(pg,D);end%------最后给出计算结果disp('*************************************************************') disp('函数的全局最优位置为:')Solution=pg'disp('最后得到的优化极值为:')Result=fitness(pg,D)disp('*************************************************************') [X,Y]=meshgrid(-500:2:500);Z=X.*sin(sqrt(X))+Y.*(sin(sqrt(Y)));hold oncontour(X,Y,Z)plot(x(:,1),x(:,2),'*');hold off标准文档实用文案。

(实例)matlab遗传算法工具箱函数及实例讲解

(实例)matlab遗传算法工具箱函数及实例讲解matlab遗传算法工具箱函数及实例讲解核心函数:(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,xOverO ps,mutFNs,mutOps)--遗传算法函数【输出参数】x--求得的最优解endPop--最终得到的种群bPop--最优种群的一个搜索轨迹【输入参数】bounds--代表变量上下界的矩阵evalFN--适应度函数evalOps--传递给适应度函数的参数startPop-初始种群opts[epsilon prob_ops display]--opts(1:2)等同于initializega 的options参数,第三个参数控制是否输出,一般为0。

如[1e-6 1 0] termFN--终止函数的名称,如['maxGenTerm']termOps--传递个终止函数的参数,如[100]selectFN--选择函数的名称,如['normGeomSelect']selectOps--传递个选择函数的参数,如[0.08]xOverFNs--交叉函数名称表,以空格分开,如['arithXover heuristicXover simpleXover']xOverOps--传递给交叉函数的参数表,如[2 0;2 3;2 0]mutFNs--变异函数表,如['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'] mutOps--传递给交叉函数的参数表,如[4 0 0;6 100 3;4 100 3;4 0 0]matlab遗传算法工具箱附件【注意】matlab工具箱函数必须放在工作目录下【问题】求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],'maxGenTerm',25,'normGeomSelect',...[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代运算结果为:x =7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)注:遗传算法一般用来取得近似最优解,而不是最优解。

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

完整的遗传算法函数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==12 disp('Insufficient arguements') end if n<3 %Default eevalation opts. eevalOps=[]; end if n<5 opts = [1e-6 1 0]; end if isempty(opts) opts = [1e-6 1 0]; end

if any(eevalFN<48) %Not using a .m file if opts(2)==1 %Float ga e1str=['x=c1; c1(xZomeLength)=', eevalFN ';']; e2str=['x=c2; c2(xZomeLength)=', eevalFN ';']; else %Binary ga e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',... eevalFN ';']; end else %Are using a .m file if opts(2)==1 %Float ga e1str=['[c1 c1(xZomeLength)]=' eevalFN '(c1,[gen eevalOps]);']; e2str=['[c2 c2(xZomeLength)]=' eevalFN '(c2,[gen eevalOps]);']; else %Binary ga e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' eevalFN ... '(x,[gen eevalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];']; end end

if n<6 %Default termination information termOps=[100]; termFN='maxGenTerm'; end if n<12 %Default muatation information if opts(2)==1 %Float GA mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0]; else %Binary GA mutFNs=['binaryMutation']; mutOps=[0.05]; end end if n<10 %默认的交叉信息 if opts(2)==1 %浮点编码 xOverFNs=['arithXover heuristicXover simpleXover']; xOverOps=[2 0;2 3;2 0]; else %Binary GA xOverFNs=['simpleXover']; xOverOps=[0.6]; end end if n<9 %Default select opts only i.e. roullete wheel. selectOps=[]; end if n<8 %Default select info selectFN=['normGeomSelect']; selectOps=[0.08]; end if n<6 %默认的算法终止准则 termOps=[100]; termFN='maxGenTerm'; end if n<4 %初始种群为空 startPop=[]; end if isempty(startPop) %随机生成初始种群 startPop=initializega(80,bounds,eevalFN,eevalOps,opts(1:2)); end if opts(2)==0 %二进制编码 bits=calcbits(bounds,opts(1)); end

xOverFNs=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 collectTrace traceInfo(gen,1)=gen; %当前代 traceInfo(gen,2)=startPop(bindx,xZomeLength); %最优适应度 traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %平均适应度 traceInfo(gen,4)=std(startPop(:,xZomeLength)); end

if ( (abs(beval - oeval)>epsilon) | (gen==1)) if display fprintf(1,'\n%d %f\n',gen,beval); end if floatGA bPop(bFoundIn,:)=[gen startPop(bindx,:)]; else bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... startPop(bindx,xZomeLength)]; end bFoundIn=bFoundIn+1; oeval=beval; else if display fprintf(1,'%d ',gen); end end

endPop = feeval(selectFN,startPop,[gen selectOps]); %选择操作 if floatGA for 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); else eeval(e1str); end if 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); else eeval(e2str); end endPop(a,:)=c1; endPop(b,:)=c2; end end

for 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); else eeval(e1str); end endPop(a,:)=c1; end end

else %遗传操作的统计模型 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)); end cp=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,:)]); end end for i=1:numMuts mN=deblank(mutFNs(i,:)); for j=1:popSize endPop(j,:) = feeval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]); eeval(e1str); end end end

相关文档
最新文档