0
点赞
收藏
分享

微信扫一扫

遗传算法(GA)——Matlab代码

上善若水山西太原 2022-03-19 阅读 28
算法
clear
clc
close all
f = @(x) x.*sin(x); % 函数表达式
figure(1)
ezplot(f, [0, 20]) % 画出函数图像
N = 50; % 种群上限
ger = 50; % 迭代次数
L = 5; % 基因长度
pc = 0.8; % 交叉概率
pm = 0.1; % 变异概率
dco = [10000; 1000; 100; 10 ;1]; % 解码器
dna = randi([0, 9], [N, L]); % 基因
hold on
x = dna * dco / 99999 * 20; % 对初始种群解码
plot(x, f(x),'ko','linewidth',3) % 画出初始解的位置
x1 = zeros(N, L); % 初始化子代基因
x2 = x1; % 同上
x3 = x1; % 同上
fi = zeros(N, 1); % 初始化适应度
record = zeros(2,ger);
for epoch = 1: ger % 进化代数为100
    for i = 1: N % 交叉操作
        if rand < pc
            d = randi(N); % 确定另一个交叉的个体
            m = dna(d,:); % 确定另一个交叉的个体
            d = randi(L-1); % 确定交叉断点
            x1(i,:) = [dna(i,1:d), m(d+1:L)]; % 新个体 1
            x2(i,:) = [m(1:d), dna(i,d+1:L)]; % 新个体 2
        end
    end
    x3 = dna;
    for i = 1: N % 变异操作
        if rand < pm
            x3(i,randi(L)) = randi([0, 9]);
        end
    end
    dna = [dna; x1; x2; x3]; % 合并新旧基因
    fi = f(dna * dco / 99999 * 20); % 计算适应度
    dna = [dna, fi];
    dna = flipud(sortrows(dna, L + 1)); % 对适应度进行排名
    while size(dna, 1) > N % 自然选择
        d = randi(size(dna, 1));
        if rand < (d - 1) / size(dna, 1)
            dna(d,:) = [];
            fi(d, :) = [];
        end
    end
    dna = dna(:, 1:L);
    record(1,epoch) = fi(1);
    record(2,epoch) = mean(fi);
end
x = dna * dco / 99999 * 20; % 对最终种群解码
figure(2)
plot([0:0.01:20],f([0:0.01:20]),'b-',x, f(x),'ro','linewidth',1)
% 画出最终解的位置
title('最终解')
figure(3)
plot(1:ger,record(1,:),'b-',1:ger,record(2,:),'r-')
title('过程曲线')
legend('最优值','种群均值','Location','southeast')
disp(['最优解为x=',num2str(x(1))]);
disp(['最优值为y=',num2str(fi(1))]);
举报

相关推荐

GA遗传算法

遗传算法[GA]

GA遗传算法实现记录

0 条评论