end end cleari; clear j; clear k; clear min; clear temp; clear temp1;
选择操作: %轮盘赌选择操作 %pop_size: 种群大小 %chromo_size: 染色体长度 %cross_rate: 是否精英选择
function selection(pop_size, chromo_size, elitism) global pop;
globalfitness_table;
fori=1:pop_size
r = rand * fitness_table(pop_size); first = 1; last = pop_size;
mid = round((last+first)/2); idx = -1;
while (first <= last) && (idx == -1) if r >fitness_table(mid) first = mid;
elseif r mid = round((last+first)/2); if (last - first) == 1 idx = last; break; end end for j=1:chromo_size pop_new(i,j)=pop(idx,j); end end if elitism p = pop_size-1; else p = pop_size; end fori=1:p for j=1:chromo_size pop(i,j) = pop_new(i,j); end end cleari; clear j; clearpop_new; clear first; clear last; clearidx; clear mid; 交叉操作: %单点交叉操作 %pop_size: 种群大小 %chromo_size: 染色体长度 %cross_rate: 交叉概率 function crossover(pop_size, chromo_size, cross_rate) global pop; fori=1:2:pop_size if(rand cross_pos = round(rand * chromo_size); if or (cross_pos == 0, cross_pos == 1) continue; end for j=cross_pos:chromo_size temp = pop(i,j); pop(i,j) = pop(i+1,j); pop(i+1,j) = temp; end end end cleari; clear j; clear temp; clearcross_pos; 变异操作: %单点变异操作 %pop_size: 种群大小 %chromo_size: 染色体长度 %cross_rate: 变异概率 function mutation(pop_size, chromo_size, mutate_rate) global pop; fori=1:pop_size if rand mutate_pos = round(rand*chromo_size); ifmutate_pos == 0 continue;