做者:凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/html
粒子羣優化算法求解函數y=x+x*sin(x)在[-10, 10]的最大值.算法
pso.mdom
function [best_x, best_y]=pso() %find the max value of a function %Author: kailugaji https://www.cnblogs.com/kailugaji/ posMax=10;posMin=-10; %range of feasible solution x=posMin:0.1:posMax; y=my_fun(x); %object function plot(x,y);hold on; %plot function popsize=30; %number of particles max_iter=100; %maximum number of iterations position=rand(popsize,1); position=position*20-ones(popsize,1)*10; %particle's position vMax=1;vMin=-1; %range of velocity velosity=2*rand(popsize,1)-1; %path direction pbest=position; %current optimum gbest=position(1); %global optimum wBegin=1;wEnd=0.05; c1=2; %weight of local information c2=2; %weight of global information for i=1:max_iter position_new=position+velosity; %change direction of each particle velosity_new=(wEnd+(wBegin-wEnd)*(100-i)/100).*velosity+c1*rand().*(position-pbest.*ones(popsize,1))+c2*rand().*(position-gbest.*ones(popsize,1)); %inertia+personal influence+social influence for j=1:popsize if(position_new(j)>posMax) position_new(j)=posMax; end if(position_new(j)<posMin) position_new(j)=posMin; end if(velosity_new(j)>vMax) velosity_new(j)=vMax; end if(velosity_new(j)<vMin) velosity_new(j)=vMin; end if(my_fun(position_new(j))>my_fun(pbest(j))) pbest(j)=position_new(j); end if(my_fun(position_new(j))>my_fun(gbest)) gbest=position_new(j); end end position=position_new; velosity=velosity_new; end plot(gbest,my_fun(gbest),'or'); best_x=gbest; best_y=my_fun(gbest);
my_fun.m函數
function y=my_fun(x) y=x+x.*sin(x);
>> [best_x, best_y]=pso() best_x = 8.0051 best_y = 15.9190
當x=8.0051時,粒子羣優化算法終止迭代,此時得到的最大值爲y=15.9190。優化