遗传算法matlab程序
时间: 2023-06-14 16:06:02 浏览: 38
以下是一个简单的遗传算法Matlab程序示例:
```matlab
% 遗传算法示例程序
clc;
clear;
% 定义问题
fun = @(x) x.^2 + 2*x - 3;
% 定义参数
popSize = 50; % 种群大小
numGen = 100; % 迭代次数
pc = 0.8; % 交叉概率
pm = 0.05; % 变异概率
numVar = 1; % 变量个数
lb = -10; % 变量下限
ub = 10; % 变量上限
% 初始化种群
pop = rand(popSize, numVar) * (ub - lb) + lb;
% 迭代
for i = 1:numGen
% 评估适应度
fit = fun(pop);
% 选择
parents = selection(pop, fit);
% 交叉
offspring = crossover(parents, pc);
% 变异
offspring = mutation(offspring, pm, lb, ub);
% 合并种群
pop = [pop; offspring];
% 保留种群大小
pop = pop(1:popSize, :);
end
% 输出结果
[minFit, minIdx] = min(fun(pop));
minX = pop(minIdx, :);
disp(['最小值:', num2str(minFit)]);
disp(['最小值对应的x:', num2str(minX)]);
% 选择函数
function parents = selection(pop, fit)
% 锦标赛选择
popSize = size(pop, 1);
numParents = size(pop, 1);
parents = zeros(numParents, size(pop, 2));
for i = 1:numParents
p1 = randi(popSize);
p2 = randi(popSize);
if fit(p1) < fit(p2)
parents(i, :) = pop(p1, :);
else
parents(i, :) = pop(p2, :);
end
end
end
% 交叉函数
function offspring = crossover(parents, pc)
% 单点交叉
numParents = size(parents, 1);
numVar = size(parents, 2);
offspring = zeros(numParents, numVar);
for i = 1:numParents/2
if rand() < pc
crossoverPoint = randi(numVar-1);
offspring(2*i-1,:) = [parents(2*i-1, 1:crossoverPoint), parents(2*i, crossoverPoint+1:end)];
offspring(2*i,:) = [parents(2*i, 1:crossoverPoint), parents(2*i-1, crossoverPoint+1:end)];
else
offspring(2*i-1,:) = parents(2*i-1, :);
offspring(2*i,:) = parents(2*i, :);
end
end
end
% 变异函数
function offspring = mutation(offspring, pm, lb, ub)
% 均匀变异
numOffspring = size(offspring, 1);
numVar = size(offspring, 2);
offspring = reshape(offspring, [], 1);
for i = 1:length(offspring)
if rand() < pm
offspring(i) = rand() * (ub - lb) + lb;
end
end
offspring = reshape(offspring, numOffspring, numVar);
end
```
此程序实现了一个简单的遗传算法,用于求解函数 f(x) = x^2 + 2x - 3 在区间 [-10, 10] 上的最小值。程序采用了锦标赛选择、单点交叉和均匀变异三种标准的遗传算法操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)