Logic in fibonacci series

조회 수: 3 (최근 30일)
Berghan
Berghan 2021년 9월 7일
댓글: Dave B 2021년 9월 7일
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
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]
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
Berghan
Berghan 2021년 9월 7일
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 2021년 9월 7일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by