📄 a3.m
字号:
NIND = 40; % Number of individuals
MAXGEN =100; % Maximum no. of generations
NVAR = 20; % No. of variables
PRECI = 20; % Precision of variables
GGAP = 0.9; % Generation gap
trace=zeros(MAXGEN,2);
% Build field descriptor
FieldD = [rep([PRECI],[1,NVAR]);rep([-512;512],[1,NVAR]); rep([1;0;1;1],[1,NVAR])];
% Initialise population
Chrom = crtbp(NIND, NVAR*PRECI);
gen = 0;% Counter
ObjV = objfun1(bs2rv(Chrom,FieldD));% Evaluate initial population
while gen < MAXGEN,% Generational loop
% Assign fitness values to entire population
FitnV = ranking(ObjV);
SelCh = select('sus', Chrom, FitnV, GGAP);% Select individuals for breeding
SelCh = recombin('xovsp',SelCh,0.7);% Recombine individuals (crossover)
SelCh = mut(SelCh);% Apply mutation
ObjVSel = objfun1(bs2rv(SelCh,FieldD));% Evaluate offspring, call objective function
[Chrom ObjV]=reins(Chrom,SelCh,1,1,ObjV,ObjVSel);% Reinsert offspring into population
gen = gen+1;% Increment counter
trace(gen,1)=min(ObjV);trace(gen,2)=sum(ObjV)/length(ObjV);
if (gen==MAXGEN)
clf;figure(1);plot(ObjV);hold on; plot(ObjV,'b*');grid
pause(2);
end
end
figure(2)
clf;plot(trace(:,1));hold on; plot(trace(:,2),'-.'); plot(trace(:,1),'.'); plot(trace(:,2),'.');grid;
legend('解的变化','种群均值的变化')
[Y,I]=min(ObjV),I,bs2rv(Chrom(I,:),FieldD)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -