Matlab code for swarm particle algorithm

%initialisation, initialising parameters

iterations = 100; %100 iterations code will repeat 100 times

inertia = 1.0;

correction_factor = 2.0;

Particles = 500;

%particle positions

Particle=zeros(500,7); %create a huge matrix of 0 values for each particle

%500 particles will be used with 7 columns to call from

%the 7 columns are assosiated with the changing

%parameters of each particle.

%coulmn 1 and 2 represent particle position u and v

%respectively

%column 3 and 4 represent particle velocity u and v

%respectively

%column 5 and 6 represent the calculated values in the

%velocity calculator that will then be used to change 3

%and 4

%column 7 is best position

counter = 1;

for i = 1 : 500

Particle(counter, 1:7) = i;

counter = counter + 1;

end

Particle(:, 7) = 1000; % Greater than maximum possible, this will reduce as the particle gets closer to the objective function

Particle(:, 5) = 0; % initial u velocity

Particle(:, 6) = 0; % initial v velocity

% Iterations

for iter = 1 : iterations

%position of Particles

for i = 1 : Particles

Particle(i, 1) = Particle(i, 1) + Particle(i, 5)/1.2 ; %update u position

Particle(i, 2) = Particle(i, 2) + Particle(i, 6)/1.2 ; %update v position

u = Particle(i, 1);

v = Particle(i, 2);

ObjF = (u – 120)^2 + (v – 350)^2; %Objective Function/ Fitness function

if ObjF < Particle(i, 7) % True if value isnt exactly the objecive function
Particle(i, 3) = Particle(i, 1); % update best position of u with velocity,

Particle(i, 4) = Particle(i, 2); % update best postion of v with velocity,

Particle(i, 7) = ObjF; % best updated minimum value

end

end

[temp, gbest] = min(Particle(:, 7)); % group best position

%Velocity change

for i = 1 : Particles

Particle(i, 5) = rand*inertia*Particle(i, 5) + correction_factor*rand*(Particle(i, 3)- Particle(i, 1)) +
correction_factor*rand*(Particle(gbest, 3) – Particle(i, 1)); % u velocity

Particle(i, 6) = rand*inertia*Particle(i, 6) + correction_factor*rand*(Particle(i, 4)- Particle(i, 2)) +
correction_factor*rand*(Particle(gbest, 4) – Particle(i, 2)); % v velocity

end

% Plot

plot(Particle(:, 1), Particle(:, 2), ‘x’)

axis([-1000 1000 -1000 1000])

pause(0.1)

end