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