写一个遗传算法的代码,用MATLAB语言
时间: 2024-01-22 17:19:45 浏览: 28
以下是基本的遗传算法MATLAB代码:
```matlab
% 遗传算法示例代码
% 适应度函数:f(x) = x*sin(10*pi*x)+2.0
% 目标:求函数最大值
% 约束条件:0≤x≤1
clear;
clc;
% 设置参数
pop_size = 50; % 种群大小
chrom_length = 22; % 染色体长度
pc = 0.8; % 交叉概率
pm = 0.01; % 变异概率
max_gen = 100; % 最大迭代次数
% 初始化种群
pop = round(rand(pop_size, chrom_length));
% 迭代
for gen = 1:max_gen
% 计算适应度值
fit_value = zeros(pop_size, 1);
for i = 1:pop_size
x = bin2dec(num2str(pop(i, :))) / (2^chrom_length-1);
fit_value(i) = x*sin(10*pi*x)+2.0;
end
% 选择
[fit_sort, fit_index] = sort(fit_value, 'descend');
best_individual = pop(fit_index(1), :);
sum_fit = sum(fit_sort);
accum_fit = cumsum(fit_sort);
roulette_index = zeros(pop_size, 1);
for i = 1:pop_size
roulette_index(i) = find(accum_fit >= sum_fit*rand, 1);
end
pop = pop(roulette_index, :);
% 交叉
for i = 1:2:pop_size
if rand < pc
cpoint = round(rand*chrom_length);
temp1 = [pop(i, 1:cpoint), pop(i+1, cpoint+1:end)];
temp2 = [pop(i+1, 1:cpoint), pop(i, cpoint+1:end)];
pop(i, :) = temp1;
pop(i+1, :) = temp2;
end
end
% 变异
for i = 1:pop_size
for j = 1:chrom_length
if rand < pm
pop(i, j) = ~pop(i, j);
end
end
end
end
% 输出结果
best_x = bin2dec(num2str(best_individual)) / (2^chrom_length-1);
best_y = best_x*sin(10*pi*best_x)+2.0;
fprintf('x = %f\n', best_x);
fprintf('y = %f\n', best_y);
```
这个代码演示了如何用遗传算法来求函数 $f(x) = x \sin(10\pi x) + 2.0$ 的最大值,其中 $0\le x\le 1$ 是约束条件。
相关推荐
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)