Logic in fibonacci series
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Dave B
2021년 9월 7일
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
추가 답변 (1개)
Jan
2021년 9월 7일
편집: Jan
2021년 9월 7일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!