%% 清空环境
clc
clear
clf
%% 参数初始化
sizepop = 50; %种群规模
dim = 30;
popmax = 2.048;
popmin = -2.048;
pa = 0.25;
beta = 3/2;
alpha = 0.01;
maxgen = 100000; %进化次数
errgoal = 10e-10;
sigma=(gamma(1+beta)*sin(pi*beta/2)/(gamma((1+beta)/2)*beta*2^((beta-1)/2)))^(1/beta);
%% Initializing variables
%随机产生一个种群
pop = (popmax-popmin).*rand(sizepop,dim) + popmin.*ones(sizepop,dim);
%计算适应度
myfunction = 'Rosenbrock';
fitness = feval(myfunction,pop);
%Rastrigin,Griewank,Schwefel,Rosenbrock,Shaffer,Ackley,Sphere;Levy
%% 个体极值和群体极值
iter = 1;
pbest = pop;
fpbest = fitness; %个体最佳适应度值
%环形拓朴结构
mpbest = pbest;
mpbest(1:sizepop-1,:) = pbest(2:sizepop,:);
mpbest(sizepop,:) = pbest(1,:);
[bestfitness bestindex]=min(fpbest);
gbest=pbest(bestindex,:); %全局最佳
fgbest=bestfitness; %全局最佳适应度值
meanpfit = zeros(1,maxgen); %占位
stgbest = zeros(1,maxgen); %占位
meanpfit(iter) = mean(fitness);
stgbest(iter) = min(fitness);
error = abs(meanpfit(iter) - stgbest(iter));
%绘图
figure(1)
hold on
plot(iter,meanpfit(iter),'ob',iter,stgbest(iter),'or');
title('最优个体适应度','fontsize',12);
legend('平均值','最优值');
xlabel('迭代次数','fontsize',12);ylabel('适应度','fontsize',12);
%% 迭代寻优
while (iter < maxgen) && (error > errgoal)
% 权重更新
iter = iter + 1;
% Levy flights by Mantegna's algorithm
u = randn(sizepop,dim)*sigma;
v = randn(sizepop,dim);
step = u./abs(v).^(1/beta);
% when the solution is the best solution, it remains unchanged.
matrgbest = repmat(gbest,sizepop,1);
stepsize = alpha*step.*(pbest-matrgbest);
% Now the actual random walks or flights
pop = pbest + stepsize.*randn(sizepop,dim);
pop(pop>popmax) = (popmax-popmin).*rand + popmin;%(popmax-popmin).*rand + popmin;
pop(pop<popmin) = (popmax-popmin).*rand + popmin;%(popmax-popmin).*rand + popmin;
% 适应度值更新
fitness = feval(myfunction,pop);
% 修改每个粒子历史上的最优位置
changerows = fitness < fpbest; % 逻辑矩阵
pbest(changerows,:) = pop(changerows,:);
fpbest(changerows) = fitness(changerows); % 修改个体粒子历史上的最优适应度
%随机游走
K = rand(sizepop,dim) > pa;
stepsize = rand*(pbest(randperm(sizepop),:) - pbest(randperm(sizepop),:));
pop = pbest + stepsize.*K;
pop(pop>popmax) = (popmax-popmin).*rand + popmin;
pop(pop<popmin) = (popmax-popmin).*rand + popmin;
% 适应度值更新
fitness = feval(myfunction,pop);
% 修改每个粒子历史上的最优位置
changerows = fitness < fpbest; % 逻辑矩阵
pbest(changerows,:) = pop(changerows,:);
fpbest(changerows) = fitness(changerows); % 修改个体粒子历史上的最优适应度
%环形拓朴结构
mpbest(1:sizepop-1,:) = pbest(2:sizepop,:);
mpbest(sizepop,:) = pbest(1,:);
% 修改种群全局最优粒子
[bestfitness bestindex] = min(fpbest);
gbest = pbest(bestindex,:);
fgbest = bestfitness;
% 记录每次迭代平均和最优适应度
meanpfit(iter) = mean(fpbest);
stgbest(iter) = min(fpbest);
error = abs(meanpfit(iter) - stgbest(iter));
%绘图
if mod(iter,500)==0
plot(iter,meanpfit(iter),'ob',iter,stgbest(iter),'or');
drawnow;
end
end
%% 结果分析
disp('gbest is:')
fprintf(' %8.4e \n',gbest')
disp('fgbest is:')
fprintf('%8.4e \n',fgbest)
评论0