Particle swarm optimization algorithm for solving function extremum
Initializes a particle population randomly distributed in the solution space. Each iteration then updates the position of each particle according to the historical optimal position of each particle and the optimal position of the particle swarm until the requirement is met.
Clc;clear all;tic;% Program Run timinge0=0.001;% allowable Errormaxnum= -;% Particle maximum iteration countnarvs=1;the number of arguments for the% target functionParticlesize= -;% particle swarm sizec1=2;% Individual learning factor for each particle, also known as the acceleration constantC2=2;% of each particle's social learning factor, also known as the acceleration constantw=0.6;% inertia factorvmax=0.8;% particle maximum speed of flightx=-5+Ten*Rand(Particlesize,narvs);where the% particles are locatedv=2*Rand(Particlesize,narvs);% particle speed of flight% use inline to define the fitness function so that the child function file is placed with the main program file,the% target function is: y=1+ (2.1* (1-x+2*x.^2). *exp (-X.^2/2))The %inline command defines the fitness function as follows:Fitness=inline (' 1/(1+ (2.1* (1-x+2*x.^2). *exp (-X.^2/2))) ',' x ');%inline defined fitness function can make the program run much less quickly for I=1:p articlesize for J=1: Narvs F (I) =fitness (X (I,J));EndEndPersonalbest_x=x;personalbest_faval=f;[Globalbest_faval i]=min (Personalbest_faval); Globalbest_x=personalbest_x (I,:); k=1; whileK<=maxnum for I=1:p articlesize for J=1: Narvs F (I) =fitness (X (I,J));End ifFI) <personalbest_faval (I)% determine if the current position is the best location in historyPersonalbest_faval (I) =f (I); Personalbest_x (I,:) =x (I,:);End End [Globalbest_faval i]=min (Personalbest_faval); Globalbest_x=personalbest_x (I,:); for I=1:p articlesize% update the newest position of each individual in the particle swarmVI,:) =w*v (I,:) +c1*Rand* (Personalbest_x (I,:)-X (I,:)) ... +c2*Rand* (Globalbest_x-x (I,:)); for J=1: Narvs% determine if the particle is flying faster than the maximum flight speed ifVI,J) >vmax; VI,J) =vmax;ElseIfVI,J) <-vmax; VI,J) =-vmax;End EndXI,:) =x (I,:) +v (I,:);End if ABS(Globalbest_faval) <e0, Break,Endk=k+1;Endvalue1=1/globalbest_faval-1; Value1=num2str (Value1);% strcat instruction enables combination output of charactersdisp(Strcat (' The maximum value ',' = ', Value1));the horizontal axis position where the maximum output value isvalue2=globalbest_x; Value2=num2str (Value2);disp(Strcat (' The corresponding coordinate ',' = ', Value2)); x=-5:0.01:5; y=2.1*(1-x+2*x.^2).*Exp(-x.^2/2);p lot (x, Y,' m ',' LineWidth ',3); hold On;plot (globalbest_x,1/globalbest_faval-1,' KP ',' LineWidth ',4); Legend (' target function ',' maximum value searched '); Xlabel (' x '); Ylabel (' y '); grid On;toc;
The results of the program run are as follows (reference fitness function)
PSO Algorithm for solving optimization problems (MATLAB)