The code is as follows:
function M_main () Clearclcmax_gen = 100;% perform algebra pop_size = 100;% population size Chromsome = 10;% chromosome length pc = 0.9;% crossover probability pm = 0.25;% mutation Probability Gen = 0;% Statistical algebra% Initialization init = 40*rand (pop_size, chromsome) -20;pop = Init;fit = obj_fitness (POP); [Max_fit, Index_max] = max (FIT); maxfit = Max_fit; [Min_fit, Index_min] = min (fit), Best_indiv = Pop (Index_max,:);% iteration operation while gen<max_gen Gen = gen+1; & nbsp BT (gen) = max_fit; If maxfit<max_fit; Maxfit = max_fit; &nbs P Pop (index_min,:) = Pop (Index_max,:); Best_indiv = Pop (Index_max,:); &nbs P end Best_indiv_tmp (gen) = Pop (Index_max); Newpop = GA (pop, PC, PM, chromsome, fit); Fit = obj_fitness (newpop); [Max_fit, Index_max] = max (FIT); [Min_fit, index_min] = min (fit); &NB Sp pop = newpop; trace (1, gen) = max_fit; Trace (2, gen) = SUM (FIT)./length (fit); end% execution result [F_max gen_ct] = max (BT)% is the maximum value and the algebraic maxfitbest_indiv% drawing% bthold Onplot (trace (1,:), '. G: ');p lot (Trace (2,:), '. R '), title ( ' Experimental result graph ') xlabel (' Iteration number/generation '), Ylabel (' Best Fit (max) '),% coordinate notation plot (gen_ct-1, 0:0.1:f_max+1, ' C ');% draw Maximum text (gen_ct, f_max+1 , ' Max ') hold off function [fitness] = obj_fitness (pop) % fitness calculation function [R C] = size (pop); x = pop; fitness = zeros (R, 1); For i = 1:r for j = 1:c &NBSP ; Fitness (i, 1) = Fitness (i, 1) +sin (sqrt (ABS (40*x (i))) +1-abs (x (i))/20.0; & nbsp end end end function Newpop = GA (pop, PC, PM, chromsome , fit) pop_size = size (pop, 1); % Roulette selection PS = Fit/sum (FIT); &nbsP Pscum = Cumsum (PS),%size (pscum) r = rand (1, pop_size); QW = Pscum*ones (1, pop_size); selected = SUM (Pscum*ones (1, pop_size) <ones (pop_size, 1) *r) +1 ; Newpop = Pop (selected,:); % cross if pop_s IZE/2 ~= 0 pop_size = pop_size-1; end &N Bsp For i = 1:2:pop_size-1 while pc>rand & nbsp C_PT = round (8*rand+1); p OP_TP1 = Newpop (i,:);p op_tp2 = Newpop (i+1,:); Newpop (i+1, 1:c_pt) = POP_TP1 (1, 1:c_pt); Newpop (i, c_pt+1:chromsome) = POP_TP2 (1, c_p T+1:chromsome); end &NBS P end % variation for i = 1:pop_size If pm>rand M_PT = 1+round (9*rand); & nbsp Newpop (i, m_pt) = 40*rand-20; end end EndEnd
Demonstration sample code for solving optimization problem of matlab genetic algorithm