當前位置:編程學習大全網 - 編程語言 - 關於遺傳算法的MATLAB實現

關於遺傳算法的MATLAB實現

function [x fx string]=fun_SuiJiSuanFa2(N,genLenth,Pc,Pm,downbound,upbound,generation)

%[x fx string]=fun_SuiJiSuanFa2(6,16,0.7,0.01,-3,3,100)

%f 表示函數

%N表示染色體種群大小

%genLenth表示染色體長度

%Pc表示交叉概率

%Pm表示突變概率

%downbound

%upbound

%generation循環代數

%進制編碼,此處編寫為二進制

num=2;

initdata=randi([0 num-1],N,genLenth);

%二進制編碼的權值

weight=(num).^(genLenth/2-1:-1:0);

weights=repmat(weight,N,1);

%保存每代的最好值和平均值,

meanally=zeros(1,generation);

maxally=zeros(1,generation);

Nowx=zeros(generation,genLenth);

for k=1:generation

%解碼後的整數

allx1=sum(initdata(:,1:genLenth/2).*weights,2);

allx2=sum(initdata(:,genLenth/2+1:end).*weights,2);

%映射到取值範圍

delt=(upbound-downbound)/(num^(genLenth/2)-1);

allx1=allx1.*delt+downbound;

allx2=allx2.*delt+downbound;

%染色體的適應性

ally=f(allx1,allx2);

%平均值,最大值

meanally(k)=mean(ally);

maxally(k)=max(ally);

%找下標,確定是哪條染色體

index=find(ally==maxally(k));

Nowx(k,:)=initdata(index(1),:);

%最大值沒有提高就取上次的

if(k>=2&&maxally(k)<maxally(k-1))

maxally(k)=maxally(k-1);

Nowx(k,:)=Nowx(k-1,:);

end

%染色體的適應性比率

ratio=ally./sum(ally);

%交叉,變異

%交叉幾個,從第幾個開始。

%此處只交叉1個(總***才6個),隨機給壹個。

sumRatio=cumsum(ratio);

data=zeros(N,genLenth);

for i=1:N/2

Select1=find(sumRatio>=rand);

Select2=find(sumRatio>=rand);

data(2*i-1,:)=initdata(Select1(1),:);

data(2*i,:)=initdata(Select2(1),:);

if(rand<Pc)

%交叉

location=randi([1,genLenth]);

temp=data(2*i-1,location:end);

data(2*i-1,location:end)=data(2*i,location:end);

data(2*i,location:end)=temp;

else

%變異

if(rand<Pm)

location=randi([1,genLenth]);

data(2*i-1,location)=1-data(2*i-1,location);

end

if(rand<Pm)

location=randi([1,genLenth]);

data(2*i,location)=1-data(2*i,location);

end

end

end

initdata=data;

end

fx=max(maxally);

lastIndex=find(maxally==fx);

string=Nowx(lastIndex(1),:);

x(1)=sum(string(1:genLenth/2).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;

x(2)=sum(string(1+genLenth/2:end).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;

%繪制性能圖

%figure,hold on;

clf;figure(1),hold on;

plot((1:k)',meanally,'b.-');

plot((1:k)',maxally,'r.:');

end

function fun=f(x,y)

fun=(1-x).^2.*exp(-x.^2-(1+y).^2)-(x-x.^3-y.^3).*exp(-x.^2-y.^2);

%fun=-(x-1).^2-3.*(y-2).^2+100;

end

  • 上一篇:單片機就業方向
  • 下一篇:c語言問題,關於printf語句的輸出
  • copyright 2024編程學習大全網