www.pudn.com > ga_basicprogram.rar > ga_basicprogram.m


 
%This  is basic program about genetic algorithm. 
 
%Parameters 
size=80;         
G=100; 
codel=10; 
umax=2.048; 
umin=-2.048; 
 
E=round(rand(size,2*codel));    %Initial Code 
 
 
 
%main pogram 
for k=1:1:G 
    time(k)=k; 
    for s=1:1:size 
       m=E(s,:); 
       y1=0;y2=0; 
        
       %uncoding 
       m1=m(1:1:codel); 
       for i=1:1:codel 
          y1=y1+m1(i)*2^(i-1);  
       end 
       x1=(umax-umin)*y1/1023+umin; 
       m2=m(codel+1:1:2*codel); 
       for i=1:1:codel 
          y2=y2+m2(i)*2^(i-1); 
           
       end 
       x2=(umax-umin)*y2/1023+umin; 
       F(s)=100*(x1^2-x2)^2+(1-x1)^2; %Fitness Function 
    end 
     
    Ji=1./F; 
    %----------step 1 
    BestJ(k)=min(Ji); 
    fi=F; 
    [oderfi,indexfi]=sort(fi);%Arranging fi small to bigger 
    Bestfi=oderfi(size);    %Let Bestfi=max(fi) 
    BestS=E(indexfi(size),:);%Let BestS=E(m),m is the Indexfi belong to max(fi) 
    bfi(k)=Bestfi; 
     
    %*********** step 2 :Select and Reproduct Operation---------------- 
    fi_sum=sum(fi); 
    fi_size=(oderfi/fi_sum)*size; 
     
    fi_S=floor(fi_size);        %Selecting Bigger fi value 
     
    kk=1; 
    for i=1:1:size 
        for u=1:1:fi_S(i)          %Select and Reproduce 
           TempE(kk,:)=E(indexfi(i),:); 
           kk=kk+1;                 %kk is used to reproduce 
        end 
    end 
     
    %********** step 3 :Crossover Operation--------------------- 
     
    pc=0.60; 
    n=ceil(20*rand); 
    for i=1:2:(size-1) 
       temp=rand; 
       if pc>temp 
           for u=n:1:20 
              TempE(i,u)=E(i+1,u); 
              TempE(i+1,u)=E(i,u); 
           end 
       end 
    end 
    TempE(size,:)=BestS; 
    E=TempE; 
     
    %*************** step 4 :Mutation Operation ------------------ 
     
    pm=0.1; 
    for i=1:1:size 
       for u=1:1:2*codel 
          temp=rand;     
          if pm>temp 
             if TempE(i,u)==0 
                TempE(i,u)=1; 
             else 
                 TempE(i,u)=0; 
             end 
          end 
       end 
    end 
     
    %*************************************************** 
    TempE(size,:)=BestS;    %Save the best individual 
    E=TempE; 
     
     
end 
 
max_value=Bestfi 
BestS 
x1 
x2 
figure(1); 
plot(time,BestJ); 
xlabel('times');ylabel('BestJ'); 
figure(2); 
plot(time,bfi); 
xlabel('times');ylabel('BestF');