⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 a4.m

📁 遗传算法工具箱
💻 M
字号:
% Define GA Parameters
NVAR = 20;   % No. of variables
RANGE = [0; 200];  %Range of variable
GGAP = 0.8; % Generation gap
XOVR = 1; % Crossover rate
MUTR = 1/NVAR; % Mutation rate
MAXGEN = 10; % Maximum no. of generations
INSR = 0.9; % Insertion rate
SUBPOP =1; % No. of subpopulations
MIGR = 0.2; % Migration rate
MIGGEN = 20; % No. of gens / migration
NIND = 20; % No. of individuals / subpop
SEL_F = 'sus'; % 选择函数名
XOV_F ='recdis'; % 重组函数名
MUT_F ='mutbga'; % 变异函数名
OBJ_F ='objharv'; % 目标函数名
FieldDD = rep(RANGE,[1,NVAR]); %译码矩阵
gen=0;  %counter
trace=zeros(MAXGEN,2);%遗传算法性能跟踪
Chrom=crtrp(NIND,FieldDD);% Fitness assignment to whole population
while gen < MAXGEN,% Generational loop
ObjV = objharv(Chrom); %Calculate objective function for population
FitnV = ranking(-ObjV,[2,1],SUBPOP);
SelCh = select(SEL_F, Chrom, FitnV, GGAP, SUBPOP);% Select individuals from population
SelCh=recombin(XOV_F, SelCh, XOVR, SUBPOP);% Recombine selected individuals
SelCh = mutate(MUT_F,SelCh,FieldDD,[MUTR],SUBPOP);% Mutate offspring
ObjVOff = feval(OBJ_F,SelCh);% Calculate objective function for offsprings
% Insert best offspring replacing worst parents
[Chrom, ObjV] = reins(Chrom, SelCh, SUBPOP,[1 INSR], ObjV, ObjVOff);
gen=gen+1;% Increment counter
[trace(gen,1),I]=min(ObjV); trace(gen,2)=mean(ObjV);
% Migrate individuals between subpopulations
if (rem(gen,MIGGEN) == 0)
[Chrom, ObjV] = migrate(Chrom, SUBPOP, [MIGR, 1, 1], ObjV);
end
end
[Y,I]=max(ObjV),%输出最优解及其序号,Y为最优解,I为种群的序号
figure(1);plot(Chrom(I,:));hold on;grid;plot(Chrom(I,:),'bo')
figure(2);plot(trace(:,1));hold on;plot(trace(:,2),'-.');grid%遗传算法性能跟踪分布图
legend('解的变化','种群均值的变化');xlabel('迭代次数')

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -