⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ga.m

📁 一个用MATLAB编写的优化控制工具箱
💻 M
📖 第 1 页 / 共 3 页
字号:
         member_count=member_count+1;         total=total+fitness(member_count);      end      % Next, make the parent chromosome    parent_chrom(:,pop_member)=pop(:,member_count);	end   end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Reproduce section (i.e., make off-spring - "children")%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% In the approach below each individual gets to mate and% they randomly pick someone else (not themselves) in the % mating pool to mate with.  Resulting children are % composed of a combination of genetic material of their% parents.  If elitism is on, when the elite member gets% a chance to mate they do not; they are simply copied% over to the next generation.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%for parent_number1 = 1:POP_SIZE,    % Crossover (parent_number1 is the 									% individual who gets to mate	if ELITISM ==1 & parent_number1==bestmember % If elitism on, and 											 % have the elite member		child(:,parent_number1)=parent_chrom(:,parent_number1);	else	   parent_number2=parent_number1;  % Initialize who the mate is	   while parent_number2 == parent_number1   % Iterate until find 		                                        % a mate other than												% yourself         parent_number2 = rand*POP_SIZE; % Choose parent number 2		 								 % randomly (a random mate)         parent_number2 = parent_number2-rem(parent_number2,1)+1;     	   end    if CROSS_PROB > rand           % If true then crossover occurs         site = rand*CHROM_LENGTH;   % Choose site for crossover         site = site-rem(site,1)+1;  % and make it a valid integer          							 % number for a site% The next two lines form the child by the swapping of genetic% material between the parentschild(1:site,parent_number1)=parent_chrom(1:site,parent_number1);child(site+1:CHROM_LENGTH,parent_number1)=...     parent_chrom(site+1:CHROM_LENGTH,parent_number2);      else                           % No crossover occurs% Copy non-crossovered chromosomes into next generation% In this case we simply take one parent and make them% the child.child(:,parent_number1)=parent_chrom(:,parent_number1);	 end   end  % End the "if ELITISM..." statementend  % End "for parent_number1=..." loop%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Mutate children.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Here, we mutate to a different allele% with a probability MUTAT_PROB%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   for pop_member= 1:POP_SIZE,	if ELITISM ==1 & pop_member==bestmember  % If elitism on, and 											 % have the elite member		child(:,pop_member)=child(:,pop_member); % Do not mutate											% the elite member	else	  for site = 1:CHROM_LENGTH,         if MUTAT_PROB > rand        % If true then mutate              rand_gene=rand*10; 		 % Creat a random gene                        % If it is the same as the one already there then             % generate another random allele in the alphabet                        while child(site,pop_member) == rand_gene-rem(rand_gene,1),               rand_gene=rand*10;            end;                        % If it is not the same one, then mutate                        child(site,pop_member)=rand_gene-rem(rand_gene,1);                        % If takes a value of 10 (which it cannot            % mutate to) then try again (this is a very low probability			% event (most random number generators generate numbers			% on the *closed* interval [0,1] and this is why this line			% is included).                        if rand_gene == 10                 site=site-1;            end         end  % End "if MUTAT_PROB > rand ... 	   end  % End for site... loop	 end  % End "if ELITISM..."   end  % End for pop_member loop%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create the next generation (this completes the main part of the GA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   pop=child;               % Create next generation (children    							% become parents)          popcount=popcount+1;		% Increment to the next generation   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next, we have to convert the population (pop) to the base-10 % representation (called trait) so that we can check if the traits% all still lie in the proper ranges specified by HIGHTRAIT and LOWTRAIT% at the beginning of the next time around the loop.  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%for pop_member = 1:POP_SIZE	for current_trait = 1:NUM_TRAITS,			 trait(current_trait,pop_member,popcount)=0; % Initialize variablesplace_pointer=1;% Change each of the coded traits on the chromosomes into base-10 traits: % For each gene on the current_trait past the sign digit but before the% next trait find its real number amount and hence after finishing% the next loop trait(current_trait,pop_member,popcount) will be the base-10% number representing the traitfor gene=TRAIT_START(current_trait)+1:TRAIT_START(current_trait+1)-1, place=DECIMAL(current_trait)-place_pointer; trait(current_trait,pop_member,popcount)=... trait(current_trait,pop_member,popcount)+...    (pop(gene,pop_member))*10^place; place_pointer=place_pointer+1;end% Determine sign of the traits and fix % trait(current_trait,pop_member,popcount) so that it has the right sign:if pop(TRAIT_START(current_trait),pop_member) < 5   trait(current_trait,pop_member,popcount)=...      -trait(current_trait,pop_member,popcount);end	end % Ends "for current_trait=..." loop         end    % Ends "for pop_member=..." loop  			%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Terminate the program when the best fitness has not changed% more than EPSILON over the last DELTA generations.  It would also% make sense to use avefitness rather than bestfitness in this test.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   if popcount > DELTA+1 & ...       max(abs(bestfitness(popcount-DELTA:popcount-1)-...          bestfitness(popcount-DELTA-1:popcount-2)))<=EPSILON       break;   end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%end  % End "for pop_count=..." loop - the main loop.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next, provide some plots of the results of the simulation.% These are for the example function that we seek to maximize; however% for other applications it is not difficult to modify this code% to show plots that are informative for the application at hand.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%t=1:popcount-1;  % For use in plottingx=0:31/100:30;   % For our function the range of values we are consideringy=x;% Compute the function that we are trying to find the maximum of.for jj=1:length(x)	for ii=1:length(y)		z(ii,jj)=...		+5*exp(-0.1*((x(jj)-15)^2+(y(ii)-20)^2))...		-2*exp(-0.08*((x(jj)-20)^2+(y(ii)-15)^2))...		+3*exp(-0.08*((x(jj)-25)^2+(y(ii)-10)^2))...		+2*exp(-0.1*((x(jj)-10)^2+(y(ii)-10)^2))...		-2*exp(-0.5*((x(jj)-5)^2+(y(ii)-10)^2))...		-4*exp(-0.1*((x(jj)-15)^2+(y(ii)-5)^2))...		-2*exp(-0.5*((x(jj)-8)^2+(y(ii)-25)^2))...		-2*exp(-0.5*((x(jj)-21)^2+(y(ii)-25)^2))...		+2*exp(-0.5*((x(jj)-25)^2+(y(ii)-16)^2))...		+2*exp(-0.5*((x(jj)-5)^2+(y(ii)-14)^2));	endend% First, show the actual function to be maximized and its contour mapfigure(1)clfsurf(x,y,z);colormap(jet)% Use next line for generating plots to put in black and white documents.colormap(white);xlabel('x');ylabel('y');zlabel('z');title('Fitness function');figure(2) clfcontour(x,y,z,25)colormap(jet)% Use next line for generating plots to put in black and white documents.colormap(gray);xlabel('x');ylabel('y');zlabel('z');title('Fitness function (contour map)');hold on% Next, add on the evolution of the other population% members over time.for pop_member = 1:POP_SIZE	xx=squeeze(trait(1,pop_member,:));	yy=squeeze(trait(2,pop_member,:));	traitplot=plot(xx,yy,'k.');	set(traitplot,'MarkerSize',6);end% Then, add on the evolution of the best individual over % time that the GA finds.btraitplot=plot(bestindividual(1,:),bestindividual(2,:),'ko');set(btraitplot,'MarkerSize',4)hold off% Next, plot some data on the operation of the GAfigure (3)clfsubplot(211)plot(t,bestfitness,'k--',t,avefitness,'k-',t,worstfitness,'k-.')xlabel('Generation')ylabel('Best, average, and worst fitness')title('Best and worst fitness vs. generation')subplot(212)plot(t,bestindividual(1,:),'k-',t,bestindividual(2,:),'k--')xlabel('Generation')ylabel('Best individuals')title('Best individuals vs. generation')%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of program%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -