Understanding BAT Algorithm--Part 1
- Adisorn O.
- Sep 27
- 2 min read
The Bat Algorithm (BA), proposed by Xin-She Yang in 2010, is a swarm intelligence method for global optimization inspired by the echolocation behavior of microbats. In nature, bats emit ultrasonic pulses and use the returning echoes to detect prey and obstacles. BA models this process by adjusting frequency, velocity, loudness, and pulse rate: frequencies guide global exploration, while decreasing loudness and increasing pulse rate intensify local exploitation near promising solutions.

The Pseudo code of BAT algortithm is shown below
Initialize bat population Xi, velocities Vi
Initialize frequency fi, loudness Ai, pulse rate ri
Evaluate fitness f(Xi) for all bats
Find global best X*
FOR t = 1 : MaxIter
FOR each bat i
Generate frequency fi
Update velocity: Vi = Vi + (Xi - X*) * fi
Update position: Xi = Xi + Vi
IF rand < ri (pulse rate test) THEN
% Exploitation (local search)
Xnew = X* + epsilon * mean(A)
ELSE
% Exploration (global search)
Xnew = Xi (already moved by velocity update)
END IF
Evaluate fitness f(Xnew)
IF f(Xnew) < f(Xi) AND rand < Ai THEN
Accept Xnew as Xi
Update Ai (reduce loudness)
Update ri (increase pulse rate)
END IF
IF f(Xnew) < f(X*) THEN
Update global best X*
END IF
END FOR
END FOR
Return global best solution X*
BAT comprises the exploration and exploitation phase, which is somewhat a hybrid of PSO and SA.
Exploration phase
FOR each bat i
Generate frequency fi
Update velocity: Vi = Vi + (Xi - X*) * fi
Update position: Xi = Xi + ViX* is the best solution (prey) so far
Exploitation phase
IF rand < ri (pulse rate test) THEN
% Exploitation (local search)
Xnew = X* + epsilon * mean(A)MATLAB Code
function bat_algorithm_demo
% Parameters
n = 20; % Population size (bats)
d = 2; % Dimension
N_gen = 1000; % Max generations
fmin = 0; fmax = 2; % Frequency range
alpha = 0.9; gamma = 0.9;
% Initialization
x = rand(n,d)*20 - 10; % Position in [-10,10]
v = zeros(n,d); % Velocities
fitness = sum(x.^2,2); % Objective (Sphere function)
[fmin_val, idx] = min(fitness);
best = x(idx,:);
A = ones(n,1); % Loudness
r = zeros(n,1); % Pulse rate
% Main loop
for t = 1:N_gen
for i = 1:n
% Frequency
beta = rand;
freq = fmin + (fmax-fmin)*beta;
% Update velocity & position
v(i,:) = v(i,:) + (x(i,:) - best)*freq;
x_new = x(i,:) + v(i,:);
% Local random walk
if rand < r(i)
x_new = best + 0.001*randn(1,d);
end
% Evaluate fitness
f_new = sum(x_new.^2);
% Accept if improved
if (f_new <= fitness(i)) && (rand < A(i))
x(i,:) = x_new;
fitness(i) = f_new;
A(i) = alpha*A(i);
r(i) = r(i)*(1-exp(-gamma*t));
end
% Update global best
if f_new < fmin_val
best = x_new;
fmin_val = f_new;
end
end
% Display iteration info
if mod(t,100)==0
fprintf('Iter %d, Best = %.6f\n', t, fmin_val);
end
end
fprintf('Final best solution = %.6f at [%s]\n', fmin_val, num2str(best));
end



