clc;
clear all;
a=(-2:0.01:2);
b=(-1:0.01:3);
for x=1:401
for y=1:401
z(x,y)=(1-a(x))^2+100*(b(y)-a(x)^2)^2;
end
end
%disp(z);
mesh(z);
n=401; % Population size
dim=2;
p(1:n,1)=-2; q(1:n,1)=2; %bounds on variable x
p(1:n,2)=-1; q(1:n,2)=3; %bounds on variable y
r=(q-p);
u=p; v=q;
s=(v-u)/4; %initial velocities are 1/4 of parameter space size
%Random initialization of positions and velocities
pos=p+r.*rand(n,dim);
vel=s.*rand(n,dim);
%Evaluate objective for all particles
for x=1:401
obfun(x,1)=(1-pos(x,1))^2+100*(pos(x,2)-pos(x,1)^2)^2;
end
%disp(obfun);
%Find gbest and pbest
[fgbest,igbest]=min(obfun);
gbest=pos(igbest,:)
pbest=pos
fpbest=obfun
%iterate
itmax=100; % Maximum iterations; total evaluated function will be 401X100
c1=1.05; c2=1.05;
wmax=1; wmin=0.3; %set to same value for constant w
w=linspace(wmax,wmin,itmax); %linear variation of w
for it=1:itmax;
%Update velocities and positions
vel(1:n,1:dim)=w(it)*vel(1:n,1:dim)+c1*rand*(pbest(1:n,1:dim)-pos(1:n,1:dim))+c2*rand*(repmat(gbest,n,1)-pos(1:n,1:dim));
pos(1:n,1:dim)=pos(1:n,1:dim)+vel(1:n,1:dim);
%Evaluate objectives
for x=1:401
obfun(x,1)=(1-pos(x,1))^2+100*(pos(x,2)-pos(x,1)^2)^2;
end
%Find gbest and pbest
[minf,iminf]=min(obfun);
if minf<= fgbest
fgbest=minf; gbest=pos(iminf,:);
end
inewpb=find(obfun<=fpbest);
pbest(inewpb,:)=pos(inewpb,:); fpbest(inewpb)=obfun(inewpb);
end %end loop on iterations
[gbest,fgbest]