1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| clc, clear, close all
N = 100; N_chrom = 2; iter = 2000; mut = 0.2; acr = 0.2; best = 1; chrom_range = [-10 -10;10 10]; chrom = zeros(N, N_chrom); fitness = zeros(N, 1); fitness_ave = zeros(1, iter); fitness_best = zeros(1, iter); chrom_best = zeros(1, N_chrom+1);
chrom = Initialize(N, N_chrom, chrom_range); fitness = CalFitness(chrom, N, N_chrom); chrom_best = FindBest(chrom, fitness, N_chrom); fitness_best(1) = chrom_best(end); fitness_ave(1) = CalAveFitness(fitness); for t = 2:iter chrom = MutChrom(chrom, mut, N, N_chrom, chrom_range, t, iter); chrom = AcrChrom(chrom, acr, N, N_chrom); fitness = CalFitness(chrom, N, N_chrom); chrom_best_temp = FindBest(chrom, fitness, N_chrom); if chrom_best_temp(end)>chrom_best(end) chrom_best = chrom_best_temp; end [chrom, fitness] = ReplaceWorse(chrom, chrom_best, fitness); fitness_best(t) = chrom_best(end); fitness_ave(t) = CalAveFitness(fitness); end
figure(1) plot(1:iter, fitness_ave, 'r', 1:iter, fitness_best, 'b') grid on legend('平均适应度', '最优适应度') e = PlotModel(chrom_best)
disp(['最优染色体为', num2str(chrom_best(1:end-1))]) disp(['最优适应度为', num2str(chrom_best(end))])
|