📄 my_genetic.asv
字号:
%%%%%%%This Code is provided by Mohammad Alipanah (87121003)clc;
clear all;
%%%%%%% initialization %%%%%%
N= 50;
Pc= 0.3;
Pm=0.05;
ITER=100;
m=2;
Lo=[-4 -1.5];
Hi=[2 1];
w=rand(N,m);
Population=[Lo(1)+(w(:,1).*(Hi(1)-Lo(1))) Lo(2)+(w(:,1).*(Hi(2)-Lo(2)))];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
best_so_far=[];
average_fitness=[];
for it=1:ITER
[selection_probability,fit,ave_fit,max_fit,opt_sol]=fit_eval(Population,N,m);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if it==1
best_so_far(it)=max_fit;
final_sol=opt_sol;
elseif max_fit>best_so_far(it-1)
best_so_far(it)=max_fit;
final_sol=opt_sol;
else
best_so_far(it)=best_so_far(it-1);
end
average_fitness(it)=ave_fit;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Reproduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Selection fot Cross over %%%%%%%%%%%%%%%%
[mating_pool]=g_roulette_wheel(Population,N,selection_probability);
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Cross Over %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[new_pop]=g_crossover(mating_pool,Pc,N);
%%%%%%%%%% Check whether new population is in range or not %%%%%%%%%%%
[new_pop]=rg_replacement(new_pop,N,m,Lo,Hi);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Mutation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[Population]=g_mutation(new_pop,Pm,N,m);
%%%%%%%%%%%%%%%%%%%%%%%%% End of reproduction %%%%%%%%%%%%%%%%%%%%%%%%
end
disp(' Final Solution');
disp(final_sol);
disp(' Optimum Fitness');
disp(best_so_far(end));
%%%%%%%%%%%%%%%%%% Graph %%%%%%%%%%%%%%%%%%%%%%
x=1:ITER;
figure,plot(x,best_so_far,'-r',x,average_fitness,'--b');
xlabel('Generation');
ylabel('Fitness Function');
legend('Best So Far','Average Fitness');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -