完整的遗传算法函数Matlab程序
完整的遗传算法函数Matlab程序
完整的遗传算法函数Matlab程序遗传算法是一种模拟自然进化过程的算法,通过遗传代数操作来搜索最优解。
它是一种优化算法,可以用于解决复杂问题,例如函数优化、组合优化、机器学习等。
在Matlab 中,遗传算法可以通过使用内置函数进行实现,也可以编写自己的遗传算法函数。
以下是一个完整的遗传算法函数Matlab程序的示例:function [x_best, f_best] = GA(fit_func, nvars)% fit_func: 适应度函数句柄% nvars: 变量个数% 遗传算法参数设置pop_size = 100; % 种群大小prob_crossover = 0.8; % 交叉概率prob_mutation = 0.02; % 变异概率max_gen = 1000; % 最大迭代次数% 初始化种群pop = rand(pop_size, nvars);for i = 1:max_gen% 计算适应度for j = 1:pop_sizefitness(j) = feval(fit_func, pop(j,:));end% 找到最优个体[f_best, best_idx] = max(fitness);x_best = pop(best_idx,:);% 交叉操作for j = 1:2:pop_sizeif rand < prob_crossover% 随机选择父代idx_parent1 = randi(pop_size);idx_parent2 = randi(pop_size);parent1 = pop(idx_parent1,:);parent2 = pop(idx_parent2,:);% 交叉idx_crossover = randi(nvars-1);child1 = [parent1(1:idx_crossover) parent2(idx_crossover+1:end)];child2 = [parent2(1:idx_crossover) parent1(idx_crossover+1:end)];% 更新种群pop(j,:) = child1;pop(j+1,:) = child2;endend% 变异操作for j = 1:pop_sizeif rand < prob_mutation% 随机选择变异个体idx_mutation = randi(nvars);pop(j,idx_mutation) = rand;endendendend在上述程序中,遗传算法的参数通过设定变量的值进行设置,包括种群大小、交叉概率、变异概率和最大迭代次数等。
遗传算法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实现的基本遗传算法算例。
本例用于解决简单的优化问题:寻找函数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程序
N2=initialize(); N3=initialize(); N4=initialize(); total=1; Num=0; MaN1=0; MaN2=0; flag=0; continue; else break; end end temp1=cal(N1,n1); temp2=cal(N2,n2); temp3=cal(N3,n3); temp4=cal(N4,n4); M=[temp1;temp2;temp3;temp4]; N1=M(1,:); N2=M(2,:); N3=M(3,:); N4=M(4,:); %交叉-crossover while 1 p=floor(1000*rand); if p>1 break; else continue; end end k=mod(p,3); switch k case 0 [N1,N2,N3,N4,ps]=crossover(N1,N2,N3,N4); case 1 [N1,N3,N2,N4,ps]=crossover(N1,N3,N2,N4); case 2 [N1,N4,N2,N3,ps]=crossover(N1,N4,N2,N3); end %变异-mutation U=[N1,N2,N3,N4]; pos=mod(floor(1000*rand),20)+1; if U(1 U(1,pos)=0; end N1=U(1,1:5); N2=U(1,6:10); N3=U(1,11:15); N4=U(1,16:20); %遗传算法结束条件:连续 10 代最大值均保持一致 if Num==10 disp('进化代数:') total-10 disp('现在的种群:') N1 N2 N3 N4 disp('最大值:') MaN1 break; end flag=mod(flag+1,2); total=total+1; end 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求函数极大值一、题目:寻找f(x)=x2,,当x在0~31区间的最大值。
二、源程序:%遗传算法求解函数最大值%本程序用到了英国谢菲尔德大学(Sheffield)开发的工具箱GATBX,该工具箱比matlab自带的GATOOL使用更加灵活,但在编写程序方面稍微复杂一些Close all;Clear all;figure(1);fplot('variable*variable',[0,31]); %画出函数曲线%以下定义遗传算法参数GTSM=40; %定义个体数目ZDYCDS=20; %定义最大遗传代数EJZWS=5; %定义变量的二进制位数DG=0.9; %定义代沟trace=zeros(2, ZDYCDS); %最优结果的初始值FieldD=[5;-1;2;1;0;1;1]; %定义区域描述器的各个参数%以下为遗传算法基本操作部分,包括创建初始种群、复制、交叉和变异Chrom=crtbp(GTSM, EJZWS); %创建初始种群,即生成给定规模的二进制种群和结构gen=0; %定义代数计数器初始值variable=bs2rv(Chrom, FieldD); %对生成的初始种群进行十进制转换ObjV=variable*variable; %计算目标函数值f(x)=x2 while gen<ZDYCDS %进行循环控制,当当前代数小于定义的最大遗传代数时,继续循环,直至代数等于最大遗传代数FitnV=ranking(-ObjV); %分配适应度值SelCh=select('sus', Chrom, FitnV, DG); %选择,即对个体按照他们的适配值进行复制SelCh=recombin('xovsp', SelCh, 0.7); %交叉,即首先将复制产生的匹配池中的成员随机两两匹配,再进行交叉繁殖SelCh=mut(SelCh); %变异,以一个很小的概率随机地改变一个个体串位的值variable=bs2rv(SelCh, FieldD); %子代个体的十进制转换ObjVSel=variable*variable; %计算子代的目标函数值[Chrom ObjV]=reins(Chrom, SelCh, 1, 1, ObjV, ObjVSel);%再插入子代的新种群,其中Chrom为包含当前种群个体的矩阵,SelCh为包好当前种群后代的矩阵variable=bs2rv(Chrom, FieldD); %十进制转换gen=gen+1; %代数计数器增加%输出最优解及其序号,并在目标函数图像中标出,Y为最优解, I为种群的%序号[Y, I]=max(ObjV);hold on; %求出其最大目标函数值plot(variable(I), Y, 'bo');trace(1, gen)=max(ObjV); %遗传算法性能跟踪trace(2, gen)=sum(ObjV)/length(ObjV);end%以下为结果显示部分,通过上面计算出的数值进行绘图variable=bs2rv(Chrom, FieldD); %最优个体进行十进制转换hold on, grid;plot(variable,ObjV,'b*'); %将结果画出三、运行结果:由图可见该函数为单调递增函数,即当X=31时,该取得最大值f(x)max =961。
遗传算法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函数的源程序
end
end
end
%确定下一代父代个体
%确定实际子代个体数值
chi_fact=zeros(x_num,chi_num*3);
for j=1:x_num
chi_fact(j,:)=x_range(j,1)+(x_range(j,2)-x_range(j,1))*chi(j,:);
par=chi(:,chi_ada_no(1:par_num));
end ');
par_fac_exc(:,1)=x_range(:,1)+(x_range(:,2)-x_range(:,1)).*par(:,1);%父代个体最优函数值
par_fun_exc=fun(par_fac_exc);
%输出父代样本实际值
par_fact=zeros(x_num,par_num);
for i=1:x_num
par_fact(i,:)=x_range(i,1)+(x_range(i,2)-x_range(i,1))*par(i,:);
if chi_ran(3)<0.5
chi(j,i)=chi_ran(1)*par(j,chi_sel1)+(1-chi_ran(1))*par(j,chi_sel2);
else
chi(j,i)=chi_ran(2)*par(j,chi_sel1)+(1-chi_ran(2))*par(j,chi_sel2);
%例子2:
%fun=@(x) sum(x.*x-cos(18*x))+5;
%x_range=[-1,1;-1,1;-1,1;-1,1;-1,1];
遗传算法的Matlab7.0程序实现
function pop=encoding(popsize,stringlength,dimension)pop=round(rand(popsize.dimension*string—length+1));function new—pop=cross~over(pop,popsize,stringlength,dimension)match=round(rand(1,popsize)*(popsize一1))+1;for i=1:popsize .["childl,child2]=cross—running(pop (i,:),pop(match(i),:),stringlength,di—mension);new—pop(2*i——1:2*i,:)=[-childl}child2];endfunction[childl,child2]=eross—running(par—entl,parent2,stringlength,dimension)cpoint=round((stringlength--1)*rand(1,di—…mension))+l;for j=1:dimensionchildl((j一1)*stringlength+1:j*string—length)=[parentl((j一1)*stringlength+1:(j一1)*stringlength+cpoint(j))parent2((j一1)* stringlength+cpoint(j)+1:j*stringlength)];child2((j一1)*stringlength+1:j-'k string—length)=[parent2((j一1)*stringlength+1:(j一1)*stringlength+cpoint(j))parentl((j一1)-'k stringlength+cpoint(j)+1:j*stringlength)];endfunction new—pop 2 mutation(new—pop,string—length,dimension,pm)new—popsize=size(new—pop,1);for i一1:new—popsizeif rand<pmmpoint--round(rand(1.dimension)*(string—length一1))+1;for j=1:dimensionnew—pop(i,(j一1)-'k stringlength+mpoint (j))一1一new—pop(i,(j一1)*stringlength+ mpoint(j));endendendfunction pop—decoding(pop,stringlength,dimen—sion,X—bound)popsize=size(pop,1);temp--2.‘(stringlength一1:一1:0)/(2‘string—length--1);for i一1:dimensionbound(i)=X—bound(i,2)一x—bound(i,1);endfor i=1:popsizeforj=1:dimensionm(:,j)一pop(i,stringlength*(j一1)+1:stringlength*j);endx2temp*m ox—x.*bound+x—bound(:,1)’;’pop(i,dimension*stringlength+1)一funname (x);Endfunction selected=selection(pop,popsize,string—length,dimension)popsize—new2size(pop,1);r=rand(1,popsize):fitness=pop(:,dimension*stringlength+1);fitness=fitness/sum(fitness);fitness=cumsum(fitness);for i=l:popsizef0√~1:popsize~newi j--a.“if,(i)三:fit:00110110,则解码后selected(i':) ,,‘。
完整的遗传算法函数Matlab程序【精品毕业设计】(完整版)
完整的遗传算法函数Matlab程序function [x,endPop,bPop,traceInfo] = ga(bounds,eevalFN,eevalOps,startPop,opts,... termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)n=nargin;if n<2 | n==6 | n==10 | n==12disp('Insufficient arguements')endif n<3 %Default eevalation opts.eevalOps=[];endif n<5opts = [1e-6 1 0];endif isempty(opts)opts = [1e-6 1 0];endif any(eevalFN<48) %Not using a .m fileif opts(2)==1 %Float gae1str=['x=c1; c1(xZomeLength)=', eevalFN ';'];e2str=['x=c2; c2(xZomeLength)=', eevalFN ';'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...eevalFN ';'];endelse %Are using a .m fileif opts(2)==1 %Float gae1str=['[c1 c1(xZomeLength)]=' eevalFN '(c1,[gen eevalOps]);'];e2str=['[c2 c2(xZomeLength)]=' eevalFN '(c2,[gen eevalOps]);'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' eevalFN ...'(x,[gen eevalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];endendif n<6 %Default termination informationtermOps=[100];termFN='maxGenTerm';endif n<12 %Default muatation informationif opts(2)==1 %Float GAmutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];else %Binary GAmutFNs=['binaryMutation'];mutOps=[0.05];endendif n<10 %默认的交叉信息if opts(2)==1 %浮点编码xOverFNs=['arithXover heuristicXover simpleXover'];xOverOps=[2 0;2 3;2 0];else %Binary GAxOverFNs=['simpleXover'];xOverOps=[0.6];endendif n<9 %Default select opts only i.e. roullete wheel.selectOps=[];endif n<8 %Default select infoselectFN=['normGeomSelect'];selectOps=[0.08];endif n<6 %默认的算法终止准则termOps=[100];termFN='maxGenTerm';endif n<4 %初始种群为空startPop=[];endif isempty(startPop) %随机生成初始种群startPop=initializega(80,bounds,eevalFN,eevalOps,opts(1:2));endif opts(2)==0 %二进制编码bits=calcbits(bounds,opts(1));endxOverFNs=parse(xOverFNs);mutFNs=parse(mutFNs);xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness numVar = xZomeLength-1; %变量数目popSize = size(startPop,1); %种群中个体数目endPop = zeros(popSize,xZomeLength); %次种群矩阵c1 = zeros(1,xZomeLength); %个体c2 = zeros(1,xZomeLength); %个体numXOvers = size(xOverFNs,1); %交叉操作次数numMuts = size(mutFNs,1); %变异操作次数epsilon = opts(1); %适应度门限值oeval = max(startPop(:,xZomeLength)); %初始种群中的最优值bFoundIn = 1;done = 0;gen = 1;collectTrace = (nargout>3);floatGA = opts(2)==1;display = opts(3);while(~done)[beval,bindx] = max(startPop(:,xZomeLength)); %当前种群的最优值best = startPop(bindx,:);if collectTracetraceInfo(gen,1)=gen; %当前代traceInfo(gen,2)=startPop(bindx,xZomeLength); %最优适应度traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %平均适应度traceInfo(gen,4)=std(startPop(:,xZomeLength));endif ( (abs(beval - oeval)>epsilon) | (gen==1))if displayfprintf(1,'\n%d %f\n',gen,beval);endif floatGAbPop(bFoundIn,:)=[gen startPop(bindx,:)];elsebPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... startPop(bindx,xZomeLength)];endbFoundIn=bFoundIn+1;oeval=beval;elseif displayfprintf(1,'%d ',gen);endendendPop = feeval(selectFN,startPop,[gen selectOps]); %选择操作if floatGAfor i=1:numXOvers,for j=1:xOverOps(i,1),a = round(rand*(popSize-1)+1); %一个父代个体b = round(rand*(popSize-1)+1); %另一个父代个体xN=deblank(xOverFNs(i,:)); %交叉函数[c1 c2] = feeval(xN,endPop(a,:),endPop(b,:),bounds,[gen… xOverOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseif c1(1:numVar)==endPop(b,(1:numVar))c1(xZomeLength)=endPop(b,xZomeLength);elseeeval(e1str);endif c2(1:numVar)==endPop(a,(1:numVar))c2(xZomeLength)=endPop(a,xZomeLength);elseif c2(1:numVar)==endPop(b,(1:numVar))c2(xZomeLength)=endPop(b,xZomeLength);elseeeval(e2str);endendPop(a,:)=c1;endPop(b,:)=c2;endendfor i=1:numMuts,for j=1:mutOps(i,1),a = round(rand*(popSize-1)+1);c1 = feeval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseeeval(e1str);endendPop(a,:)=c1;endendelse %遗传操作的统计模型for i=1:numXOvers,xN=deblank(xOverFNs(i,:));cp=find(rand(popSize,1)if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); endcp=reshape(cp,size(cp,1)/2,2);for j=1:size(cp,1)a=cp(j,1); b=cp(j,2);[endPop(a,:) endPop(b,:)] = feeval(xN,endPop(a,:),endPop(b,:), bounds,[gen xOverOps(i,:)]); endendfor i=1:numMutsmN=deblank(mutFNs(i,:));for j=1:popSizeendPop(j,:) = feeval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);eeval(e1str);endendend。
遗传算法matlab代码
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复制代码% 遗传算法参数设置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实现源程序
附页:一.遗传算法源程序: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;。
matlab遗传算法程序
% Optimizing a function using Simple Genetic Algorithm with elitist% preserved%bval=father,newbval=child,bvalxx=fatherbest,q=Nsclc;clear all;format long;%设定数据显示格式%初始化参数T=100;%仿真代数%N=80;% 群体规模N=50;nc=44;nm=15;nb=4;%较差变异个数%pm=0.05;pc=0.8;%交叉变异概率%umax=2.048;umin=-2.048;%参数取值范围xmax=10;xmin=-10;L=16;%单个参数字串长度,总编码长度2Lfather=round(rand(N,2*L));%初始种群,,取整为最近整数0或1,生成N*2L矩阵的随机数bestvalue=-inf;%最优适应度初值,负无穷大%迭代开始for k=1:T%解码,计算适应度for i=1:Ny1=0;y2=0;for j=1:1:Ly1=y1+father(i,L-j+1)*2^(j-1);endx1=(xmax-xmin)*y1/(2^L-1)+xmin;for j=1:1:Ly2=y2+father(i,2*L-j+1)*2^(j-1);endx2=(xmax-xmin)*y2/(2^L-1)+xmin;%obj(i)=100*(x1*x1-x2).^2+(1-x1).^2; %目标函数obj(i)=sin(x1)/x1*sin(x2)/x2;%obj(i)=0.9*exp(-((x1+5).^2+(x2+5).^2)/10)+0.99996*exp(-((x1-5).^2+(x2-5).^2)/20); %obj(i)=0.99996*exp(-((x1-5).^2+(x2-5).^2)/20);xx(i,:)=[x1,x2];%矩阵第i行赋值为x1,x2endfunc=obj;%目标函数转换为适应度函数p=func./sum(func);Ns=cumsum(p);%累加[fmax,indmax]=max(func);%求当代最佳个体,最大值返回给fmax,其索引给indmaxif fmax>=bestvaluebestvalue=fmax;%到目前为止最优适应度值fatherbest=father(indmax,:);%到目前为止最佳位串optimal=xx(indmax,:);%到目前为止最优参数endbestfit(k)=bestvalue; % 存储每代的最优适应度%%%%遗传操作开始% 轮盘赌选择for i=1:N-1r=rand;for j=1:Nif r<=Ns(j)child(i,:)=father(j,:);break;endendendchild(N,:)=fatherbest;%最优保留father=child;%单点交叉for i=1:2:(N-1)cc=rand;pc=nc/N;if cc<pcpoint=L/2;tmp1=father(i,:);father(i,point+1:L)=father(i+1,point+1:L);father(i+1,point+1:L)=tmp1(1,point+1:L);father(i,point+L+1:2*L)=father(i+1,point+L+1:2*L); father(i+1,point+L+1:2*L)=tmp1(1,point+L+1:2*L); endendfather(N,:)=fatherbest;%最优保留%位点变异pm=nb*nm/(2*N);tmp2=rand(N,2*L)<pm;%N行tmp2(N,:)=zeros(1,2*L);%最后一行不变异,强制赋0father(tmp2)=1-father(tmp2);end% 输出plot(bestfit,'-o');% 绘制最优适应度进化曲线xlabel('代数T');ylabel('最优值');title('nc=44 nm=15');grid on;bestvalue %输出最优适应度值optimal %输出最优参数她含着笑,切着冰屑悉索的萝卜,她含着笑,用手掏着猪吃的麦糟,她含着笑,扇着炖肉的炉子的火,她含着笑,背了团箕到广场上去晒好那些大豆和小麦,大堰河,为了生活,在她流尽了她的乳液之后,她就用抱过我的两臂,劳动了。
遗传算法matlab实现
MATLAB程序实现初始化:%初始化种群%pop_size: 种群大小%chromo_size: 染色体长度functioninitilize(pop_size, chromo_size)global pop;fori=1:pop_sizefor j=1:chromo_sizepop(i,j) = round(rand);endendcleari;clear j;计算适应度:(该函数应该根据具体问题进行修改,这里优化的函数是前述的一维函数)%计算种群个体适应度,对不同的优化目标,此处需要改写%pop_size: 种群大小%chromo_size: 染色体长度function fitness(pop_size, chromo_size)globalfitness_value;global pop;global G;fori=1:pop_sizefitness_value(i) = 0.;endfori=1:pop_sizefor j=1:chromo_sizeif pop(i,j) == 1fitness_value(i) = fitness_value(i)+2^(j-1);endendfitness_value(i) = -1+fitness_value(i)*(3.-(-1.))/(2^chromo_size-1);fitness_value(i) = -(fitness_value(i)-1).^2+4;endcleari;clear j;对个体按照适应度大小进行排序:%对个体按适应度大小进行排序,并且保存最佳个体%pop_size: 种群大小%chromo_size: 染色体长度function rank(pop_size, chromo_size)globalfitness_value;globalfitness_table;globalfitness_avg;globalbest_fitness;globalbest_individual;globalbest_generation;global pop;global G;fori=1:pop_sizefitness_table(i) = 0.;endmin = 1;temp = 1;temp1(chromo_size)=0;fori=1:pop_sizemin = i;for j = i+1:pop_sizeiffitness_value(j)<fitness_value(min);min = j;endendif min~=itemp = fitness_value(i);fitness_value(i) = fitness_value(min);fitness_value(min) = temp;for k = 1:chromo_sizetemp1(k) = pop(i,k);pop(i,k) = pop(min,k);pop(min,k) = temp1(k);endendendfori=1:pop_sizeifi==1fitness_table(i) = fitness_table(i) + fitness_value(i); elsefitness_table(i) = fitness_table(i-1) + fitness_value(i); endendfitness_tablefitness_avg(G) = fitness_table(pop_size)/pop_size;iffitness_value(pop_size) >best_fitnessbest_fitness = fitness_value(pop_size);best_generation = G;for j=1:chromo_sizebest_individual(j) = pop(pop_size,j);endendcleari;clear j;clear k;clear min;clear temp;clear temp1;选择操作:%轮盘赌选择操作%pop_size: 种群大小%chromo_size: 染色体长度%cross_rate: 是否精英选择function selection(pop_size, chromo_size, elitism) global pop;globalfitness_table;fori=1:pop_sizer = rand * fitness_table(pop_size);first = 1;last = pop_size;mid = round((last+first)/2);idx = -1;while (first <= last) && (idx == -1)if r >fitness_table(mid)first = mid;elseif r <fitness_table(mid) last = mid;elseidx = mid;break;endmid = round((last+first)/2); if (last - first) == 1idx = last;break;endendfor j=1:chromo_sizepop_new(i,j)=pop(idx,j); endendif elitismp = pop_size-1;elsep = pop_size;endfori=1:pfor j=1:chromo_sizepop(i,j) = pop_new(i,j); endendcleari;clear j;clearpop_new;clear first;clear last;clearidx;clear mid;交叉操作:%单点交叉操作%pop_size: 种群大小%chromo_size: 染色体长度%cross_rate: 交叉概率function crossover(pop_size, chromo_size, cross_rate) global pop;fori=1:2:pop_sizeif(rand <cross_rate)cross_pos = round(rand * chromo_size);if or (cross_pos == 0, cross_pos == 1)continue;endfor j=cross_pos:chromo_sizetemp = pop(i,j);pop(i,j) = pop(i+1,j);pop(i+1,j) = temp;endendendcleari;clear j;clear temp;clearcross_pos;变异操作:%单点变异操作%pop_size: 种群大小%chromo_size: 染色体长度%cross_rate: 变异概率function mutation(pop_size, chromo_size, mutate_rate) global pop;fori=1:pop_sizeif rand <mutate_ratemutate_pos = round(rand*chromo_size);ifmutate_pos == 0continue;endpop(i,mutate_pos) = 1 - pop(i, mutate_pos);endendcleari;clearmutate_pos;打印算法迭代过程:%打印算法迭代过程%generation_size: 迭代次数functionplotGA(generation_size)globalfitness_avg;x = 1:1:generation_size;y = fitness_avg;plot(x,y)算法主函数:%遗传算法主函数%pop_size: 输入种群大小%chromo_size: 输入染色体长度%generation_size: 输入迭代次数%cross_rate: 输入交叉概率%cross_rate: 输入变异概率%elitism: 输入是否精英选择%m: 输出最佳个体%n: 输出最佳适应度%p: 输出最佳个体出现代%q: 输出最佳个体自变量值function [m,n,p,q] = GeneticAlgorithm(pop_size, chromo_size, generation_size, cross_rate, mutate_rate, elitism)global G ; %当前代globalfitness_value;%当前代适应度矩阵globalbest_fitness;%历代最佳适应值globalfitness_avg;%历代平均适应值矩阵globalbest_individual;%历代最佳个体globalbest_generation;%最佳个体出现代fitness_avg = zeros(generation_size,1);disp"hhee"fitness_value(pop_size) = 0.;best_fitness = 0.;best_generation = 0;initilize(pop_size, chromo_size);%初始化for G=1:generation_sizefitness(pop_size, chromo_size); %计算适应度rank(pop_size, chromo_size); %对个体按适应度大小进行排序selection(pop_size, chromo_size, elitism);%选择操作crossover(pop_size, chromo_size, cross_rate);%交叉操作mutation(pop_size, chromo_size, mutate_rate);%变异操作endplotGA(generation_size);%打印算法迭代过程m = best_individual;%获得最佳个体n = best_fitness;%获得最佳适应度p = best_generation;%获得最佳个体出现代%获得最佳个体变量值,对不同的优化目标,此处需要改写q = 0.;for j=1:chromo_sizeifbest_individual(j) == 1q = q+2^(j-1);endendq = -1+q*(3.-(-1.))/(2^chromo_size-1);cleari;clear j;2. 案例研究对上一节中的函数进行优化,设置遗传算法相关参数,程序如下functionrun_ga()elitism = true;%选择精英操作pop_size = 20;%种群大小chromo_size = 16;%染色体大小generation_size = 200;%迭代次数cross_rate = 0.6;%交叉概率mutate_rate = 0.01;%变异概率[m,n,p,q] = GeneticAlgorithm(pop_size, chromo_size, generation_size, cross_rate, mutate_rate,elitism);disp"最优个体"mdisp"最优适应度"ndisp"最优个体对应自变量值"qdisp"得到最优结果的代数" pclear;结果如下:"最优个体"m =1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 "最优适应度"n =4.0000"最优个体对应自变量值" q =1.0000"得到最优结果的代数"p =74此结果非常准确。
遗传算法的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函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。
(实例)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)注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法 matlab程序
遗传算法 matlab程序遗传算法(Genetic Algorithm)是一种模拟生物进化过程的优化算法,主要用于解决复杂的优化问题。
在这篇文章中,我们将介绍如何使用MATLAB编写遗传算法的程序,并展示其在实际问题中的应用。
我们需要明确遗传算法的基本原理。
遗传算法通过模拟自然选择、交叉和变异等基因操作,以产生新的解,并通过适应度函数评估每个解的优劣。
通过不断迭代,遗传算法逐渐找到最优解。
在MATLAB中,我们可以使用遗传算法工具箱来实现遗传算法的程序。
首先,我们需要定义问题的目标函数和约束条件。
目标函数是我们希望优化的函数,而约束条件则是问题的限制条件。
在定义完目标函数和约束条件后,我们可以使用遗传算法工具箱中的函数来构建遗传算法的程序。
在遗传算法中,每个解都可以看作一个个体,而每个个体都由一串基因表示。
在MATLAB中,我们可以用一个二进制字符串来表示一个个体。
例如,一个8位的二进制字符串可以表示一个整数值或一个实数值。
在遗传算法中,这个二进制字符串称为染色体。
在遗传算法的程序中,我们需要定义染色体的编码方式、交叉方式、变异方式等。
编码方式决定了染色体的表示方法,常见的编码方式有二进制编码和实数编码。
交叉方式决定了如何将两个染色体进行交叉操作,常见的交叉方式有单点交叉和多点交叉。
变异方式决定了如何对染色体进行变异操作,常见的变异方式有位变异和基因变异。
在编写遗传算法的程序时,我们需要定义适应度函数来评估每个个体的优劣。
适应度函数的值越大,说明个体的优势越大。
根据适应度函数的值,我们可以选择一些优秀的个体进行交叉和变异操作,以产生新的解。
在MATLAB中,我们可以使用遗传算法工具箱中的函数来进行遗传算法的迭代过程。
通过设置迭代次数和种群大小等参数,我们可以控制算法的运行过程。
在每次迭代中,遗传算法会根据适应度函数的值选择一些优秀的个体,进行交叉和变异操作,以产生新的解。
经过多次迭代后,遗传算法会逐渐找到最优解。
遗传算法matlab程序
function result=sga(n,a,b,pc,pm,e)%n—群体规模;a—搜索上限;b—搜索下限;%pc—交叉概率;pm—变异概率;e—计算精度;for i=1:50 %求出群体的码串最小长度mif (b-a)/e>2^(i)m=i+1elsei=i+1endendpopusize=n;chromlength=m;j=1;popu=round(rand(popusize,chromlength)); %随机产生n行m列的初始群体while j<=30 %设置程序中止条件py=chromlength;for i=1:py %进行二进制转换成十进制的解码操作popu1(:,i)=2.^(py-1).*popu(:,i);Py=py-1;endpopu2=sum(popu1,2);x=a+popu2*(b-a)/(2^l-1);yvalue=2*x.^2.*cos(3*x)+x.*sin(5*x)+8; %计算群体中每个个体的适应度for i=1:popusize %执行复制操作if yvalue(i)<0yvalue(i)=0;endendfitscore=yvalue/sum(yvalue);%个体被选中的概率fitscore=cumsum(fitscore);% 群体中个体的累积概率wh=sort(rand(popusize,1));% 从小到大排列wheel=1;fitone=1;while wheel<=popusize %执行转盘式选择操作if wh(wheel)<fitscore(fitone)newpopu(wheel,:)=popu(fitone,:);wheel=wheel+1;elsefitone=fitone+1;endendpopu=newpopu;for i=1:2:popusize-1 %执行交叉操作if rand<pccpoint=round(rand*chromlength);newpopu(i,:)=[popu(i,1:cpoint) popu(i+1,cpoint+1:chromlength)]; newpopu(i+1,:)=[popu(i+1,1:cpoint) popu(i,cpoint+1:chromlength)]; elsenewpopu(i,:)=popu(i,:);newpopu(i+1,:)=popu(i+1,:);endendpopu=newpopu;for i=1:popusize %执行变异操作if rand<pmmpoint=round(rand*chromlength);if mpoint<=0;mpoint=1;endnewpopu(i,:)=popu(i,:);if newpopu(i,mpoint)==0newpopu(i,mpoint)=1;elsenewpopu(i,mpoint)=0;endelsenewpopu(i,:)=popu(i,:);endend[y(j) index]=max(yvalue); %求出群体中适应值最大的个体及其适应值bestindividual=newpopu(index,:);py=chromlength;for i=1:py %进行二进制转换成十进制的解码操作bestindividual(1,i)=2.^(py-1).*bestindividual(:,i);py=py-1;endr(j)=a+sum(bestindividual,2)*(b-a)/(2^l-1);popu=newpopu;j=j+1;% 重新赋值并返回endfplot('2*x.^2.*cos(3*x)+x.*sin(5*x)+8';[a b]);hold on;plot(r,y,'r*');hold offxlabel('x');ylabel('y')[y index]=max(y); %计算最大值及其位置result=[r(index) y];% 返回优化结果她含着笑,切着冰屑悉索的萝卜,她含着笑,用手掏着猪吃的麦糟,她含着笑,扇着炖肉的炉子的火,她含着笑,背了团箕到广场上去晒好那些大豆和小麦,大堰河,为了生活,在她流尽了她的乳液之后,她就用抱过我的两臂,劳动了。
遗传算法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、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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==12disp('Insufficient arguements')endif n<3 %Default eevalation opts.eevalOps=[];endif n<5opts = [1e-6 1 0];endif isempty(opts)opts = [1e-6 1 0];endif any(eevalFN<48) %Not using a .m fileif opts(2)==1 %Float gae1str=['x=c1; c1(xZomeLength)=', eevalFN ';'];e2str=['x=c2; c2(xZomeLength)=', eevalFN ';'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...eevalFN ';'];endelse %Are using a .m fileif opts(2)==1 %Float gae1str=['[c1 c1(xZomeLength)]=' eevalFN '(c1,[gen eevalOps]);'];e2str=['[c2 c2(xZomeLength)]=' eevalFN '(c2,[gen eevalOps]);'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' eevalFN ...'(x,[gen eevalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];endendif n<6 %Default termination informationtermOps=[100];termFN='maxGenTerm';endif n<12 %Default muatation informationif opts(2)==1 %Float GAmutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];else %Binary GAmutFNs=['binaryMutation'];mutOps=[0.05];endendif n<10 %默认的交叉信息if opts(2)==1 %浮点编码xOverFNs=['arithXover heuristicXover simpleXover'];xOverOps=[2 0;2 3;2 0];else %Binary GAxOverFNs=['simpleXover'];xOverOps=[0.6];endendif n<9 %Default select opts only i.e. roullete wheel.selectOps=[];endif n<8 %Default select infoselectFN=['normGeomSelect'];selectOps=[0.08];endif n<6 %默认的算法终止准则termOps=[100];termFN='maxGenTerm';endif n<4 %初始种群为空startPop=[];endif isempty(startPop) %随机生成初始种群startPop=initializega(80,bounds,eevalFN,eevalOps,opts(1:2));endif opts(2)==0 %二进制编码bits=calcbits(bounds,opts(1));endxOverFNs=parse(xOverFNs);mutFNs=parse(mutFNs);xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness numVar = xZomeLength-1; %变量数目popSize = size(startPop,1); %种群中个体数目endPop = zeros(popSize,xZomeLength); %次种群矩阵c1 = zeros(1,xZomeLength); %个体c2 = zeros(1,xZomeLength); %个体numXOvers = size(xOverFNs,1); %交叉操作次数numMuts = size(mutFNs,1); %变异操作次数epsilon = opts(1); %适应度门限值oeval = max(startPop(:,xZomeLength)); %初始种群中的最优值bFoundIn = 1;done = 0;gen = 1;collectTrace = (nargout>3);floatGA = opts(2)==1;display = opts(3);while(~done)[beval,bindx] = max(startPop(:,xZomeLength)); %当前种群的最优值best = startPop(bindx,:);if collectTracetraceInfo(gen,1)=gen; %当前代traceInfo(gen,2)=startPop(bindx,xZomeLength); %最优适应度traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %平均适应度traceInfo(gen,4)=std(startPop(:,xZomeLength));endif ( (abs(beval - oeval)>epsilon) | (gen==1))if displayfprintf(1,'\n%d %f\n',gen,beval);endif floatGAbPop(bFoundIn,:)=[gen startPop(bindx,:)];elsebPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... startPop(bindx,xZomeLength)];endbFoundIn=bFoundIn+1;oeval=beval;elseif displayfprintf(1,'%d ',gen);endendendPop = feeval(selectFN,startPop,[gen selectOps]); %选择操作if floatGAfor i=1:numXOvers,for j=1:xOverOps(i,1),a = round(rand*(popSize-1)+1); %一个父代个体b = round(rand*(popSize-1)+1); %另一个父代个体xN=deblank(xOverFNs(i,:)); %交叉函数[c1 c2] = feeval(xN,endPop(a,:),endPop(b,:),bounds,[gen… xOverOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseif c1(1:numVar)==endPop(b,(1:numVar))c1(xZomeLength)=endPop(b,xZomeLength);elseeeval(e1str);endif c2(1:numVar)==endPop(a,(1:numVar))c2(xZomeLength)=endPop(a,xZomeLength);elseif c2(1:numVar)==endPop(b,(1:numVar))c2(xZomeLength)=endPop(b,xZomeLength);elseeeval(e2str);endendPop(a,:)=c1;endPop(b,:)=c2;endendfor i=1:numMuts,for j=1:mutOps(i,1),a = round(rand*(popSize-1)+1);c1 = feeval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseeeval(e1str);endendPop(a,:)=c1;endendelse %遗传操作的统计模型for i=1:numXOvers,xN=deblank(xOverFNs(i,:));cp=find(rand(popSize,1)if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); endcp=reshape(cp,size(cp,1)/2,2);for j=1:size(cp,1)a=cp(j,1); b=cp(j,2);[endPop(a,:) endPop(b,:)] = feeval(xN,endPop(a,:),endPop(b,:), bounds,[gen xOverOps(i,:)]); endendfor i=1:numMutsmN=deblank(mutFNs(i,:));for j=1:popSizeendPop(j,:) = feeval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);eeval(e1str);endendend。