|
3-基于GA的寻优计算:
百度网盘链接:
链接:http://pan.baidu.com/s/1c1VuyUO 密码:2gof
具体链接在halcom.cn论坛,联系人QQ:3283892722
该论坛是一个学习交流平台,我会逐一的和大家分享学习。
欢迎大家录制视频,并提交给我,我来设置视频,你可在论坛进行打赏分享。
视频专用播放器:http://halcom.cn/forum.php?mod=viewthread&tid=258&extra=page%3D1
GA代码如下:
- clc,clear,close all
- warning off
- tic
- popmin = [-1, -1]; % Lb
- popmax =[ 1, 1]; % Ub
- pc = 0.75; % 0-1之间
- pm = 0.05; % 0-1之间
- nvar = 2; % 2个未知数
- itermax = 30; % 迭代次数
- sizepop = 30; % 种群
- % 初始化种群
- for i=1:sizepop
- pop(i,:) = code(popmin,popmax); % 实数编码
- fitness(i) = fun(pop(i,:)); % 目标函数值
- end
- [bestfitness,index] = min(fitness); % 极小值
- zbest = pop(index,:); % 最佳个体
- fitnessgbest = fitness; % 个体最优
- gbest = pop; % 最优种群
- fitnesszbest = bestfitness; % 全局最优
- %% 迭代寻优
- for i=1:itermax
- % 选择算子
- pop = select(sizepop,pop,fitness,popmin,popmax);
- % 交叉算子
- pop = cross(sizepop,pc,pop,popmin,popmax);
- % 变异
- pop = mut(sizepop,pm,pop,popmin,popmax);
-
- for j=1:sizepop
- fitness(j) = fun( pop(j,:) ); % 计算适应度值
- if fitness(j)< fitnessgbest(j)
- fitnessgbest(j) = fitness(j);
- gbest(j,:) = pop(j,:);
- end
- if fitness(j)<fitnesszbest
- fitnesszbest = fitness(j);
- zbest = pop(j,:);
- end
- end
- fitness_iter(i) = fitnesszbest;
- end
- figure,
- plot(fitness_iter,'ro-','linewidth',2)
- toc
- disp(['最优解 ', num2str(zbest)] )
复制代码 选择算子:
- function pop = select(sizepop,pop,fitness,popmin,popmax)
- [a, b] = sort(fitness,'descend');
- c = floor(sizepop/4);
- % 替换了最差的个体,保留了精英种群
- for i=1:c
- pop(b(i),:) = popmin + rand(1,2).*(popmax-popmin);
- end
复制代码 变异算子
- function pop = mut(sizepop,pm,pop,popmin,popmax)
- for j = 1:sizepop*2
- if rand>pm
- a=0;
- while a==0
- a = floor(rand*sizepop);
- end
- b = pop(a,:);
- if rand>0.5
- pop(a,:) = pop(a,:) + rand(1,2).* (popmax-pop(a,:));
- else
- pop(a,:) = pop(a,:) + rand(1,2).* (popmin-pop(a,:));
- end
-
- flag2 = test( pop(a,:),popmin,popmax );
- if flag2==1 % 不可行
- pop(a,:) = b;
- end
-
- end
- end
复制代码 交叉算子:
- function pop = cross(sizepop,pc,pop,popmin,popmax)
- for j=1:sizepop*2
- if rand>pc
- a = [0,0];
- while min(a)==0
- a = floor( rand(1,2)*sizepop );
- end
- k = rand;
- pop1 = pop(a(1),:) ;
- pop2 = pop(a(2),:) ;
- pop(a(1),:) = (1-k)*pop1+k*pop2;
- pop(a(2),:) = (1-k)*pop2+k*pop1;
-
- flag1 = test( pop(a(1),:) ,popmin,popmax);
- if flag1==1 % 不可行
- pop(a(1),:) = pop1;
- end
- flag2 = test( pop(a(2),:) ,popmin,popmax);
- if flag2==1 % 不可行
- pop(a(2),:) = pop2;
- end
-
- end
- end
复制代码 编码:
- function pop = code(popmin,popmax)
- flag =1;
- while flag==1
- pop = popmin + rand(1,2).*(popmax-popmin); % 实数编码
- % 检验染色体的可行性
- flag = test(pop,popmin,popmax);
- end
复制代码 校验:
- function flag = test(pop,popmin,popmax)
- % 检验染色体的可行性
- if pop(1)<popmin(1) || pop(1)>popmax(1) || pop(2)<popmin(2) || pop(2)>popmax(2)
- flag = 1; % 不可行
- else
- flag = 0; % 可行
- end
复制代码
案例分享:
【1】遗传算法GA 在MacroFemtocell异构网络基于能效优化的子载波分配
|
|