遗传算法matlab实例
时间: 2023-08-13 18:09:00 浏览: 86
当然没问题!下面是一个简单的遗传算法的 MATLAB 实例:
```matlab
% 遗传算法参数设置
popSize = 50; % 种群大小
numGenes = 10; % 染色体长度
mutationRate = 0.01; % 变异率
tournamentSize = 5; % 锦标赛选择的参与者数量
maxGenerations = 100; % 最大迭代次数
% 初始化种群
population = round(rand(popSize, numGenes));
% 迭代优化
for generation = 1:maxGenerations
% 计算适应度
fitness = sum(population, 2);
% 选择父代
parents = tournamentSelection(population, fitness, tournamentSize);
% 生成子代
offspring = crossover(parents);
% 变异
offspring = mutation(offspring, mutationRate);
% 更新种群
population = offspring;
% 显示当前最优解
[~, idx] = max(fitness);
bestIndividual = population(idx, :);
disp(['Generation ', num2str(generation), ': Best Individual = ', num2str(bestIndividual)]);
end
% 锦标赛选择函数
function selectedParents = tournamentSelection(population, fitness, tournamentSize)
numParents = size(population, 1);
selectedParents = zeros(numParents, size(population, 2));
for i = 1:numParents
tournamentIndices = randperm(numParents, tournamentSize);
tournamentFitness = fitness(tournamentIndices);
[~, idx] = max(tournamentFitness);
selectedParents(i, :) = population(tournamentIndices(idx), :);
end
end
% 单点交叉函数
function offspring = crossover(parents)
numParents = size(parents, 1);
numGenes = size(parents, 2);
offspring = zeros(numParents, numGenes);
for i = 1:numParents
parent1 = parents(i, :);
parent2 = parents(mod(i, numParents) + 1, :);
crossoverPoint = randi(numGenes - 1);
offspring(i, :) = [parent1(1:crossoverPoint), parent2(crossoverPoint+1:end)];
end
end
% 变异函数
function mutatedOffspring = mutation(offspring, mutationRate)
numOffspring = size(offspring, 1);