# Firefly Algorithm (FA) in MATLAB

URL: https://yarpiz.com/firefly-algorithm-ypea112
Author: Mostapha Kalami Heris
Published: 2015-09-06
Updated: 2026-10-30
Topics: Metaheuristics

> Run the Firefly Algorithm in MATLAB with distance-based attraction, shrinking random steps, bound handling, and benchmark functions.

The Firefly Algorithm (FA) is a metaheuristic algorithm for global optimization, inspired by the flashing behavior of [fireflies](https://en.wikipedia.org/wiki/Firefly). It was proposed by Xin-She Yang in 2008.

In nature, fireflies flash to attract other fireflies, usually to send signals to the opposite sex. In the mathematical model of FA, all fireflies are unisex, so any firefly can attract any other.

The attractiveness of a firefly is proportional to its brightness, and brightness comes from the objective function: a firefly with a lower cost is brighter. For any pair of fireflies, the brighter one attracts the other, so the less bright one moves toward the brighter one. This is done for every pair of fireflies in the population on every iteration. For more information, see the [Wikipedia article on the Firefly Algorithm](https://en.wikipedia.org/wiki/Firefly_algorithm).

## How FA works

Light seen from a distance gets weaker, because the air absorbs part of it. FA models this with an attractiveness that falls with the distance $r_{ij}$ between fireflies $i$ and $j$:

$$
\beta(r_{ij}) = \beta_0\, e^{-\gamma r_{ij}^2}
$$

Here $\beta_0$ is the attractiveness at distance zero, and $\gamma$ is the light absorption coefficient. A small $\gamma$ lets every firefly see every other one, and a large $\gamma$ makes the search more local.

When firefly $j$ is brighter than firefly $i$, firefly $i$ moves toward it:

$$
x_i \leftarrow x_i + \beta(r_{ij})\,(x_j - x_i) + \alpha\,\varepsilon_i
$$

The second term pulls $i$ toward $j$. The last term is a random step: $\varepsilon_i$ is a random vector, and $\alpha$ sets the size of the step. In a basic version of the model, the brightest firefly has no brighter neighbor to follow and may take a random step. The implementation below instead retains it through elitist selection.

## Implementation in MATLAB

This post shares an open-source MATLAB implementation of the Firefly Algorithm (FA). If you know MATLAB, you should find it easy to use in your research and projects.

### What is in the download

The `Firefly Algorithm` folder holds these files:

- `fa.m`: the FA script, with the problem definition, the parameters, the main loop and the results.
- `Rosenbrock.m`: the cost function used by default.
- `Sphere.m` and `Ackley.m`: two more test functions you can use instead.
- `main.m`: a one line entry point that runs `fa.m`.

To run the code, open the `Firefly Algorithm` folder in MATLAB and run `main.m`. The program prints the best cost of every iteration and then plots the best cost against the iteration number on a logarithmic scale.

The script creates the first fireflies with `unifrnd`, a function of the Statistics and Machine Learning Toolbox, so it probably needs that toolbox.

### Parameters in the code

| Parameter | Meaning | Value |
| --- | --- | ---: |
| `nVar` | Number of decision variables | 5 |
| `VarMin`, `VarMax` | Lower and upper bounds of the variables | $-10$, $10$ |
| `MaxIt` | Maximum number of iterations | 1000 |
| `nPop` | Number of fireflies | 25 |
| `gamma` | Light absorption coefficient | 1 |
| `beta0` | Attractiveness at distance zero | 2 |
| `alpha` | Size of the random step | 0.2 |
| `alpha_damp` | Damping ratio of `alpha` | 0.98 |
| `delta` | Range of the uniform random step | $0.05\,(\text{VarMax} - \text{VarMin})$ |
| `m` | Exponent of the distance | 2 |

### Details of this implementation

The code follows the model above, with a few practical choices:

- The distance $r_{ij}$ is divided by `dmax`, the diagonal of the search space, so it lies between 0 and 1 whatever the bounds are.
- The attraction $\beta$ is multiplied by a vector of uniform random numbers in $[0, 1]$, one for each variable.
- The random step is $\alpha\,\delta\,u$, where $u$ is uniform in $[-1, 1]$. A Gaussian step is also in the code as a commented line. The value of `alpha` is multiplied by `alpha_damp` after every iteration, so the random steps shrink over time.
- Each firefly keeps the best of the moves it made toward brighter fireflies in that iteration. The new fireflies are then merged with the old ones, and the best `nPop` are kept. This keeps the best solutions from one iteration to the next. The brightest firefly makes no random move in the code, and the merge step keeps it.
- Positions outside the bounds are set back to the nearest bound.

To solve your own problem, write a cost function that takes a row vector and returns a number, and set `CostFunction`, `nVar`, `VarMin` and `VarMax` in the problem definition section of `fa.m`.

## Check the result

Start with the default Rosenbrock problem and inspect both the cost and the coordinates of the best solution. The normalized distance and random-step scale depend on the variable ranges, so review them when changing the bounds. Each iteration considers pairs of fireflies, which makes population size important for computational work. Compare repeated runs and evaluation counts rather than a single final convergence curve.

## Related posts

- [YPEA](https://yarpiz.com/yarpiz-evolutionary-algorithms-ypea) is a MATLAB toolbox that includes FA and 14 other algorithms that share one problem definition.
- [Particle Swarm Optimization in MATLAB](https://yarpiz.com/particle-swarm-optimization-ypea102) is another swarm based method with the same code structure.

## How to cite

Mostapha Kalami Heris, Firefly Algorithm (FA) in MATLAB (YPEA112), Yarpiz, 2015. https://yarpiz.com/firefly-algorithm-ypea112
