pso algorithm in matlab

Here is an example implementation of the Particle Swarm Optimization (PSO) algorithm in MATLAB:

main.m
% Define objective function
f = @(x) sum(x.^2);

% Define PSO parameters
num_dims = 2;
num_particles = 20;
max_iter = 100;
w = 0.7;
c1 = 1.5;
c2 = 1.5;
lb = -10 * ones(1, num_dims);
ub = 10 * ones(1, num_dims);

% Initialize particles
pos = lb + rand(num_particles, num_dims) .* (ub - lb);
vel = zeros(num_particles, num_dims);
best_pos = pos;
best_val = inf(num_particles, 1);

% Run PSO algorithm
for iter = 1:max_iter
    % Evaluate objective function
    vals = f(pos);
    
    % Update personal best
    update = vals < best_val;
    best_val(update) = vals(update);
    best_pos(update, :) = pos(update, :);
    
    % Update global best
    [global_best_val, global_best_idx] = min(best_val);
    global_best_pos = best_pos(global_best_idx, :);
    
    % Update velocity and position
    r1 = rand(num_particles, num_dims);
    r2 = rand(num_particles, num_dims);
    vel = w * vel + c1 * r1 .* (best_pos - pos) + c2 * r2 .* (global_best_pos - pos);
    pos = pos + vel;
    
    % Enforce bounds
    pos = max(pos, lb);
    pos = min(pos, ub);
end

% Print results
disp(['Best solution: ', num2str(global_best_pos)]);
disp(['Best objective value: ', num2str(global_best_val)]);
1188 chars
48 lines

In this example, the PSO algorithm is used to minimize the sum of squares objective function. The algorithm is implemented using the standard PSO equations for updating particle velocity and position, with parameters for inertia weight (w), cognitive coefficient (c1), and social coefficient (c2) set to reasonable values based on prior research. The algorithm runs for a specified number of iterations, with the best solution and objective value printed at the end of the run.

gistlibby LogSnag