Logic in fibonacci series
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
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]
k = 3
value_two_behind = n(k-2)
value_one_behind = n(k-1)
n(k) = value_two_behind + value_one_behind
k = 4
value_two_behind = n(k-2)
value_one_behind = n(k-1)
n(k) = value_two_behind + value_one_behind
k = 5
value_two_behind = n(k-2)
value_one_behind = n(k-1)
n(k) = value_two_behind + value_one_behind
k = 6
value_two_behind = n(k-2)
value_one_behind = n(k-1)
n(k) = value_two_behind + value_one_behind
2 Kommentare
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)
n(2)
n(3)
n(4)
Weitere Antworten (1)
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!