1+ function out = RunGA(problem , params )
2+
3+ % Problem
4+ CostFunction = problem .CostFunction ;
5+ nVar = problem .nVar ;
6+
7+ % Params
8+ MaxIt = params .MaxIt ;
9+ nPop = params .nPop ;
10+ beta = params .beta ;
11+ pC = params .pC ;
12+ nC = round(pC * nPop / 2 )*2 ;
13+ mu = params .mu ;
14+
15+ % Template for Empty Individuals
16+ empty_individual.Position = [];
17+ empty_individual.Cost = [];
18+
19+ % Best Solution Ever Found
20+ bestsol.Cost = inf ;
21+
22+ % Initialization
23+ pop = repmat(empty_individual , nPop , 1 );
24+ for i = 1 : nPop
25+
26+ % Generate Random Solution
27+ pop(i ).Position = randi([0 , 1 ], 1 , nVar );
28+
29+ % Evaluate Solution
30+ pop(i ).Cost = CostFunction(pop(i ).Position);
31+
32+ % Compare Solution to Best Solution Ever Found
33+ if pop(i ).Cost < bestsol .Cost
34+ bestsol = pop(i );
35+ end
36+
37+ end
38+
39+ % Best Cost of Iterations
40+ bestcost = nan(MaxIt , 1 );
41+
42+ % Main Loop
43+ for it = 1 : MaxIt
44+
45+ % Selection Probabilities
46+ c = [pop .Cost ];
47+ avgc = mean(c );
48+ if avgc ~= 0
49+ c = c / avgc ;
50+ end
51+ probs = exp(-beta * c );
52+
53+ % Initialize Offsprings Population
54+ popc = repmat(empty_individual , nC / 2 , 2 );
55+
56+ % Crossover
57+ for k = 1 : nC / 2
58+
59+ % Select Parents
60+ p1 = pop(RouletteWheelSelection(probs ));
61+ p2 = pop(RouletteWheelSelection(probs ));
62+
63+ % Perform Crossover
64+ [popc(k , 1 ).Position, popc(k , 2 ).Position] = ...
65+ Crossover(p1 .Position , p2 .Position );
66+
67+ end
68+
69+ % Convert popc to Single-Column Matrix
70+ popc = popc(: );
71+
72+ % Mutation
73+ for l = 1 : nC
74+
75+ % Perform Mutation
76+ popc(l ).Position = Mutate(popc(l ).Position, mu );
77+
78+ % Evaluation
79+ popc(l ).Cost = CostFunction(popc(l ).Position);
80+
81+ % Compare Solution to Best Solution Ever Found
82+ if popc(l ).Cost < bestsol .Cost
83+ bestsol = popc(l );
84+ end
85+
86+ end
87+
88+ % Merge and Sort Populations
89+ pop = SortPopulation([pop ; popc ]);
90+
91+ % Remove Extra Individuals
92+ pop = pop(1 : nPop );
93+
94+ % Update Best Cost of Iteration
95+ bestcost(it ) = bestsol .Cost ;
96+
97+ % Display Itertion Information
98+ disp([' Iteration ' num2str(it ) ' : Best Cost = ' num2str(bestcost(it ))]);
99+
100+ end
101+
102+
103+ % Results
104+ out.pop = pop ;
105+ out.bestsol = bestsol ;
106+ out.bestcost = bestcost ;
107+
108+ end
0 commit comments