问题描述
仿真过程
matlab源码
%此脚本要命名为func3.m
%%%%%%%%%%%%%%%%%%%%%%%%%适应度函数%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function result=func3(x,Xs,Xx)
m=0;
D=length(x);
for j=1:D
m=x(j)*2^(j-1)+m;
end
f=Xx+m*(Xs-Xx)/(2^D-1); %译码成十进制数
fit= f+6*sin(4*f)+9*cos(5*f);
result=fit;
%20201017lu注:该matlab代码成功在matlabR2019a运行
%%%%%%%%%%%%%%%%%离散粒子群算法求函数极值%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%初始化%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all; %清除所有变量
close all; %清图
clc; %清屏
N=100; %群体粒子个数
D=20; %粒子维数
T=200; %最大迭代次数
c1=1.5; %学习因子1
c2=1.5; %学习因子2
Wmax=0.8; %惯性权重最大值
Wmin=0.4; %惯性权重最小值
Xs=9; %位置最大值
Xx=0; %位置最小值
Vmax=10; %速度最大值
Vmin=-10; %速度最小值
%%%%%%%%%%%%%%%%初始化种群个体(限定位置和速度)%%%%%%%%%%%%%%%%
% x=randint(N,D); %随机获得二进制编码的初始种群
x=randi([0,1],N,D); %随机获得二进制编码的初始种群
v=rand(N,D) * (Vmax-Vmin)+Vmin;
%%%%%%%%%%%%%%%%%%初始化个体最优位置和最优值%%%%%%%%%%%%%%%%%%%
p=x;
pbest=ones(N,1);
for i=1:N
pbest(i)= func3(x(i,:),Xs,Xx);
end
%%%%%%%%%%%%%%%%%%%初始化全局最优位置和最优值%%%%%%%%%%%%%%%%%%
g=ones(1,D);
gbest=inf;
for i=1:N
if(pbest(i)<gbest)
g=p(i,:);
gbest=pbest(i);
end
end
gb=ones(1,T);
%%%%%%%%%%%按照公式依次迭代直到满足精度或者迭代次数%%%%%%%%%%%%%
for i=1:T
for j=1:N
%%%%%%%%%%%%%%更新个体最优位置和最优值%%%%%%%%%%%%%%%%%
if (func3(x(j,:),Xs,Xx)<pbest(j))
p(j,:)=x(j,:);
pbest(j)=func3(x(j,:),Xs,Xx);
end
%%%%%%%%%%%%%%%%更新全局最优位置和最优值%%%%%%%%%%%%%%%
if(pbest(j)<gbest)
g=p(j,:);
gbest=pbest(j);
end
%%%%%%%%%%%%%%%%计算动态惯性权重值%%%%%%%%%%%%%%%%%%%%
w=Wmax-(Wmax-Wmin)*i/T;
%%%%%%%%%%%%%%%%%跟新位置和速度值%%%%%%%%%%%%%%%%%%%%%
v(j,:)=w*v(j,:)+c1*rand*(p(j,:)-x(j,:))...
+c2*rand*(g-x(j,:));
%%%%%%%%%%%%%%%%%%%%边界条件处理%%%%%%%%%%%%%%%%%%%%%%
for ii=1:D
if (v(j,ii)>Vmax) | (v(j,ii)< Vmin)
v(j,ii)=rand * (Vmax-Vmin)+Vmin;
end
end
%%%%%%%%%%%%%%%%%%%%位置更新等式%%%%%%%%%%%%%%%%%%%%%%
vx(j,:)=1./(1+exp(-v(j,:)));
for jj=1:D
if vx(j,jj)>rand
x(j,jj)=1;
else
x(j,jj)=0;
end
end
end
%%%%%%%%%%%%%%%%%%%%记录历代全局最优值%%%%%%%%%%%%%%%%%%%%%
gb(i)=gbest;
end
g %最优个体 20201017lu注:二进制表示
m=0;
for j=1:D
m=g(j)*2^(j-1)+m;
end
f1=Xx+m*(Xs-Xx)/(2^D-1) %最优个体20201017lu注:将二进制转成实数表示
func3(g,Xs,Xx) %20201017lu添:函数最优值
figure
plot(gb)
xlabel('迭代次数');
ylabel('适应度值');
title('适应度进化曲线')
g =
0 1 0 1 1 0 0 1 1 0 1 0 0 0 1 1 1 1 1 0
f1 =
4.371687289893427e+00
ans =
-1.041986087784334e+01
中 智能优化算法及其MATLAB实例(第二版)[包子阳,余继周][电子工业出版社][2018年01月][9787121330308]
经过调试,随书所有代码均可以在matlabR2019a上成功运行https://mianbaoduo.com/o/bread/YZyVlp9v