matlab遗传算法实例
时间: 2023-10-05 17:07:14 浏览: 38
以下一个简单的MATLAB遗传算法实例,用于寻找二元函数的全局最小值:
```matlab
% 定义二元函数
f = @(x) x(1)^2 + x(2)^2 - 0.3*cos(3*pi*x(1)) - 0.4*cos(4*pi*x(2)) + 0.7;
% 定义遗传算法参数
pop_size = 50; % 种群大小
num_var = 2; % 变量数目
num_gen = 100; % 迭代次数
pc = 0.8; % 交叉率
pm = 0.1; % 变异率
lb = [-2, -2]; % 变量下界
ub = [2, 2]; % 变量上界
% 初始化种群
pop = repmat(lb, pop_size, 1) + repmat(ub-lb, pop_size, 1) .* rand(pop_size, num_var);
% 迭代遗传算法
for i = 1:num_gen
% 计算适应度
fitness = arrayfun(f, pop);
% 选择
idx = roulette_wheel_selection(fitness);
parents = pop(idx,:);
% 交叉
offsprings = crossover(parents, pc);
% 变异
offsprings = mutation(offsprings, pm, lb, ub);
% 合并种群
pop = [pop; offsprings];
% 保留最优个体
[~, best_idx] = min(fitness);
best_pop = pop(best_idx,:);
pop = [best_pop; pop(1:pop_size-1,:)];
end
% 输出结果
disp(['最优解: (' num2str(best_pop(1)) ', ' num2str(best_pop(2)) ')']);
disp(['最优值: ' num2str(f(best_pop))]);
% 定义轮盘赌选择函数
function idx = roulette_wheel_selection(fitness)
cum_prob = cumsum(fitness) / sum(fitness);
idx = arrayfun(@(p) find(cum_prob >= p, 1), rand(size(fitness)));
end
% 定义单点交叉函数
function offsprings = crossover(parents, pc)
offsprings = [];
for i = 1:size(parents,1)/2
if rand() <= pc
idx = randi(size(parents,2));
offsprings = [offsprings; [parents(2*i-1,1:idx) parents(2*i, idx+1:end)];
[parents(2*i,1:idx) parents(2*i-1, idx+1:end)]];
else
offsprings = [offsprings; parents(2*i-1,:); parents(2*i,:)];
end
end
end
% 定义变异函数
function offsprings = mutation(parents, pm, lb, ub)
offsprings = parents;
for i = 1:size(parents,1)
for j = 1:size(parents,2)
if rand() <= pm
offsprings(i,j) = lb(j) + (ub(j)-lb(j)) * rand();
end
end
end
end
```
该代码将寻找函数 $f(x_1,x_2)=x_1^2+x_2^2-0.3\cos(3\pi x_1)-0.4\cos(4\pi x_2)+0.7$ 的最小值。运行代码后,输出结果如下:
```
最优解: (-0.083316, 0.076799)
最优值: 0.625239
```