www.gusucode.com > 基于matlab编程斯坦纳树的配电网规划研究程序 > 基于matlab编程斯坦纳树的配电网规划研究程序/code/PSO.m

    function [xm,fv,fvt]=PSO(fitness,popsize,c1,c2,w,MAXITER,dimension,irange_r,irange_l,xmax,xmin)
format long;
%------初始化种群的个体------------
x=(irange_r- irange_l)*rand(popsize,dimension,1) + irange_l;
%         x(i,j)=randn;  %随机初始化位置
v=(rand(popsize,dimension,1)-0.5)*(irange_r- irange_l);  %随机初始化速度
pbest=x;
gbest=zeros(1,dimension);
%------先计算各个粒子的适应度,并初始化Pi和Pg----------------------
for i=1:popsize
    f_x(i)=fitness(x(i,:));
    f_pbest(i)=f_x(i);
end
g=min(find(f_pbest==min(f_pbest(1:popsize))));
gbest=pbest(g,:);
f_gbest=f_pbest(g);
MINIUM=f_pbest(g);
fvt=ones(1,MAXITER);
%------进入主要循环,按照公式依次迭代------------
for t=1:MAXITER
    for i=1:popsize
        v(i,:)=w*v(i,:)+c1*rand*(pbest(i,:)-x(i,:))+c2*rand*(gbest-x(i,:));
        y1=x(i,:)+v(i,:);
%         y1=min(y,xmax);
        x(i,:)=max(min(y1,xmax),xmin);
        f_x(i)=fitness(x(i,:));
        if f_x(i)<f_pbest(i)
            pbest(i,:)=x(i,:);
            f_pbest(i)=f_x(i);
        end
        if f_pbest(i)<f_gbest
            gbest=pbest(i,:);
            f_gbest=f_pbest(i);
        end
        MINIUM=f_gbest;
    end
    fvt(t)=MINIUM;
    disp(t)
    disp(gbest')
    disp(MINIUM)
end
xm = gbest';
fv = f_gbest;