# Logic in fibonacci series

1 view (last 30 days)
Berghan on 7 Sep 2021
Commented: Dave B on 7 Sep 2021
I was looking around on the web and found this code that works as intended but im not sure why it works, could i get an explanation on how the function in the code works? I would like to get a deeper understanding of how the code works so that i can experiement with more advanced version's of it. (New to matlab)
clear
n = [1, 1];
for k = 3:10
n(k) = n(k-2)+n(k-1);
end
n

Dave B on 7 Sep 2021
You can imagine a for loop as running the contained code for each of the values that it's iterating over. Below, I've unpacked your loop by copying and pasting a few times, and I've removed the semicolons and added some more steps so we can see the output of each operation
n = [1 1]
n = 1×2
1 1
k = 3
k = 3
value_two_behind = n(k-2)
value_two_behind = 1
value_one_behind = n(k-1)
value_one_behind = 1
n(k) = value_two_behind + value_one_behind
n = 1×3
1 1 2
k = 4
k = 4
value_two_behind = n(k-2)
value_two_behind = 1
value_one_behind = n(k-1)
value_one_behind = 2
n(k) = value_two_behind + value_one_behind
n = 1×4
1 1 2 3
k = 5
k = 5
value_two_behind = n(k-2)
value_two_behind = 2
value_one_behind = n(k-1)
value_one_behind = 3
n(k) = value_two_behind + value_one_behind
n = 1×5
1 1 2 3 5
k = 6
k = 6
value_two_behind = n(k-2)
value_two_behind = 3
value_one_behind = n(k-1)
value_one_behind = 5
n(k) = value_two_behind + value_one_behind
n = 1×6
1 1 2 3 5 8
##### 2 CommentsShowHide 1 older comment
Dave B on 7 Sep 2021
when k is 5, n is [1 1 2 3] (just look at the last result for n, right above k=5)
n(5-2) is the same as n(3)
n(3) means 'the third element of n' which is quite plainly 2
n = [1 1 2 3]
n = 1×4
1 1 2 3
n(1)
ans = 1
n(2)
ans = 1
n(3)
ans = 2
n(4)
ans = 3

Jan on 7 Sep 2021
Edited: Jan on 7 Sep 2021
Do you know Matlab's debugger? Store the function in a script and open it in the editor. Then set a breakpoint on the left side. Now you can step through the code line by line either by pressing the corresponding icon in the menubar of the editor or by pressing F5.
You can remove the semicolon afer the line to let Matlab display the result of each line:
n = [1, 1]
for k = 3:10
n(k) = n(k-2) + n(k-1)
end
Examine, what the results of each line are to understand, what's going on.
There is a free online course to learn the Matlab basics: https://www.mathworks.com/learn/tutorials/matlab-onramp.html

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!