遗传麻雀算法的matlab代码
时间: 2023-12-01 21:43:21 浏览: 20
以下是遗传麻雀算法的MATLAB代码:
```matlab
% 遗传麻雀算法
% 适应度函数
function y = fitness(x)
y = x^2;
end
% 遗传麻雀算法主函数
function [best_x, best_y] = genetic_sparrow()
% 初始化参数
pop_size = 50; % 种群大小
chrom_length = 20; % 染色体长度
pc = 0.8; % 交叉概率
pm = 0.01; % 变异概率
max_gen = 100; % 最大迭代次数
gen = 1; % 当前迭代次数
pop = randi([0, 1], pop_size, chrom_length); % 初始化种群
best_x = []; % 最优解
best_y = []; % 最优解对应的适应度值
% 迭代
while gen <= max_gen
% 计算适应度值
fitness_values = arrayfun(@fitness, bi2de(pop));
% 选择
[parent1, parent2] = selection(pop, fitness_values);
% 交叉
[child1, child2] = crossover(parent1, parent2, pc);
% 变异
child1 = mutation(child1, pm);
child2 = mutation(child2, pm);
% 更新种群
pop = [pop; child1; child2];
% 保留最优解
[best_fitness, best_index] = max(fitness_values);
best_x = [best_x; bi2de(pop(best_index, :))];
best_y = [best_y; best_fitness];
% 精英保留
[~, elite_index] = max(fitness_values);
pop(elite_index, :) = [];
% 更新迭代次数
gen = gen + 1;
end
end
% 选择函数
function [parent1, parent2] = selection(pop, fitness_values)
% 轮盘赌选择
fitness_sum = sum(fitness_values);
fitness_prob = fitness_values / fitness_sum;
fitness_cumprob = cumsum(fitness_prob); parent1_index = find(fitness_cumprob >= rand(), 1);
parent2_index = find(fitness_cumprob >= rand(), 1);
parent1 = pop(parent1_index, :);
parent2 = pop(parent2_index, :);
end
% 交叉函数
function [child1, child2] = crossover(parent1, parent2, pc)
% 单点交叉
if rand() < pc
cross_point = randi(length(parent1));
child1 = [parent1(1:cross_point), parent2(cross_point+1:end)];
child2 = [parent2(1:cross_point), parent1(cross_point+1:end)];
else
child1 = parent1;
child2 = parent2;
end
end
% 变异函数
function child = mutation(parent, pm)
% 每个基因以一定概率翻转
child = parent;
for i = 1:length(parent)
if rand() < pm
child(i) = ~parent(i);
end
end
end
```