变异操作的
Matlab
编程实现
三种变异操作方式:
互换
逆序:
涉及函数
fliplr
插入:
涉及函数:
circshift
%变异操作--插入方法
function outChromes=muteChromesInsert(chromes,muteRate)
[pop,len]=size(chromes);
for i=1:pop
nowChrome=chromes(i,:);
if rand()<muteRate %判断能否变异
% outPoint=randperm(len,1);
% inPoint=randperm(len,1);
i
points=randperm(len,2)
nowChrome
if points(1)<points(2)
insertChrome=nowChrome(points(1):points(2)-1);
newChrome=circshift(insertChrome,-1);
chromes(i,points(1):points(2)-1)=newChrome;
else
insertChrome=nowChrome(points(2)-1:points(1));
newChrome=circshift(insertChrome,1);
chromes(i,points(2)-1:points(1))=newChrome;
end
chromes(i,:)
end
outChromes=chromes;
end
end
%变异操作--逆序方法
function outChromes=muteChromesInv(chromes,muteRate)
[pop,len]=size(chromes);
for i=1:pop
nowChrome=chromes(i,:);
if rand()<muteRate
% outPoint=randperm(len,1);
% inPoint=randperm(len,1);
i
points=sortrows(randperm(len,2)')'
nowChrome
newChrome0=nowChrome(points(1):points(2));
newChrome1=fliplr(newChrome0)
chromes(i,points(1):points(2))=newChrome1;
chromes(i,:)
end
outChromes=chromes;
end
end
JSP
遗传算法集成
%找出当前种群中最优解的染色体编码以及最优解的值
function [nowOptFit,nowOptChrome]=findOptSolution(inChromes,data)
%step1:计算每条染色体的适应度值,放到数组中
pop=size(inChromes,1);
fitnesses=zeros(pop,1);
for i=1:pop
sch=createSchedule(data,inChromes(i,:));
fit=fitness(sch);
fitnesses(i)=fit;
end
%对适应度值进行排序
[fit2,chromeId]=sortrows(fitnesses,1);
nowOptFit=fit2(1); %对应最好的适应度值
nowOptChrome=inChromes(chromeId(1),:); %对应最好的染色体
end