HOWTO · MATLAB

How to Calculate Fibonacci Sequence in MATLAB

Use MATLAB fibonacci() to calculate one Fibonacci value, generate a vector of values, and represent a large result symbolically.

On this page

Use MATLAB’s fibonacci() function to calculate a single Fibonacci value or apply it to a vector of indices. For a large result, pass a symbolic index created with sym() to keep the value exact. These functions require Symbolic Math Toolbox.

Generate a Fibonacci number in MATLAB

In the Fibonacci sequence, each value after the first two is the sum of the previous two. This article uses the convention F₁ = 1 and F₂ = 1, so Fₙ = Fₙ₋₁ + Fₙ₋₂ for n ≥ 3. The index n identifies a position in the sequence; it is not the number of values to generate.

To calculate the tenth value, enter fn = fibonacci(10). With this sequence convention, the result is 55. The MATLAB call is shown inline because the configured execution environment does not run MATLAB; its output has not been independently executed here.

Generate a Fibonacci sequence with a vector

Pass a vector of indices to fibonacci() to get the corresponding values in one call. For the first ten values, use v = 1:10; fn = fibonacci(v). This produces the row vector [1 1 2 3 5 8 13 21 34 55]. The entries in v are sequence positions, and each result element corresponds to the index in the same position.

The MATLAB expression is provided inline rather than in an executable code fence because MATLAB is not among the available runtimes for this article. The listed values follow the recurrence and the F₁ = F₂ = 1 convention above.

Represent large Fibonacci numbers symbolically

A numeric result for a large index can display in scientific notation, which rounds the displayed digits. To keep the exact integer, make the index symbolic before calling fibonacci(): fn = fibonacci(sym(300)). For comparison, fibonacci(300) returns a numeric value displayed approximately as 2.2223e+62, while the symbolic call represents the exact 300th Fibonacci value, 222232244629420445529739893461909967206666939096499764990979600.

The symbolic result is useful when you need the full integer rather than a floating-point approximation. See the MathWorks fibonacci documentation for details about the function. The MATLAB examples in this article are unexecuted in the configured runtime.