遗传算法求函数极值matlab
时间: 2023-12-06 22:04:19 浏览: 94
以下是使用遗传算法求解函数极值的Matlab代码示例:
```matlab
% 定义适应度函数
function f = fitness(x)
f = -x^2 + 2*x + 1;
end
% 定义遗传法参数
popsize = 50; % 种群大小
maxgen = 100; % 最大迭代次数
Pcrossover = 0.8; % 交叉概率
Pmutation = 0.1; % 变异概率
x_min = -10; % 自变量x的最小值
x_max = 10; % 自变量x的最大值
% 初始化种群
pop = zeros(popsize, 2);
for i = 1:popsize
pop(i, 1) = x_min + (x_max - x_min) * rand;
pop(i, 2) = fitness(pop(i, 1));
end
% 迭代
for gen = 1:maxgen
% 选择
[parent1, parent2] = selection(pop);
% 交叉
[child1, child2] = crossover(parent1, parent2, Pcrossover, x_min, x_max);
% 变异
child1 = mutation(child1, Pmutation, x_min, x_max);
child2 = mutation(child2, Pmutation, x_min, x_max);
% 计算适应度
child1(2) = fitness(child1(1));
child2(2) = fitness(child2(1));
% 替换
pop = replacement(pop, child1, child2);
end
% 输出最优解
[~, idx] = max(pop(:, 2));
x_opt = pop(idx, 1);
f_opt = pop(idx, 2);
fprintf('最优解:x = %f, f(x) = %f\n', x_opt, f_opt);
```
阅读全文