matlab 遗传算法代码
时间: 2024-05-03 19:15:18 浏览: 107
matlab遗传算法代码
遗传算法是一种模拟自然进化过程的优化算法,常用于解决复杂的优化问题。在MATLAB中,可以使用遗传算法工具箱来实现遗传算法。
以下是一个简单的MATLAB遗传算法代码示例:
```matlab
% 定义适应度函数
fitnessFunc = @(x) x^2;
% 定义遗传算法参数
populationSize = 50; % 种群大小
geneLength = 10; % 基因长度
mutationRate = 0.01; % 变异率
crossoverRate = 0.8; % 交叉率
maxGenerations = 100; % 最大迭代次数
% 初始化种群
population = randi([0, 1], populationSize, geneLength);
% 迭代优化
for generation = 1:maxGenerations
% 计算适应度值
fitness = arrayfun(fitnessFunc, population);
% 选择操作
selectedPopulation = selection(population, fitness);
% 交叉操作
offspringPopulation = crossover(selectedPopulation, crossoverRate);
% 变异操作
mutatedPopulation = mutation(offspringPopulation, mutationRate);
% 更新种群
population = mutatedPopulation;
end
% 找到最优解
bestFitness = max(fitness);
bestIndividual = population(find(fitness == bestFitness, 1), :);
% 输出结果
disp(['最优解:', num2str(bestIndividual)]);
disp(['最优适应度:', num2str(bestFitness)]);
% 选择操作函数
function selectedPopulation = selection(population, fitness)
% 使用轮盘赌选择算子
totalFitness = sum(fitness);
probabilities = fitness / totalFitness;
cumulativeProbabilities = cumsum(probabilities);
selectedPopulation = zeros(size(population));
for i = 1:size(population, 1)
r = rand();
selectedIndividualIndex = find(cumulativeProbabilities >= r, 1);
selectedPopulation(i, :) = population(selectedIndividualIndex, :);
end
end
% 交叉操作函数
function offspringPopulation = crossover(selectedPopulation, crossoverRate)
offspringPopulation = zeros(size(selectedPopulation));
for i = 1:2:size(selectedPopulation, 1)
if rand() < crossoverRate
% 随机选择交叉点
crossoverPoint = randi([1, size(selectedPopulation, 2) - 1]);
% 进行交叉操作
offspringPopulation(i, :) = [selectedPopulation(i, 1:crossoverPoint), selectedPopulation(i+1, crossoverPoint+1:end)];
offspringPopulation(i+1, :) = [selectedPopulation(i+1, 1:crossoverPoint), selectedPopulation(i, crossoverPoint+1:end)];
else
% 不进行交叉操作,直接复制父代个体
offspringPopulation(i, :) = selectedPopulation(i, :);
offspringPopulation(i+1, :) = selectedPopulation(i+1, :);
end
end
end
% 变异操作函数
function mutatedPopulation = mutation(offspringPopulation, mutationRate)
mutatedPopulation = offspringPopulation;
for i = 1:size(mutatedPopulation, 1)
for j = 1:size(mutatedPopulation, 2)
if rand() < mutationRate
% 变异操作,将基因取反
mutatedPopulation(i, j) = ~mutatedPopulation(i, j);
end
end
end
end
```
这段代码实现了一个简单的遗传算法,用于求解函数 f(x) = x^2 的最大值。其中,适应度函数为 f(x),种群大小为 50,基因长度为 10,变异率为 0.01,交叉率为 0.8,最大迭代次数为 100。代码中的选择操作使用了轮盘赌选择算子,交叉操作使用了单点交叉,变异操作将基因取反。
阅读全文