主程序
主程序如下:
clear
clc
popsize = 30; % 種群規(guī)模
chromlength = 10; % 染色體長度
pc = 0.5; % 交叉概率
pm = 0.05; % 變異概率
maxgen = 20; % 最大迭代數(shù)
lx = 5; ux = 10;
bestfit = zeros(1, maxgen);
bestobjvalue = zeros(2, maxgen);
% 優(yōu)化
pop = initpop(popsize, chromlength);
objvalue = calobjvalue(pop, lx, ux);
fitvalue = calfitvalue(objvalue,'max');
for i = 1:maxgen
pop = selection(pop, fitvalue); % 選擇
pop = crossover(pop, pc); % 交叉
pop = mutation(pop, pm); % 變異
objvalue = calobjvalue(pop, lx, ux);
fitvalue = calfitvalue(objvalue, 'max');
bestindex = bestindividual(pop, fitvalue, 'max');
x = calx(pop, lx, ux);
bestfit(1, i) = fitvalue(bestindex);
bestobjvalue(1, i) = x(bestindex);
bestobjvalue(2, i) = objvalue(bestindex);
% fprintf('bestX: %f, bestY: %f\n', bestobjvalue(1, i), bestobjvalue(2, i));
end
figure(1);
fplot(@(x) 9 .* sin(5 .* x) + 8 .* cos(4 .* x), [lx, ux]);
hold on;
plot(bestobjvalue(1,:), bestobjvalue(2,:),'bo');
xlabel('x');
ylabel('y=9sin(5x)+8cos(4x)');
title('函數(shù)圖');
grid on;
hold off;
figure(2);
plot(1:maxgen, bestfit(1,:));
xlabel('進化代數(shù)');
ylabel('最優(yōu)適應(yīng)度值');
title('最優(yōu)適應(yīng)度值圖');
grid on;
bestX = bestobjvalue(1, end);
bestY = bestobjvalue(2, end);
fprintf('bestX: %f, bestY: %f\n', bestX, bestY);
執(zhí)行結(jié)果
執(zhí)行結(jié)果:bestX: 7.859238, bestY: 16.995125

函數(shù)圖

適應(yīng)值圖