主程序如下:
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);endfigure(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;
执行结果如下: