本算法是遗传算法的示例

源代码在线查看: 遗传算法matlab代码.txt

软件大小: 2 K
上传用户: stone825
关键词: 算法
下载地址: 免注册下载 普通下载 VIP

相关代码

				遗传算法matlab代码
				function youhuafun
				
				D=code;
				N=50;         % Tunable
				maxgen=50;     % Tunable
				crossrate=0.5; %Tunable
				muterate=0.08; %Tunable
				generation=1;  
				num = length(D);
				fatherrand=randint(num,N,3);
				score = zeros(maxgen,N);
				while generation				   ind=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;
				%     end
				   fatherrand=[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;
				       end
				       childind(k)=scoreind(logical(difind));
				   end
				   fatherrand=fatherrand(:,childind);    
				   generation=generation+1;
				end
				% score
				maxV=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 D
				
				function D=code
				load youhua.mat
				% properties F2 and F3
				F1=A(:,1);
				F2=A(:,2);
				F3=A(:,3);
				if (max(F2)>1450)||(min(F2)				   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:1
				   index=find(F2				   F4(index)=ite;
				end
				D=[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:N
				   FF4k=FF4rnd(:,k);
				   for ite=1:11
				       F0index=find(FF4k==ite);
				       if ~isempty(F0index)
				           tmpMat=F3(F0index);
				           tmpSco=sum(tmpMat);
				           ScoreBin(ite)=mod(tmpSco,300);
				       end
				   end
				   Scorek(k)=sum(ScoreBin);
				end
				ScoreN=ScoreN-Scorek;			

相关资源