写一份matlab遗传算法
时间: 2023-11-13 13:55:53 浏览: 69
好的,以下是一个简单的 Matlab 遗传算法的实现:
```matlab
% 遗传算法实现
% 目标函数:f(x) = x^2 + 2x + 1
% 求解区间:[-10, 10]
% 种群大小:50
% 交叉概率:0.8
% 变异概率:0.01
% 迭代次数:100
pop_size = 50; % 种群大小
chrom_length = 16; % 染色体长度
pc = 0.8; % 交叉概率
pm = 0.01; % 变异概率
max_gen = 100; % 迭代次数
% 初始化种群
pop = round(rand(pop_size, chrom_length));
for i = 1:max_gen
% 计算适应度
x = bin2dec(num2str(pop)); fitness = x.^2 + 2*x + 1;
% 轮盘赌选择
p_fit = fitness / sum(fitness);
cum_fit = cumsum(p_fit);
new_pop = zeros(size(pop));
for j = 1:pop_size
idx = find(cum_fit >= rand, 1);
new_pop(j,:) = pop(idx,:);
end
% 交叉操作
for j = 1:2:pop_size
if rand < pc
cpoint = randi([1, chrom_length-1]);
temp1 = [new_pop(j,1:cpoint), new_pop(j+1,cpoint+1:end)];
temp2 = [new_pop(j+1,1:cpoint), new_pop(j,cpoint+1:end)];
new_pop(j,:) = temp1;
new_pop(j+1,:) = temp2;
end
end
% 变异操作
for j = 1:pop_size
for k = 1:chrom_length
if rand < pm
new_pop(j,k) = 1 - new_pop(j,k);
end
end
end
% 更新种群
pop = new_pop;
end
% 输出最优解
x = bin2dec(num2str(pop(1,:)));
y = x^2 + 2*x + 1;
fprintf('最优解:x=%d, y=%d\n', x, y);
```
阅读全文