GA Optimization
GA Optimization
% Define parameters
populationSize = 50; % Number of individuals in the population
numGenerations = 100; % Number of generations
numWeights = 11; % Number of weights to optimize (change as needed)
mutationRate = 0.1; % Probability of mutation
% Initialize population
population = rand(populationSize, numWeights) * 2 - 1; % Random weights between -1 and 1
% Main GA loop
for generation = 1:numGenerations
fitnessScores = zeros(populationSize, 1);
% Crossover
offspring = crossover(selectedPopulation);
% Mutation
offspring = mutate(offspring, mutationRate);
for i = 1:populationSize
competitors = randi(populationSize, tournamentSize, 1);
[~, bestIdx] = min(fitnessScores(competitors));
selectedIndices(i) = competitors(bestIdx);
end
end
for i = 1:2:numSelected-1
parent1 = selectedPopulation(i, :);
parent2 = selectedPopulation(i+1, :);
% One-point crossover
crossoverPoint = randi(numWeights - 1);
offspring(i, :) = [parent1(1:crossoverPoint), parent2(crossoverPoint + 1:end)];
offspring(i+1, :) = [parent2(1:crossoverPoint), parent1(crossoverPoint + 1:end)];
end
end
for i = 1:numIndividuals
for j = 1:numWeights
if rand < mutationRate
mutatedPopulation(i, j) = rand * 2 - 1; % New random weight between -1 and 1
end
end
end
end