ERROR with PSO algorithm for two variable function
1 view (last 30 days)
Show older comments
I write this PSO algorithm. my algorithm worked for single variable Cost Function. However, when I want run this code for two variable Cost Function I see this error
Error in Iterativepso (line 43)
particle(i).cost=CostFunction(particle(i).position);
my code :
function [best_cost,best_particle,N_iter]=Iterativepso
clc; clear;
tic
npop=100; maxit=40; w=1; wdamp=0.98;
c1=2; c2=2;
xmin = [0.0001 0.0001]; % Lower band of parameter case30 xmax = [1 1];
nvar=size(xmin,2); dx=xmax-xmin;
vmax=0.1*dx;
empty_particle.position=[]; empty_particle.velocity=[]; empty_particle.cost=[]; empty_particle.pbest=[]; empty_particle.pbestcost=[];
particle=repmat(empty_particle,npop,1);
gbest=zeros(maxit,nvar); gbestcost=zeros(maxit,1);
for it=1:maxit if it==1 gbestcost(1)=inf; for i=1:npop particle(i).velocity=zeros(1,nvar); particle(i).position=xmin+(xmax-xmin).*rand(1,nvar); particle(i).cost=CostFunction(particle(i).position); particle(i).pbest=particle(i).position; particle(i).pbestcost=particle(i).cost;
if particle(i).pbestcost<gbestcost(it)
gbest(it,:)=particle(i).pbest;
gbestcost(it)=particle(i).pbestcost;
end
end
else
gbest(it,:)=gbest(it-1,:);
gbestcost(it)=gbestcost(it-1);
for i=1:npop
particle(i).velocity=w*particle(i).velocity...
+c1*rand*(particle(i).pbest-particle(i).position)...
+c2*rand*(gbest(it,:)-particle(i).position);
particle(i).velocity=min(max(particle(i).velocity,-vmax),vmax);
particle(i).position=particle(i).position+particle(i).velocity;
particle(i).position=min(max(particle(i).position,xmin),xmax);
particle(i).cost=CostFunction(particle(i).position);
if particle(i).cost<particle(i).pbestcost
particle(i).pbest=particle(i).position;
particle(i).pbestcost=particle(i).cost;
if particle(i).pbestcost<gbestcost(it)
gbest(it,:)=particle(i).pbest;
gbestcost(it)=particle(i).pbestcost;
end
end
end
end
w=w*wdamp;
end
best_particle=gbest(maxit,:);
best_cost=gbestcost(maxit);
N_iter=npop*maxit;
toc
0 Comments
Answers (0)
See Also
Categories
Find more on Particle Swarm in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!