clc,clear
%%
%define the function
fitness=inline('(2.1*(1-x+2*x.^2).*exp(-x.^2/2))+sin(x)+x','x');
%%
E0=0.001;
Max_num=50;
particlesize=30;
c1=0.5;
c2=1;
w=0.3;
vc=0.5;
vmax=0.6;
x=-5+10*rand(particlesize,1);
v=1*rand(particlesize,1);
%%
f=fitness(x);
personalbest_x=x;
personalbest_f=f;
[groupbest_f i]=max(personalbest_f);
groupbest_x=x(i);
for j=1:Max_num
v=w*v+c1*rand*(personalbest_x-x)+c2*rand*(groupbest_x*ones(particlesize,1)-x);
for kk=1:particlesize
if v(kk)>vmax
v(kk)=vmax;
else if v(kk)<-vmax
v(kk)=-vmax;
end
end
end
x=x+vc*v;
f=fitness(x);
for kk=1:particlesize
if f(kk)>personalbest_f(kk)
personalbest_f(kk)=f(kk);
personalbest_x(kk)=x(kk);
end
end
[groupbest_f i]=max(personalbest_f);
groupbest_x=x(i);
ddd(j)=groupbest_f;
end
str=num2str(groupbest_f)
%%
subplot(2,1,1)
x_0=-5:0.01:5;
f_0=fitness(x_0);
plot(x_0,f_0,'r','linewidth',2);
hold on
plot(groupbest_x,groupbest_f,'b+','linewidth',6);
legend('所求函数','最优解位置');
subplot(2,1,2)
plot(1:Max_num,ddd,'linewidth',2);
legend('最优解的变化');
xlabel('迭代次数');
ylabel(str);