Logic in fibonacci series

2 Ansichten (letzte 30 Tage)
Berghan
Berghan am 7 Sep. 2021
Kommentiert: Dave B am 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

Akzeptierte Antwort

Dave B
Dave B am 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 Kommentare
Berghan
Berghan am 7 Sep. 2021
why does n(k-2)=2, when k=5
doesn't that mean n(5-2)=2? can't find the logic behind it
Dave B
Dave B am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 7 Sep. 2021
Bearbeitet: Jan am 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

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by