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

📄 yichuan.m

📁 一种遗传算法的MATLAB实现代码
💻 M
字号:
% generic algorithm for function f(x1,x2) optimum
clear all;
close all;

%parameters
size=80;
G=100;
codeL=10;
umax=2.048;
umin=-2.048;
E=round(rand(size,2*codeL));  %initial code

%main program
for k=1:1:G
    time(k)=k;
    
    for s=1:1:size
        m=E(s,:);
        y1=0;y2=0;
        
        %decoding
        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;
    end
    Ji=1./F;
    %*********step 1:evaluate best J **********
    BestJ(k)=min(Ji);
    jjj=sort(Ji);
    
    fi=F;
    [oderfi,indexfi]=sort(fi);
    bestfi=oderfi(size);
    bests=E(indexfi(size),:);
    bfi(k)=bestfi;
    %*********step 2:select and reproduct operation **********
    fi_sum=sum(fi);
    fi_size=(oderfi/fi_sum)*size;
    fi_s=floor(fi_size);
   
    kk=1;
    for i=1:1:size
        for j=1:1:fi_s(i)
           tempE(kk,:)=E(indexfi(i),:);
           kk=kk+1;
        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 j=n:1:20
               tempE(i,j)=E(i+1,j);
               tempE(i+1,j)=E(i,j);
            end
        end
    end
    tempE(size,:)=bests;     %保优
    E=tempE;
    %*********step 4:mutation operation **********
    pm=0.1;
    for i=1:1:size
        for j=1:1:2*codeL
            temp=rand;
            if pm>temp
                if tempE(i,j)==0
                    tempE(i,j)=1;
                else
                    tempE(i,j)=0;
                end
            end
        end
    end
    %guarantee tempPop(30,:)is the code belong to the best individual(max(fi))
    tempE(size,:)=bests;
    E=tempE;
end

max_value=bestfi;
y1=0;y2=0;
%decoding
m1=bests(1:codeL);
for i=1:1:codeL
    y1=y1+m1(i)*2^(i-1);
end
x1=(umax-umin)*y1/1023+umin;
m2=bests(codeL+1:2*codeL);
for i=1:1:codeL
    y2=y2+m2(i)*2^(i-1);
end
x2=(umax-umin)*y2/1023+umin;
bests
bestfi
x1
x2
figure(1);
plot(time,BestJ);
xlabel('times');ylabel('best J');
figure(2);
plot(time,bfi);
xlabel('times');ylabel('best F');

⌨️ 快捷键说明

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