自适应遗传算法MATLAB代码
时间: 2023-07-02 21:24:28 浏览: 105
以下是一个简单的 MATLAB 实现自适应遗传算法的代码示例:
```
% 自适应遗传算法
% 目标函数为 Rosenbrock 函数
pop_size = 100; % 种群大小
chrom_len = 10; % 染色体长度
max_generation = 100; % 最大迭代次数
pc = 0.8; % 交叉概率
pm = 0.01; % 变异概率
% 初始化种群
pop = rand(pop_size, chrom_len);
for i = 1:max_generation
% 计算适应度值
fitness = 1 ./ (1 + rosenbrock(pop));
% 计算选择概率
p = fitness / sum(fitness);
% 计算适应度比例
k = 1 / max(fitness);
% 计算个体适应度比例
pk = fitness / sum(fitness);
% 计算群体适应度比例
sk = (pk - min(pk)) / (sum(pk) - min(pk));
% 计算交叉概率和变异概率
pc = 0.8 * sk;
pm = 0.01 * k;
% 选择操作
pop_new = zeros(size(pop));
for j = 1:pop_size
idx1 = roulette_wheel_selection(p);
idx2 = roulette_wheel_selection(p);
chrom1 = pop(idx1, :);
chrom2 = pop(idx2, :);
pop_new(j, :) = crossover(chrom1, chrom2, pc);
end
% 变异操作
pop_new = mutation(pop_new, pm);
% 更新种群
pop = pop_new;
end
% 打印最优解
[~, idx] = max(fitness);
best_chrom = pop(idx, :);
best_fitness = fitness(idx);
disp(['Best solution: ', num2str(best_chrom)]);
disp(['Best fitness: ', num2str(best_fitness)]);
% Rosenbrock 函数
function f = rosenbrock(x)
x1 = x(:, 1:end-1);
x2 = x(:, 2:end);
f = sum(100 .* (x2 - x1 .^ 2) .^ 2 + (1 - x1) .^ 2, 2);
end
% 轮盘赌选择
function idx = roulette_wheel_selection(p)
r = rand;
c = cumsum(p);
idx = find(r <= c, 1, 'first');
end
% 交叉操作
function chrom = crossover(chrom1, chrom2, pc)
r = rand(size(chrom1));
chrom = chrom1 .* (r <= pc) + chrom2 .* (r > pc);
end
% 变异操作
function pop = mutation(pop, pm)
mask = rand(size(pop)) < pm;
pop = pop + mask .* randn(size(pop));
end
```
需要注意的是,以上代码仅供参考,实际应用中可能需要根据具体问题进行适当的修改和优化。
阅读全文