clc
clear
close all
r = 0.6;%光强吸收系数
a = 0.2;%扰动系数
d = 2;%变量个数
gen=100; %设置进化代数
popsize=200; %设置种群规模大小
pop = 10*rand(popsize,d)-5;%生成初始种群
xmax = [5 5];%变量上限
xmin = [-5 -5];%变量下限
fitness = fun(pop);%计算适应度
[best_fitness,mx] = max(fitness);%最佳适应度`q
funtu(pop)%画图1
best_in_history = zeros(gen,1); %初始化全局历史最优解
best_in_history(1,1) = best_fitness;
bestx = zeros(gen,d);
bestx = pop(mx,:);
for ij = 1:gen
for ii = 1:popsize
for jj = 1:popsize
if fitness(ii)<fitness(jj)%比较荧光亮度
dij = fund(pop(ii,:),pop(jj,:));%计算距离
pop(ii,:) = pop(ii,:)+ fitness(jj)*exp(-r*dij^2)*(pop(jj,:)-pop(ii,:))+a*(0.2*rand(1,d)-0.1);%更新位置
end
end
end
for ii = 1:popsize
for jj = 1:d
if pop(ii,jj)>xmax(jj)
pop(ii,jj) = xmax(jj);
elseif pop(ii,jj)<xmin(jj)
pop(ii,jj) = xmin(jj);
end
end
end
fitness = fun(pop);%计算适应度
[best_fitness1,mx] = max(fitness);%最佳适应度
if best_fitness<best_fitness1
best_fitness = best_fitness1;
bestx = pop(mx,:);
end
pop(mx,:) = pop(mx,:) + (rand(1,d)-0.5);
best_in_history(ij,1) = best_fitness;
end
figure (2)
plot(1./best_in_history,'k-')
xlabel('迭代次数')
ylabel('函数值')
title('萤火虫求解函数极值收敛曲线')
funtuz(bestx,pop)