Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
To generate the Fibonacci sequence in MATLAB, preallocate a vector with zeros, set the first two elements to 1, and fill the rest with a for loop that adds the previous two elements. A recursive function in its own file (fibnum.m) gives the same numbers and mirrors the mathematical definition, but it repeats work and is far slower. A closed-form expression based on the golden ratio works for small n only. All three run on double-precision numbers, so every method stops being exact once the values pass 253, which happens between F(78) and F(79).
This page uses the convention F(1) = 1, F(2) = 1 and F(n) = F(n-1) + F(n-2). Some texts start the sequence at F(0) = 0. MATLAB arrays are indexed from 1, so the code below stores F(n) in element n. The numeric claims about precision are checked by the arithmetic shown, and the MATLAB behaviours are taken from the MathWorks documentation listed under Sources.
What it is used for in research
The Fibonacci sequence is a standard teaching example for loops, recursion, function files and numerical precision, which is why it appears in introductory MATLAB courses and in research-computing training for new analysts. In a research workflow the sequence itself is rarely the end product. What transfers is the pattern: a quantity computed from earlier values (a recurrence), a choice between an iterative and a recursive implementation, and awareness that floating-point numbers have a finite exact range. If you are deciding whether MATLAB is the right environment for numerical work in the first place, see the comparison MATLAB vs R. For documenting code so that others can rerun it, see computational reproducibility.
How to install or access it
MATLAB is a MathWorks product, and its documentation is published at mathworks.com/help/matlab. Licensing is arranged through MathWorks or through your institution, so check with your research computing or IT office what your institution provides. GNU Octave is a free alternative: its project page states that the Octave language is mostly compatible with MATLAB and that Octave is freely redistributable under the GNU General Public License (octave.org/about). The loop and function-file code below uses only basic syntax; the numbers quoted in the text come from separate exact-integer and double-precision arithmetic checks, so compare them with your own session’s output.
Step-by-step: three ways to compute the sequence
Method 1: a for loop with preallocation
The MathWorks for reference gives the syntax for index = values, statements, end, and advises avoiding assigning a value to the index variable inside the loop. The MathWorks page on preallocating arrays says that code often runs faster if you allocate the maximum space an array needs up front, and that growing an array inside a loop can hurt performance and memory use. Applied to Fibonacci, you know the length (n) in advance, so allocate it with zeros.
- Open the MATLAB Editor or the Command Window.
- Set how many terms you want:
n = 20;(this loop needs n of at least 2). - Preallocate:
F = zeros(1, n); - Seed the first two terms:
F(1) = 1;andF(2) = 1; - Fill the rest:
for k = 3:n F(k) = F(k-1) + F(k-2); end - Display the result with
disp(F), or typeFwithout a semicolon.
The whole script, to paste in one block:
n = 20;
F = zeros(1, n);
F(1) = 1;
F(2) = 1;
for k = 3:n
F(k) = F(k-1) + F(k-2);
end
disp(F)
Method 2: a recursive function in its own file
The MathWorks page on creating functions in files states that a function must be defined within a file, not at the command line, and recommends giving the function and the file the same name. Save the following as fibnum.m in your current folder:
function f = fibnum(n)
% FIBNUM n-th Fibonacci number, with F(1) = F(2) = 1.
if n <= 2
f = 1;
else
f = fibnum(n-1) + fibnum(n-2);
end
end
Then call it from the Command Window with fibnum(10). The first function in a file is the main function that other code can call, and any further functions in that file are local functions. If you prefer to keep the recursive function inside a script, the same page says that local functions in scripts must be defined at the end of the file, after the last line of script code (the page labels this as the behaviour before R2024a, so confirm the rule for your release in the current documentation).
Method 3: the closed-form (golden ratio) expression
The closed form is the Binet formula, F(n) = round(φn / √5) with φ = (1 + √5) / 2. In MATLAB:
n = 30;
F = round(((1 + sqrt(5)) / 2)^n / sqrt(5))
It needs no loop and no recursion, and it evaluates each term independently. The cost is that it relies on floating-point powers. In a separate check using IEEE double-precision arithmetic, the formula reproduced the exact values for n = 10, 20, 30, 50 and 70 (55, 6765, 832040, 12586269025 and 190392490709135) but returned 8944394323791488 for n = 78, where the exact value is 8944394323791464. The exact result differs in the last digits, so treat this method as a convenience for small n. A MATLAB session may differ from that check in the final digits because of how ^ is evaluated, which is another reason to avoid it for large n.
Output and how to read it
For n = 20, the loop prints one row of 20 values beginning 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and ending with 4181 and 6765, with the ordering following the index: element 10 is 55 and element 20 is 6765. How the row is laid out on screen depends on your display settings, so match the values, not the spacing.
Where double precision stops being exact
MATLAB’s numeric default is double, built on IEEE 754 double precision. The MathWorks flintmax page says it returns the largest consecutive integer in IEEE double precision, 253 = 9007199254740992, and that above that value not every integer can be represented exactly. Comparing the Fibonacci numbers with that limit (exact integer arithmetic, run outside MATLAB):
- F(77) = 5527939700884757 and F(78) = 8944394323791464 are both below 253.
- F(79) = 14472334024676221 is above 253; being odd, it cannot be represented exactly as a double.
- F(80) = 23416728348467685 is also above 253 and odd, so it too is not exactly representable.
So with double, the loop and the recursion give exact terms through n = 78, and from n = 79 the stored values may be rounded. The upper bound for any double is far higher (the MathWorks double page gives realmax as about 1.7977e+308), so MATLAB will keep returning numbers well beyond n = 78; they are just no longer guaranteed to be the exact integers. If you need exact large terms, the exactness limit is a reason to move to an integer or arbitrary-precision type instead of relying on double.
Why the recursive version is slower
The naive recursive function calls itself twice per step. With the base case F(1) = F(2) = 1, the number of function calls needed for F(n) is 2·F(n) − 1. That gives 109 calls for n = 10, 13,529 for n = 20, 92,735 for n = 24 and 1,664,079 for n = 30 (counts computed by the recurrence calls(n) = calls(n−1) + calls(n−2) + 1). The loop, in contrast, does one addition per term. The call count grows by about 1.6 times for each extra n, which is why recursion is fine for teaching n = 10 and impractical for n = 50.
Timing it yourself
The MathWorks tic page documents the pair tic / toc, and also tStart = tic with tEnd = toc(tStart). It also notes that if the code under test runs for less than about a tenth of a second, you should time it inside a loop and average the result. A simple comparison:
tic
fibnum(24);
toc
Run the same with the loop version (wrap it in a function so the comparison is fair) and compare elapsed times on your own machine. The page also says not to time timeit with tic/toc.
Data table: the double-precision limit and recursion cost
The data table below lists selected terms, whether each is below the flintmax limit, and how many calls the naive recursive function needs. Use it to choose n for a demonstration and to know when to stop trusting double results.
Choosing a method
| Method | Files needed | Cost for n terms | Main limit |
|---|---|---|---|
for loop with zeros |
One script or function | One addition per term; preallocation avoids growing the array | Exact only while terms stay below 253 (through n = 78) |
| Recursive function | One function file named after the function | 2·F(n) − 1 calls for F(n) | Impractical for larger n; same 253 limit |
| Closed form (Binet) | None | One power and one rounding per term | Checked as exact only up to n = 70 in double arithmetic; wrong in the last digits by n = 78 |
Troubleshooting
Calling fibnum fails
The function must be defined within a file, not typed at the command line, and the file name should match the function name. Check that fibnum.m is saved in the current folder or on the MATLAB path and that the name is spelled identically. MATLAB ties the program to the file name, so a mismatch means the file name is what gets called.
Index errors in the loop version
If n is 1, zeros(1, 1) holds one element, so assigning F(2) = 1 makes the vector longer than you asked for, and the loop range 3:n is empty. Handle n of 1 separately, for example by returning F(1) alone, if your code accepts any n.
The loop seems to ignore changes to the index
MathWorks advises not assigning to the loop index inside the loop. Keep the loop variable read-only and write results into F(k).
The recursion takes minutes
That is the expected cost, not a bug: see the call counts above. Use the loop for n above about 30.
Large terms print as rounded values
Past n = 78 the values are doubles that may not be exact integers. Check the flintmax limit before using a large term in further calculations, and see the data table.
Free alternatives
| Alternative | What the source says | Source |
|---|---|---|
| GNU Octave | Language is mostly compatible with MATLAB; freely redistributable under the GNU General Public License | octave.org/about, read 2026-11-12 |
Because compatibility is described as “mostly”, test your function file in Octave before relying on it for a project that must run in both. A reproducibility note on sharing code that others will rerun is in computational reproducibility. The sequence also appears in reference databases of integer sequences; see the CASRAI guide to the OEIS.
FAQ
How do I generate the Fibonacci sequence in MATLAB?
Preallocate F = zeros(1, n), set F(1) = 1 and F(2) = 1, then run for k = 3:n with F(k) = F(k-1) + F(k-2). Preallocation follows the MathWorks guidance on avoiding arrays that grow inside loops.
Can I write the Fibonacci function recursively in MATLAB?
Yes. Save a function named fibnum in fibnum.m, with f = 1 for n of 2 or less and fibnum(n-1) + fibnum(n-2) otherwise. It needs 2·F(n) − 1 calls for F(n), so it is slow for n above about 30.
Why can’t I define the function at the command line?
MathWorks states that a function must be defined within a file, not at the command line. Use a function file, or a local function at the end of a script (see the release note on local functions in scripts above).
What is the largest Fibonacci number MATLAB computes exactly?
With double, exact through F(78) = 8944394323791464, because F(79) exceeds the 253 value that flintmax reports as the largest consecutive integer in double precision.
How do I time the Fibonacci code?
Use tic before and toc after the code. If it runs faster than about a tenth of a second, repeat it in a loop and average.
Is there a free way to run this code?
GNU Octave is described as mostly compatible with MATLAB and is freely redistributable under the GNU GPL. Test the code in it before relying on identical behaviour.
Sources
- MathWorks, “for” (MATLAB documentation), https://www.mathworks.com/help/matlab/ref/for.html, read 2026-11-12.
- MathWorks, “Create Functions in Files”, https://www.mathworks.com/help/matlab/matlab_prog/create-functions-in-files.html, read 2026-11-12.
- MathWorks, “tic”, https://www.mathworks.com/help/matlab/ref/tic.html, read 2026-11-12.
- MathWorks, “Preallocating Arrays”, https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html, read 2026-11-12.
- MathWorks, “flintmax”, https://www.mathworks.com/help/matlab/ref/flintmax.html, read 2026-11-12.
- MathWorks, “double”, https://www.mathworks.com/help/matlab/ref/double.html, read 2026-11-12.
- GNU Octave, “About”, https://octave.org/about, read 2026-11-12.
- Terms, call counts and Binet-formula results on this page were computed with exact integer arithmetic and IEEE double-precision arithmetic, 2026-11-12.
Data: Fibonacci terms against the double-precision exact-integer limit, with naive recursion call counts
Selected Fibonacci numbers F(n) with F(1)=F(2)=1, computed with exact integer arithmetic, compared with the flintmax value 2^53 documented by MathWorks, plus the number of function calls 2F(n)-1 that a naive two-branch recursive function needs. Compiled from the MathWorks flintmax documentation and exact arithmetic.
| n | F(n), exact integer | F(n) below 2^53 (flintmax) | Calls for naive recursion, 2F(n)-1 |
|---|---|---|---|
| 10 | 55 | yes | 109 |
| 20 | 6765 | yes | 13529 |
| 24 | 46368 | yes | 92735 |
| 30 | 832040 | yes | 1664079 |
| 50 | 12586269025 | yes | 25172538049 |
| 70 | 190392490709135 | yes | 380784981418269 |
| 78 | 8944394323791464 | yes | 17888788647582927 |
| 79 | 14472334024676221 | no | 28944668049352441 |
| 80 | 23416728348467685 | no | 46833456696935369 |
Sources
- MathWorks: flintmax (accessed 2026-11-12)
- MathWorks: double (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







