遗传算法的Matlab代码
时间: 2023-12-24 08:23:00 浏览: 35
以下是一个简单的遗传算法的Matlab代码:
%% 遗传算法的Matlab代码
clc; clear all; close all;
% 定义参数
popSize = 50; % 种群大小
chromLen = 20; % 每个染色体的长度
pc = 0.6; % 交叉概率
pm = 0.01; % 变异概率
gen = 100; % 迭代次数
% 随机初始化种群
pop = round(rand(popSize, chromLen));
% 计算适应度
fit = zeros(popSize, 1);
for i = 1:popSize
fit(i) = sum(pop(i,:));
end
% 迭代
for t = 1:gen
% 选择
[selPop, selFit] = selection(pop, fit);
% 交叉
croPop = crossover(selPop, pc);
% 变异
mutPop = mutation(croPop, pm);
% 合并
pop = [selPop; mutPop];
fit = [selFit; zeros(size(mutPop,1),1)];
for i = 1:size(pop,1)
fit(i) = sum(pop(i,:));
end
% 最优解
[bestFit, bestIdx] = max(fit);
bestChrom = pop(bestIdx,:);
% 显示结果
fprintf('第%d代:最优解为%d\n', t, bestFit);
end
% 选择函数
function [selPop, selFit] = selection(pop, fit)
% 轮盘赌选择
p = fit/sum(fit);
psum = cumsum(p);
selPop = zeros(size(pop));
selFit = zeros(size(fit));
for i = 1:size(pop,1)
idx = find(psum>=rand(),1);
selPop(i,:) = pop(idx,:);
selFit(i) = fit(idx);
end
end
% 交叉函数
function croPop = crossover(selPop, pc)
% 单点交叉
croPop = zeros(size(selPop));
for i = 1:size(selPop,1)/2
if rand()<pc
croIdx = randi(size(selPop,2));
croPop(2*i-1,:) = [selPop(2*i-1,1:croIdx) selPop(2*i,croIdx+1:end)];
croPop(2*i,:) = [selPop(2*i,1:croIdx) selPop(2*i-1,croIdx+1:end)];
else
croPop(2*i-1,:) = selPop(2*i-1,:);
croPop(2*i,:) = selPop(2*i,:);
end
end
end
% 变异函数
function mutPop = mutation(croPop, pm)
% 单点变异
mutPop = croPop;
for i = 1:size(croPop,1)
for j = 1:size(croPop,2)
if rand()<pm
mutPop(i,j) = ~mutPop(i,j);
end
end
end
end
相关推荐
![](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)