GA(遗传算法)的Matlab程序原理(from:六分之一工作室)

z=f(x,y) 

1、 编码(解决初始化种群),先创建一个数组pop(popsize stringlenth)有popsize表示染色体个数列stringlenth的前 一部分代表x的染色体,后一部分代表y的染色体。计算x,y染色体对所对应的十进制数值并记数组pop的第 stringlenth+1,stringlenth+2列,计算f(x,y)的值并计为数组pop的第stringlenth+3列,计算每个染色体的 复制概率并计为数组pop的第stringlenth+4列 

function[pop1 f d pe stringlenth]=initialize(popsize stringlenth pop), 

pop=round(rand(popsize stringlenth)), 

pop(.stringlenth+1=((2.^(size(pop(.1.stringlenth1).2)-1.-1.0)*pop(.1.stringlenth)).*( )/(2.^stringlenth1-1)+ ), 

pop(.stringlenth+3)=fun(pop(.stringlenth+1)pop(.stringlenth+2)), 

pop(.stringlenth+4)=pop(.stringlenth+4)=pop(.stringlenth+3)./sum(pop(.stringlenth+3)), 
其中fun(x)为目标函数的matlab.m文件.

 

2、确保复制过程中染色体个数保持不变的情况下确定每个染色体复制数,如果是某一染色体的复制数为负数,则令此染色体的复制数为0,复制概率为止的染色体的复制数根据其占正值总体的比率来确定,复制数=比率 popsize 

pop(.stringlenth+5)=round(pop. Stringlenth+4).*popsize), 

A=sort(pop(.stringlenth+5)), 

b=sum(A((11-a).10),(其中a为复制概率为正值的染色体个数) 

pop(.stringlenth+6)=round(pop(.stringlenth+5)./b).*popsize). 

pop(.stringlenth+6)表示每个染色体复制数.

 

3、染色体复制数,根据每个染色体的复制数重新创建新的染色体数组pop1 

function[parent1 parent2 stringlenth]=parent(f d pop stringlenth), 

Ci=repmat(pop(i 1. stringlenth)[pop(i stringlenth+6)1 1]).(i=1 2 …popsize) 

pop1=[C1] [C2] … [Cpopsize], 

pop1=round([C1] [C2] … [Cpopsize]). 
每个初始染色体按其复制数进行复制.

 

4、选择父代进行父叉,在数组pop1中随机地使各染色体两两配对,作为父代进行父叉,创建新的数组child1和child2父叉点cpoint随机选取父叉概率pc根据实际情况人为选取 

function[child1 child2 pm parent stringlenth]=crossover(parent1 parent2 pc stringlenth ), 

f=round(9*rand(1.10))+1, 

d=[1 2 3 4 5 6 7 8 9 10], 

parent1=pop1(f.),parent2=pop1(d.), 

if(randcpoint=round(rand*(stringlenth-2))+1, 

child1=[parent1(.1.cpoint)][parent2(.cpoint+1. stringlenth)], 

child2=[parent2(.1.cpoint)][parent1(.cpoint+1. stringlenth)], 

else 

child1=parent1, 

child2=parent2. 

5、染色体变异 随机选取染色体中某一个或几个基因进行变异创建新的数组child作为父代 

function[child]=mutation(parent pm), 

parent=child, 

if(randmpoint=round(rand*(stringlenth-1))+1, 

child=parent, 

child(.mpoint)=abs(parent(.mpoint)-1), 

else 

child=parent, 

end 

6、保留上一代的优良染色体作为部分初始值和随机染色体组成新的染色体组 

function[pop2 m W]=best(child child1 child2 pop), 

Q1=child(.stringlenth+3), 

for i=1.10 

if(Q1(i)>(max(Q1)-0.0001)) 

q1=i, 

end 
end 

W=round(9.*rand(1 4)+1, 

pop2(W 1. stringlenth+3)=[child(q1.)child(q2.).child2(q3.).pop(q4 1. stringlenth+3)], 

m=max([max(Q1)max(Q2)max(Q3)max(Q4)]), 

end 

其中m为最好染色体值,循环执行上述程序即可 

关于2元约束问题先根据约束力方程求解2元函数fun1(x)再只需要将单约束程序中的y的下限b2换成fun1(x)即可,因为这样能限制当x取值后y的取值。多元多约束程序和2元多约束程序一样,只不过多开辟空间而已。

 

原文地址:https://www.cnblogs.com/menfightfor2018/p/3863821.html