function main
% this is particle swarm optimization program
% n:dimension of variable; m:number of particle
% x:m*n matrix; v:m*n matrix
% pbx:m*n matrix; gbx:1*n matrix
% pbf:m*1 matrix; gbf:number
clear all;
clc
tic;
E0=0.001; %permitted error
MaxNum=100; %iteration number of every time
%
n=1;
m=50;
c1=2;
c2=2;
w=1;
vmax=0.5;
rand('state',sum(100*clock));
% random m particle
x=-4+8*rand(m,n);
v=2*rand(m,n);
% compute fitness
for i=1:m
for j=1:n
f(i)=fitness(x(i,j));
end
end
% find individual max and global max
pbx=x;
pbf=f;
[gbf i]=min(pbf);
gbx=pbx(i,:);
% start loop
k=1;
while k<=MaxNum
for i=1:m
for j=1:n
f(i)=fitness(x(i,j));
end
if f(i)<pbf(i)
pbf(i)=f(i);
pbx(i,:)=x(i,:);
end
end
[gbf i]=min(pbf);
gbx=pbx(i,:);
for i=1:m
v(i,:)=w*v(i,:)+c1*rand*(pbx(i,:)-x(i,:))+c2*rand*(gbx-x(i,:));
for j=1:n
if v(i,j)>vmax
v(i,j)=vmax;
elseif v(i,j)<-vmax
v(i,j)=-vmax;
end
end
x(i,:)=x(i,:)+v(i,:);
end
if abs(gbf)<E0,break,end
k=k+1;
end
% Display the results
disp('the maximum value is');1/gbf-1
disp('and the corresponding coordinate is');gbx
x=-4:0.01:4;
y=1.1*(1-x+2*x.^2).*exp(-x.^2/2);
plot(x,y);
hold on;
plot(gbx,1/gbf-1,'r*');
hold off
toc