遗传算法解决旅行商问题(TSP)三:主程序和执行结果

主程序如下:

clc;
clear;

CITYSIZE            = 10;       % 城市个数
POPSIZE             = 50;       % 种群个数
PC                  = 0.4;      % 交叉概率
PM                  = 0.05;     % 变异概率
MAXGEN              = 150;      % 迭代次数

LEAVING             = 5;        % 父代保留数量

gen = 0;
bestfit = zeros(1, MAXGEN);
bestlength = zeros(1, MAXGEN);

pos = [1 2 2 3 1 4 5 5 6 4; 1 1 2 2 3 4 4 5 5 6];       % 城市坐标
D = distancematrix(pos);                                % 城市距离矩阵

pop = initpop(POPSIZE, CITYSIZE);
len = callength(D, pop); 
fit = calfitness(len);
% 优化
while gen < MAXGEN
    childpop = selection(pop, fit, LEAVING);        % 选择
    leavingpop = selection(pop, fit, POPSIZE-LEAVING);
    pop = [leavingpop; childpop];                   % 保留一部分父代
    pop = crossover(pop, PC);                       % 交叉
    pop = mutation(pop, PM);                        % 变异
    gen = gen + 1;
    
    len = callength(D, pop);
    fit = calfitness(len);
    
    bestindex = bestindividual(fit);
    bestfit(1, gen) = fit(bestindex);
    bestlength(1, gen) = len(bestindex);
end

figure(1);
plot(1:MAXGEN, bestfit(1,:));
xlabel('进化代数');
ylabel('最优适应度值');
title('最优适应度值图');
grid on;

figure(2);
plot(1:MAXGEN, bestlength(1,:));
xlabel('进化代数');
ylabel('最优距离');
title('最优距离图');
grid on;

figure(3);
plot_route(pos, pop(bestindex,:));
grid on;

执行结果如下:

GA解TSP问题路径图
GA解TSP问题适应度值图
GA解TSP问题最优距离图

你可能感兴趣的:(遗传算法解决旅行商问题(TSP)三:主程序和执行结果)