实数编码的遗传算法代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
function GA_real_coded_min
% ±¾ÀýΪʵÊý±àÂëÒÅ´«Ëã·¨Çóº¯Êý×îСֵµÄÓÅ»¯ÎÊÌâ
% Ä¿±êº¯ÊýΪ J = x1^2 + x2^2
% ÆäÖÐ x1 µÄ·¶Î§Îª [-10,10], x2 µÄ·¶Î§Îª [-10,10]
Size = 200;% the value of population
CodeL = 2;
MinX(1) = -10;
MaxX(1) = 10;
MinX(2) = -10;
MaxX(2) = 10;
E(:,1) = MinX(1) + (MaxX(1)-MinX(1))*rand(Size,1);
E(:,2) = MinX(2) + (MaxX(2)-MinX(2))*rand(Size,1);
G = 100;% the max generation
%---------------Start
Running---------------------------------------------
for kg = 1 : G
time(kg) = kg;
%----------------------step 1: Evaluate BestJ-------------------------for i = 1 : Size
xi = E(i,:);
x1 = xi(1);
x2 = xi(2);
% ÏÂÃæµÄ F
ÓÃÓÚ¼ÆËã¸öÌåµÄÊÊÓ¦¶ÈÖµ£¬ÊÊÓ¦¶Èº¯Êý¸ù¾ÝÄ¿±êº¯Êý½øÐÐÁËÏßÐԱ任
F(i) = 1/(x1^2 + x2^2);% ¼ÆËãÊÊÓ¦¶ÈÖµ£¬Ô½´óÔ½ºÃ
Ji = x1^2 + x2^2;% ¼ÆËãÄ¿±êÖµ£¬Ô½Ð¡Ô½ºÃ
BsJi(i) = min(Ji);
end
[OrderJi,IndexJi] = sort(BsJi);
BestJ(kg) = OrderJi(1);
Ji = BsJi + eps;% Avoiding deviding zero
fi = F;
[Orderfi,Indexfi] = sort(fi); % Arranging fi small to bigger
Bestfi = Orderfi(Size); % Let Bestfi=max(fi)
BestS = E(Indexfi(Size),:); % Let BestS=E(m),m is the Indexfi belongs to max(fi)
bfi(kg) = Bestfi;
kg
BestS
%--------------------Step 2:Select and Reproduct Operation------------ fi_sum = sum(fi);
fi_Size = (Orderfi/fi_sum)*Size;
fi_S = floor(fi_Size); % Selecting Bigger fi value
r = Size - sum(fi_S);
Rest = fi_Size - fi_S;
[RestValue,Index] = sort(Rest);
for i = Size : -1 : Size-r+1
fi_S(Index(i)) = fi_S(Index(i)) + 1;% Adding rest to equal Size end
k = 1;
for i = Size : -1 : 1
for j = 1 : fi_S(i)
TempE(k,:) = E(Indexfi(i),:); % Selecting and Reproduce
k = k + 1; % k is used to reproduce end
end
%---------------------Step 3: Crossover Operation--------------------- Pc = 0.90;
for i = 1 : 2 : Size-1
temp = rand;
if Pc > temp
alfa = rand;
TempE(i,:) = alfa*E(i+1,:) + (1-alfa)*E(i,:);
TempE(i+1,:) = alfa*E(i,:) + (1-alfa)*E(i+1,:);
end
end
TempE(Size,:) = BestS;
E = TempE;
%---------------------Step 4: Mutation Operation---------------------- Pm = 0.10 - [1:Size]*(0.01)/Size; % Bigger fi,smaller Pm
Pm_rand = rand(Size,CodeL);
Mean = (MaxX+MinX)/2;
Dif = MaxX - MinX;
for i = 1 : Size
for j = 1 : CodeL
if Pm(i) > Pm_rand(i,j);
TempE(i,j) = Mean(j) + Dif(j)*(rand-0.5);
end
end
end
% Guarantee TempE(Size,:) belong to the best individual
TempE(Size,:) = BestS;
E = TempE;
end
%-------------------------------------------------------------------------
BestS
Bestfi
figure(1);
plot(time,BestJ,'b');
xlabel('Generations'); ylabel('Best Objective');% the value of objective figure(2);
plot(time,bfi,'b');
xlabel('Generations'); ylabel('Best Fitness');% the value of fitness。