请提供matlab遗传算法求最大值代码
时间: 2023-09-16 10:07:20 浏览: 78
以下是一个简单的matlab遗传算法求最大值的代码示例:
% 遗传算法求解最大值问题
% 初始化参数
pop_size = 50; % 种群大小
chrom_len = 10; % 染色体长度
max_gen = 100; % 最大迭代次数
pc = 0.7; % 交叉概率
pm = 0.01; % 变异概率
min_val = -5; % 变量最小值
max_val = 5; % 变量最大值
% 生成初始种群
pop = randi([0, 1], pop_size, chrom_len);
for i = 1:max_gen
% 计算适应度
x = bin2dec(num2str(pop));
x = x / (2^chrom_len-1) * (max_val-min_val) + min_val;
f = sin(10*pi*x) ./ (2*x) + (x-1).^4;
f(isnan(f)) = 0;
fitness = f;
% 选择操作
fitness_sum = sum(fitness);
fitness_prob = fitness / fitness_sum;
cum_prob = cumsum(fitness_prob);
new_pop = zeros(pop_size, chrom_len);
for j = 1:pop_size
r = rand();
idx = find(cum_prob >= r, 1, 'first');
new_pop(j,:) = pop(idx,:);
end
% 交叉操作
for j = 1:pop_size/2
if rand() < pc
idx1 = randi([1, pop_size], 1, 1);
idx2 = randi([1, pop_size], 1, 1);
while idx2 == idx1
idx2 = randi([1, pop_size], 1, 1);
end
c = randi([1, chrom_len], 1, 1);
new_pop(j*2-1,:) = [new_pop(idx1,1:c), new_pop(idx2,c+1:end)];
new_pop(j*2,:) = [new_pop(idx2,1:c), new_pop(idx1,c+1:end)];
end
end
% 变异操作
for j = 1:pop_size
for k = 1:chrom_len
if rand() < pm
new_pop(j,k) = 1 - new_pop(j,k);
end
end
end
% 更新种群
pop = new_pop;
% 计算最优解
[~, idx] = max(fitness);
x_best = bin2dec(num2str(pop(idx,:))) / (2^chrom_len-1) * (max_val-min_val) + min_val;
f_best = fitness(idx);
% 输出结果
fprintf('Generation %d: Best solution = %f, Fitness = %f\n', i, x_best, f_best);
end
阅读全文